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.ok {
2122        bail!("gh pr view {pr_url}: {}", view.combined());
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.stdout)?.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    find_open_pr_with(Path::new("gh"), repo, branch, base).await
2268}
2269
2270pub(crate) async fn find_open_pr_with(
2271    program: &Path,
2272    repo: &Path,
2273    branch: &str,
2274    base: &str,
2275) -> Result<OpenPr> {
2276    let out = gh_with(
2277        program,
2278        repo,
2279        &[
2280            "pr".to_owned(),
2281            "list".to_owned(),
2282            "--head".to_owned(),
2283            branch.to_owned(),
2284            "--base".to_owned(),
2285            base.to_owned(),
2286            "--state".to_owned(),
2287            "open".to_owned(),
2288            "--json".to_owned(),
2289            "number,url,title,baseRefName,isCrossRepository".to_owned(),
2290        ],
2291    )
2292    .await?;
2293    if !out.ok {
2294        bail!("gh pr list failed: {}", out.combined());
2295    }
2296    pick_open_pr(&out.stdout, base)
2297}
2298
2299#[derive(Debug, Deserialize)]
2300#[serde(rename_all = "camelCase")]
2301struct GhPrHead {
2302    head_ref_name: String,
2303    base_ref_name: String,
2304    state: String,
2305    // Required, like `GhOpenPr`'s fields: a record that cannot say whether the
2306    // head lives in a fork must be a parse error, never "same repository".
2307    is_cross_repository: bool,
2308    // Required too: it is what ties the pull request to the commits that were
2309    // actually proven to be on the base.
2310    head_ref_oid: String,
2311}
2312
2313/// Why [`closable`] said no, and whether asking again later could say yes.
2314#[derive(Debug, Clone, PartialEq, Eq)]
2315pub struct Refusal {
2316    /// A later attempt may succeed (the head moved, the view was unreadable);
2317    /// `false` means this pull request is simply not the run's to close.
2318    pub retry: bool,
2319    /// What was wrong.
2320    pub why: String,
2321}
2322
2323impl Refusal {
2324    fn final_(why: String) -> Self {
2325        Self { retry: false, why }
2326    }
2327}
2328
2329/// Pure half of [`close_superseded_pr`]: read `gh pr view --json
2330/// headRefName,baseRefName,state,isCrossRepository` and say whether closing
2331/// is safe, `Err` carrying the reason when it is not.
2332///
2333/// Closing is outward-facing, so every property is checked on what the forge
2334/// says now, not on what magi recorded: the head must be exactly `branch` in
2335/// this repository (a fork's branch of the same name is somebody else's), the
2336/// base must be `base`, and the pull request must still be open.
2337pub fn closable(
2338    json: &str,
2339    branch: &str,
2340    base: &str,
2341    verified: &[String],
2342) -> std::result::Result<(), Refusal> {
2343    let pr: GhPrHead = serde_json::from_str(json).map_err(|e| Refusal {
2344        retry: true,
2345        why: format!("could not read the pull request ({e})"),
2346    })?;
2347    if pr.head_ref_name != branch {
2348        return Err(Refusal::final_(format!(
2349            "its head is `{}`, not this run's `{branch}`",
2350            pr.head_ref_name
2351        )));
2352    }
2353    if pr.is_cross_repository {
2354        return Err(Refusal::final_("its head lives in a fork".to_owned()));
2355    }
2356    if pr.base_ref_name != base {
2357        return Err(Refusal::final_(format!(
2358            "it targets `{}`, not `{base}`",
2359            pr.base_ref_name
2360        )));
2361    }
2362    if !pr.state.eq_ignore_ascii_case("open") {
2363        return Err(Refusal::final_(format!(
2364            "it is already {}",
2365            pr.state.to_ascii_lowercase()
2366        )));
2367    }
2368    // Last, so a pull request that is not this run's at all is reported as
2369    // such. A head that is this branch but not a commit checked against the
2370    // base (somebody pushed since) may well get checked next time: retry.
2371    if !verified.contains(&pr.head_ref_oid) {
2372        return Err(Refusal {
2373            retry: true,
2374            why: format!(
2375                "its head {} is not a commit this run checked against the base",
2376                crate::already::short_sha(&pr.head_ref_oid)
2377            ),
2378        });
2379    }
2380    Ok(())
2381}
2382
2383/// Does `remote` point at something a forge could host - a URL or an scp-style
2384/// `user@host:path` - rather than a filesystem path or nothing at all? Judged
2385/// from the URL alone, so it answers the same on every machine, whatever `gh`
2386/// happens to be installed or logged in to.
2387async fn remote_is_forge(repo: &Path, remote: &str) -> bool {
2388    let Ok(url) = git::git(repo, &["remote", "get-url", remote]).await else {
2389        return false;
2390    };
2391    is_forge_url(url.trim())
2392}
2393
2394fn is_forge_url(url: &str) -> bool {
2395    url.contains("://") && !url.starts_with("file://")
2396        || url
2397            .split_once(':')
2398            .is_some_and(|(host, _)| host.contains('@') && !host.contains(['/', '\\']))
2399}
2400
2401/// Does this `gh` failure mean there is no GitHub to ask, as opposed to a
2402/// request that failed?
2403fn forge_unavailable(message: &str) -> bool {
2404    message.contains("known GitHub host") || message.contains("spawn gh")
2405}
2406
2407/// The comment left on a pull request closed because its change is already on
2408/// the base.
2409pub fn superseded_comment(base: &str, evidence: &crate::already::Evidence) -> String {
2410    let how = match evidence.proof {
2411        crate::already::Proof::PatchId => format!(
2412            "carried by commit {} on `{base}` with the same patch",
2413            evidence.names()
2414        ),
2415        crate::already::Proof::Ancestry => {
2416            format!("already in the history of `{base}` as {}", evidence.names())
2417        }
2418        crate::already::Proof::Tree => format!(
2419            "already part of `{base}` (merging this branch changes nothing at {})",
2420            crate::already::short_sha(&evidence.tip)
2421        ),
2422    };
2423    format!(
2424        "Closing: everything this branch adds is {how}, so there is nothing left to \
2425         land. This pull request was closed automatically after that was verified; \
2426         reopen it if you disagree."
2427    )
2428}
2429
2430/// Close the open pull request for `branch`, if there is one and it is
2431/// provably this run's, with a comment naming what supersedes it. `Ok(Ok(url))` is
2432/// the URL closed; `Ok(Err(why))` is a final "nothing to close" (no pull request,
2433/// not this run's, no forge); `Err` is anything a later attempt could resolve (a
2434/// failed `gh` call, a head that moved since it was checked), which the caller
2435/// must not treat as settled.
2436///
2437/// The recorded `state.pr` is preferred, else the forge is asked for an open
2438/// pull request on `branch`; either way the candidate is re-read and passed
2439/// through [`closable`] before anything is written; `verified` lists the
2440/// commits proven to be on the base, and the pull request's head must be one.
2441pub async fn close_superseded_pr(
2442    state: &mut RunState,
2443    branch: &str,
2444    evidence: &crate::already::Evidence,
2445    verified: &[String],
2446) -> Result<std::result::Result<String, String>> {
2447    let repo = state.repo.clone();
2448    let base = state.base_branch.clone();
2449    let url = match state.pr.as_ref().filter(|p| p.state == "open") {
2450        Some(p) => p.url.clone(),
2451        // No recorded pull request. A forge that cannot be asked at all (no
2452        // GitHub remote, no `gh`) says nothing about this run, so that is
2453        // "none found"; any other lookup failure is an error, because "could
2454        // not look" is not "nothing there" and the caller must retry.
2455        None if !remote_is_forge(&repo, &state.config.merge.remote).await => {
2456            return Ok(Err(
2457                "the remote is not a forge, so there is no pull request".to_owned(),
2458            ));
2459        }
2460        None => match find_open_pr(&repo, branch, &base).await {
2461            Err(e) if forge_unavailable(&format!("{e:#}")) => {
2462                return Ok(Err(format!("no forge to ask: {e:#}")));
2463            }
2464            Err(e) => return Err(e),
2465            Ok(OpenPr::One { url, .. }) => url,
2466            Ok(OpenPr::None) => return Ok(Err("no open pull request".to_owned())),
2467            Ok(OpenPr::Many(urls)) => {
2468                return Ok(Err(format!(
2469                    "{} open pull requests name it; not choosing between them",
2470                    urls.len()
2471                )));
2472            }
2473        },
2474    };
2475    let view = gh(
2476        &repo,
2477        &[
2478            "pr".to_owned(),
2479            "view".to_owned(),
2480            url.clone(),
2481            "--json".to_owned(),
2482            "headRefName,headRefOid,baseRefName,state,isCrossRepository".to_owned(),
2483        ],
2484    )
2485    .await?;
2486    if !view.ok {
2487        bail!("gh pr view {url} failed: {}", view.combined());
2488    }
2489    if let Err(refusal) = closable(&view.stdout, branch, &base, verified) {
2490        // A pull request whose head cannot be tied to what was proven is not
2491        // one to walk away from: the caller keeps the run resumable.
2492        if refusal.retry {
2493            bail!("left {url} open: {}", refusal.why);
2494        }
2495        return Ok(Err(format!("left {url} open: {}", refusal.why)));
2496    }
2497    let out = gh(
2498        &repo,
2499        &[
2500            "pr".to_owned(),
2501            "close".to_owned(),
2502            url.clone(),
2503            "--comment".to_owned(),
2504            superseded_comment(&base, evidence),
2505        ],
2506    )
2507    .await?;
2508    if !out.ok {
2509        bail!("gh pr close {url} failed: {}", out.combined());
2510    }
2511    if let Some(p) = state.pr.as_mut().filter(|p| p.url == url) {
2512        p.state = "closed".to_owned();
2513    }
2514    Ok(Ok(url))
2515}
2516
2517/// `gh pr edit <url> --title <title>`, for an adopted pull request whose title
2518/// differs from the one this run computed. Only the title: the body may have
2519/// been edited by the owner and cannot be compared.
2520pub async fn set_pr_title(state: &mut RunState, repo: &Path, url: &str, title: &str) -> Result<()> {
2521    let (title, _) = crate::github_text::prepare(state, title, "");
2522    edit_pr_title(repo, url, &title).await
2523}
2524
2525/// [`set_pr_title`] for a title the owner explicitly chose to post unmodified
2526/// (`github_text::POST_ORIGINAL` or `github_text::USE_REWRITE`): the posting
2527/// gate is skipped on purpose.
2528pub async fn set_pr_title_verbatim(repo: &Path, url: &str, title: &str) -> Result<()> {
2529    edit_pr_title(repo, url, title).await
2530}
2531
2532/// Post both fields of the owner's chosen rewrite to an adopted pull request,
2533/// unmodified and without the posting gate.
2534pub async fn set_pr_text_verbatim(repo: &Path, url: &str, title: &str, body: &str) -> Result<()> {
2535    let out = gh(
2536        repo,
2537        &[
2538            "pr".to_owned(),
2539            "edit".to_owned(),
2540            url.to_owned(),
2541            "--title".to_owned(),
2542            title.to_owned(),
2543            "--body".to_owned(),
2544            body.to_owned(),
2545        ],
2546    )
2547    .await
2548    .map_err(|_| anyhow::anyhow!("could not run gh pr edit for the chosen rewrite"))?;
2549    if !out.ok {
2550        // Command output may echo the chosen text; keep it out of run events.
2551        bail!("gh pr edit failed while posting the chosen rewrite");
2552    }
2553    Ok(())
2554}
2555
2556async fn edit_pr_title(repo: &Path, url: &str, title: &str) -> Result<()> {
2557    let out = gh(
2558        repo,
2559        &[
2560            "pr".to_owned(),
2561            "edit".to_owned(),
2562            url.to_owned(),
2563            "--title".to_owned(),
2564            title.to_owned(),
2565        ],
2566    )
2567    .await?;
2568    if !out.ok {
2569        bail!("gh pr edit failed: {}", out.combined());
2570    }
2571    Ok(())
2572}
2573
2574/// Ask GitHub whether this run's winning candidate branch was actually merged
2575/// somewhere `land::land`'s own loop never saw — the gap `magi fold
2576/// --merged` exists to close, minus the operator having to find the URL by
2577/// hand.
2578///
2579/// `Ok(None)` covers every case where nothing can be said with confidence: no
2580/// winner decided yet (nothing to check a branch for), no merged pull request
2581/// found, or [`pick_merged_pr`] found more than one candidate and would not
2582/// guess between them. Never wired to a weaker, URL-less signal like
2583/// [`branch_is_ancestor`] — a caller wanting that has to ask for it
2584/// separately, precisely because it cannot drive an automatic correction on
2585/// its own (see that function's own doc).
2586pub async fn find_external_merge(state: &RunState) -> Result<Option<ExternalMerge>> {
2587    let Some(winner) = state.winner() else {
2588        return Ok(None);
2589    };
2590    find_external_merge_with(
2591        state,
2592        state.pr_head.as_deref().unwrap_or(&winner.branch),
2593        false,
2594    )
2595    .await
2596}
2597
2598/// Reopening needs proof of absence, not merely failure to identify one PR.
2599pub(crate) async fn find_external_merge_for_reopen(
2600    state: &RunState,
2601) -> Result<Option<ExternalMerge>> {
2602    let Some(branch) = state.pr_branch() else {
2603        anyhow::ensure!(
2604            state.pr.is_none() && state.pr_pushed_head.is_none(),
2605            "run has public PR evidence but no known branch to check"
2606        );
2607        return Ok(None);
2608    };
2609    find_external_merge_with(state, branch, true).await
2610}
2611
2612async fn find_external_merge_with(
2613    state: &RunState,
2614    branch: &str,
2615    reject_ambiguous: bool,
2616) -> Result<Option<ExternalMerge>> {
2617    let out = gh(
2618        &state.repo,
2619        &[
2620            "pr".to_owned(),
2621            "list".to_owned(),
2622            "--head".to_owned(),
2623            branch.to_owned(),
2624            "--state".to_owned(),
2625            "merged".to_owned(),
2626            "--json".to_owned(),
2627            "url,number,mergedAt,baseRefName".to_owned(),
2628        ],
2629    )
2630    .await?;
2631    if !out.ok {
2632        bail!("gh pr list --head {branch}: {}", out.combined());
2633    }
2634    if reject_ambiguous {
2635        pick_merged_pr_with(&out.stdout, &state.base_branch, state.created_at, true)
2636    } else {
2637        pick_merged_pr(&out.stdout, &state.base_branch, state.created_at)
2638    }
2639}
2640
2641/// Whether `branch` is, right now, an ancestor of `base_branch` in the local
2642/// git graph — the weaker, URL-less signal that a branch landed somewhere.
2643///
2644/// Deliberately never consulted by [`find_external_merge`]: a base branch
2645/// that has moved since the run started can make an old, abandoned branch
2646/// look like an ancestor of the *current* base for reasons that have nothing
2647/// to do with a merge (a later commit that happens to supersede it, an
2648/// unrelated squash), and there is no pull request URL here to confirm
2649/// against or to land through anyway. Its only honest use is a weaker
2650/// notice — "this looks merged, go check" — never an automatic rewrite of
2651/// `status`/`merge`.
2652pub async fn branch_is_ancestor(repo: &Path, branch: &str, base_branch: &str) -> Result<bool> {
2653    let out = tokio::process::Command::new("git")
2654        .args(["merge-base", "--is-ancestor", branch, base_branch])
2655        .current_dir(repo)
2656        .quiet()
2657        .stdin(std::process::Stdio::null())
2658        .output()
2659        .await
2660        .context("spawn git merge-base --is-ancestor")?;
2661    Ok(out.status.success())
2662}
2663
2664/// Parse `host/owner/repo` out of a forge URL, with no network access.
2665///
2666/// The host is part of the slug, not discarded: `owner/repo` alone would
2667/// treat `github.example.com/o/r` and `github.com/o/r` as the same
2668/// repository, which is exactly the mix-up the same-repo guard exists to
2669/// catch. Returns `None` for anything that doesn't have a `<host>/<path>`
2670/// shape at all.
2671fn forge_slug(url: &str) -> Option<(String, &str)> {
2672    let rest = url.rsplit("://").next()?;
2673    let (host, path) = rest.split_once('/')?;
2674    if host.is_empty() {
2675        return None;
2676    }
2677    Some((host.to_ascii_lowercase(), path))
2678}
2679
2680/// Parse `host/owner/repo` out of a GitHub pull request URL, with no network
2681/// access - the first half of the same-repo guard [`correct_manual_merge`]
2682/// applies before it writes anything.
2683///
2684/// Returns `None` for anything that does not look like
2685/// `https://<host>/<owner>/<repo>/pull/<n>`, which the caller treats as
2686/// fail-closed: a URL this cannot make sense of refuses rather than guesses.
2687pub(crate) fn slug_of_pr_url(url: &str) -> Option<String> {
2688    let (host, path) = forge_slug(url)?;
2689    let mut segments = path.split('/');
2690    let owner = segments.next()?;
2691    let repo = segments.next()?;
2692    let kind = segments.next()?;
2693    if owner.is_empty() || repo.is_empty() || kind != "pull" {
2694        return None;
2695    }
2696    Some(format!("{host}/{owner}/{repo}"))
2697}
2698
2699/// Parse `host/owner/repo` out of a plain repository URL (no `/pull/<n>`
2700/// suffix), the shape `gh repo view --json url` returns - the other half of
2701/// the same-repo guard, matched against [`slug_of_pr_url`]'s output.
2702fn slug_of_repo_url(url: &str) -> Option<String> {
2703    let (host, path) = forge_slug(url)?;
2704    let mut segments = path.split('/');
2705    let owner = segments.next()?;
2706    let repo = segments.next()?;
2707    if owner.is_empty() || repo.is_empty() {
2708        return None;
2709    }
2710    Some(format!("{host}/{owner}/{repo}"))
2711}
2712
2713/// Refuse to correct a run against a pull request from a different
2714/// repository than the one it is recorded against.
2715///
2716/// This is the guard the shun/8c75 incident argued for: an operator ran
2717/// `magi fold --merged <shun PR url>` meaning to correct an old `Blocked` run
2718/// in a different repository, omitted the run id, and the id defaulted to
2719/// this machine's most recently created run - an unrelated, still-in-progress
2720/// run in a completely different repository - which then had its `status`
2721/// rewritten to `merged` from a pull request it had nothing to do with.
2722/// `correct_manual_merge` now requires an explicit id (see `magi fold`'s own
2723/// CLI help), but a mistyped or stale id could still name a run in a
2724/// different repository than the one the URL belongs to, so this checks that
2725/// independently rather than trusting the id alone.
2726///
2727/// Comparison is case-insensitive - GitHub owner/repo names are - and a
2728/// mismatch names both slugs rather than just refusing, so an operator whose
2729/// local checkout's `origin` is a fork of the repository the pull request was
2730/// opened against (a legitimate setup this cannot tell apart from a genuine
2731/// mix-up) can judge for themselves rather than being blocked with no way to
2732/// see why.
2733pub(crate) fn ensure_same_repo(run_repo_slug: &str, pr_repo_slug: &str) -> Result<()> {
2734    if run_repo_slug.eq_ignore_ascii_case(pr_repo_slug) {
2735        return Ok(());
2736    }
2737    bail!(
2738        "refusing to correct this run: it is recorded against {run_repo_slug}, but the pull \
2739         request URL belongs to {pr_repo_slug} - pass the run id whose repository the URL \
2740         actually belongs to (or, if `origin` is a fork opened against a different upstream, \
2741         verify by hand before treating this as a false positive)"
2742    );
2743}
2744
2745/// Ask the forge which `host/owner/repo` a local checkout's `origin` remote
2746/// actually resolves to, for the same-repo guard in [`correct_manual_merge`].
2747///
2748/// Asking `gh` rather than parsing `git remote -v` locally is deliberate: it
2749/// normalizes case, SSH vs. HTTPS remotes, and a renamed or transferred
2750/// repository the same way GitHub itself would recognize it, so the
2751/// comparison in [`ensure_same_repo`] is against the same canonical slug on
2752/// both sides. Reads `url` rather than `nameWithOwner` so the host is part of
2753/// the answer too - `nameWithOwner` alone cannot tell a `github.com` repo from
2754/// a same-named one on a GitHub Enterprise host.
2755async fn repo_slug(repo: &Path) -> Result<String> {
2756    let out = gh(
2757        repo,
2758        &[
2759            "repo".to_owned(),
2760            "view".to_owned(),
2761            "--json".to_owned(),
2762            "url".to_owned(),
2763        ],
2764    )
2765    .await?;
2766    if !out.ok {
2767        bail!("gh repo view --json url: {}", out.combined());
2768    }
2769    #[derive(Debug, Deserialize)]
2770    struct GhRepo {
2771        url: String,
2772    }
2773    let parsed: GhRepo = serde_json::from_str(&out.stdout)
2774        .with_context(|| format!("parse `gh repo view` output: {}", out.stdout.trim()))?;
2775    slug_of_repo_url(&parsed.url)
2776        .with_context(|| format!("could not parse a host/owner/repo out of {}", parsed.url))
2777}
2778
2779/// Confirm `url` is actually a merged pull request, then rewrite `state`'s
2780/// `status` and `merge` exactly as the automatic land loop (`land::land`)
2781/// would have written them had magi opened and merged this pull request
2782/// itself.
2783///
2784/// This is `magi fold --merged`'s whole implementation, and also what the
2785/// web `fold-merged` route calls once it has a URL in hand — an operator
2786/// recovery path for a merge magi could not finish on its own: a PR title too
2787/// long for the GraphQL mutation, `gh pr create` unreachable, a stale token -
2788/// closed by hand with a pull request magi never opened and so never
2789/// recorded. Reusing `land::land` rather than writing `status`/`merge`
2790/// directly keeps this one authoritative: a merged pull request decides
2791/// `Step::Done { merged: true }` on the very first read, before any of
2792/// `land`'s own checks/fix/rebase machinery can run, which is what makes it
2793/// safe to call here even though this pull request was never magi's own.
2794///
2795/// [`ensure_same_repo`] is checked before anything else: a pull request from
2796/// a different repository than the one `state` is recorded against is
2797/// refused outright, regardless of its lifecycle. This is the guard for a
2798/// URL an *operator* hands in - the CLI or the web route - where a stale or
2799/// mistyped run id could otherwise get corrected from an unrelated
2800/// repository's pull request (see the shun/8c75 incident in `magi fold`'s own
2801/// CLI help). The automatic janitor sweep (`clean::reconcile_external_merges`)
2802/// goes through [`correct_confirmed_external_merge`] instead, which skips
2803/// this check: its `url` was never operator-supplied, it comes from
2804/// [`find_external_merge`] querying `gh` from inside `state.repo` itself, so
2805/// it is already guaranteed to name a pull request in that same repository -
2806/// re-deriving and re-checking the repository here would only be a second
2807/// `gh repo view` call that can fail for reasons that have nothing to do with
2808/// correctness (a rate limit, a network blip), turning a self-heal that would
2809/// otherwise have succeeded into a run left `Blocked` for another pass.
2810///
2811/// [`lifecycle`] is checked next and separately so a mistyped or still-open
2812/// URL fails loudly without writing anything, rather than handing an open
2813/// pull request to the full autonomous loop by accident.
2814///
2815/// Correcting `status` this way does not run `bump::after_merge`
2816/// (`src/bump.rs`): that call is made only from `graph::Runner::run_land`,
2817/// which this path never goes through. A release version bump the change
2818/// might have earned is therefore not filed automatically and has to be
2819/// requested by hand - recorded as an event on the run so the gap is visible
2820/// to whoever reads it later, not just wherever this was called from. Follow-up
2821/// tasks for findings the merge left open (`crate::followup`) *are* filed here.
2822///
2823/// Returns the status before and after, so every caller (CLI, janitor, web
2824/// route) can build its own log line or response from the same pair rather
2825/// than each re-deriving it.
2826pub async fn correct_manual_merge(
2827    state: &mut RunState,
2828    url: &str,
2829) -> Result<(RunStatus, RunStatus)> {
2830    let Some(pr_slug) = slug_of_pr_url(url) else {
2831        bail!(
2832            "could not parse an owner/repo out of {url}; refusing to guess which repository \
2833             this pull request belongs to"
2834        );
2835    };
2836    let run_slug = repo_slug(&state.repo).await?;
2837    ensure_same_repo(&run_slug, &pr_slug)?;
2838    correct_merge(state, url).await
2839}
2840
2841/// The janitor's own entry point into the same correction
2842/// [`correct_manual_merge`] performs for an operator-supplied URL, minus the
2843/// same-repo guard - see that function's own doc for why skipping it here is
2844/// safe rather than a hole: [`clean::reconcile_external_merges`] only ever
2845/// calls this with a `url` [`find_external_merge`] already found by querying
2846/// `state.repo`'s own remote, so the guard could never do anything here but
2847/// fail on its own transient errors.
2848///
2849/// [`crate::clean`] is the only caller; `pub(crate)` rather than private only
2850/// because it lives in a different module.
2851pub(crate) async fn correct_confirmed_external_merge(
2852    state: &mut RunState,
2853    url: &str,
2854) -> Result<(RunStatus, RunStatus)> {
2855    correct_merge(state, url).await
2856}
2857
2858/// Same pull request, same repository: the url, or the number within one repo.
2859fn names_same_pr(a: &RunState, url: &str, number: u64, repo: &Path) -> bool {
2860    let Some(pr) = a.pr.as_ref() else {
2861        return false;
2862    };
2863    if !url.is_empty()
2864        && pr
2865            .url
2866            .trim_end_matches('/')
2867            .eq_ignore_ascii_case(url.trim_end_matches('/'))
2868    {
2869        return true;
2870    }
2871    number > 0
2872        && pr.number == number
2873        && match (a.repo.canonicalize(), repo.canonicalize()) {
2874            (Ok(x), Ok(y)) => x == y,
2875            _ => a.repo == repo,
2876        }
2877}
2878
2879/// Rewrite `pr.state` to a final state on every run record under `home` that
2880/// `decide` picks, and report how many were rewritten.
2881///
2882/// Lifecycle writes through to other runs are deliberately narrow (task-head
2883/// ownership is recorded separately): only a **terminal** run (never one a
2884/// driver may still be writing), only a proven-stopped driver with no daemon
2885/// claim (the shared liveness judge), only a record
2886/// whose `pr.state` is still `open`, and only `merged` / `closed` ever goes in.
2887/// The record is read as folding reads it (no schema check: every bump so far
2888/// only added fields, and the whole struct round-trips) and written through
2889/// [`RunState::save_under`], the path every record uses, so nothing but
2890/// `pr.state` and an event line changes (and `updated_at`, as for any save).
2891/// A run that cannot be read or written is skipped with a warning.
2892fn rewrite_open_prs(
2893    home: &Path,
2894    decide: &mut dyn FnMut(&RunState) -> Option<PrLifecycle>,
2895) -> usize {
2896    let now = Timestamp::now();
2897    let mut changed = 0;
2898    for id in crate::run::list_ids_in(&home.join("runs")) {
2899        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2900            continue;
2901        };
2902        let path = home.join("runs").join(&id).join("run.json");
2903        let Ok(body) = std::fs::read_to_string(&path) else {
2904            continue;
2905        };
2906        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2907            continue;
2908        };
2909        if !state.status.done()
2910            || state.pr.as_ref().is_none_or(|p| p.state != "open")
2911            || state.liveness_under(home, crate::daemon::is_working_on(home, &id, now))
2912                != crate::run::Liveness::Dead
2913        {
2914            continue;
2915        }
2916        let Some(to @ (PrLifecycle::Merged | PrLifecycle::Closed)) = decide(&state) else {
2917            continue;
2918        };
2919        if let Some(pr) = state.pr.as_mut() {
2920            pr.state = to.as_str().to_owned();
2921        }
2922        let url = state.pr.as_ref().map(|p| p.url.clone()).unwrap_or_default();
2923        state.event(
2924            "land",
2925            format!("recorded {url} as {}: another run settled it", to.as_str()),
2926        );
2927        match state.save_under(home) {
2928            Ok(()) => changed += 1,
2929            Err(e) => tracing::warn!("write pr state through to run {id}: {e:#}"),
2930        }
2931    }
2932    changed
2933}
2934
2935/// A run reached a final state for its pull request: tell every other terminal
2936/// run in the same repository that names the same pull request (handed-over
2937/// predecessors, blocked attempts, anything), so their records stop saying
2938/// `open`. Best effort; `run`'s own record is the caller's.
2939pub(crate) fn write_pr_state_through(run: &RunState, to: PrLifecycle) {
2940    if to == PrLifecycle::Open {
2941        return;
2942    }
2943    let Some(home) = crate::run::try_home() else {
2944        return;
2945    };
2946    write_pr_state_through_in(&home, run, to);
2947}
2948
2949pub(crate) fn write_pr_state_through_in(home: &Path, run: &RunState, to: PrLifecycle) -> usize {
2950    let Some(pr) = run.pr.as_ref() else {
2951        return 0;
2952    };
2953    let (url, number) = (pr.url.clone(), pr.number);
2954    rewrite_open_prs(home, &mut |other| {
2955        (other.id != run.id && names_same_pr(other, &url, number, &run.repo)).then_some(to)
2956    })
2957}
2958
2959/// Terminal runs whose record still says their pull request is open, as
2960/// `(run id, repo, url)`, for [`repair_stale_pr_states`].
2961pub(crate) fn stale_open_prs(home: &Path) -> Vec<(String, PathBuf, String)> {
2962    let now = Timestamp::now();
2963    let mut out = Vec::new();
2964    for id in crate::run::list_ids_in(&home.join("runs")) {
2965        let path = home.join("runs").join(&id).join("run.json");
2966        let Ok(body) = std::fs::read_to_string(&path) else {
2967            continue;
2968        };
2969        let Ok(state) = serde_json::from_str::<RunState>(&body) else {
2970            continue;
2971        };
2972        if let Some(pr) = state.pr.as_ref()
2973            && state.status.done()
2974            && pr.state == "open"
2975            && !pr.url.is_empty()
2976            && !crate::daemon::is_working_on(home, &id, now)
2977        {
2978            out.push((id, state.repo.clone(), pr.url.clone()));
2979        }
2980    }
2981    out
2982}
2983
2984/// Apply forge answers (`pr url -> state`) to every stale terminal record.
2985/// A url with no answer (the forge was unreadable) changes nothing.
2986pub(crate) fn apply_pr_states(home: &Path, known: &BTreeMap<String, PrLifecycle>) -> usize {
2987    rewrite_open_prs(home, &mut |s| {
2988        s.pr.as_ref().and_then(|p| known.get(&p.url)).copied()
2989    })
2990}
2991
2992/// One-time (and idempotent) repair of records that froze an `open` pull
2993/// request: ask the forge about each distinct pull request that a terminal run
2994/// still calls open - at most `max_lookups` of them - and rewrite the merged
2995/// and closed ones. A genuinely open pull request is left alone, and a lookup
2996/// that fails is "unknown, change nothing". Returns `(records rewritten,
2997/// lookups that failed)`.
2998pub async fn repair_stale_pr_states(home: &Path, max_lookups: usize) -> (usize, usize) {
2999    let mut known = BTreeMap::new();
3000    let mut failed = 0;
3001    let mut seen = BTreeSet::new();
3002    for (_, repo, url) in stale_open_prs(home) {
3003        if known.len() + failed >= max_lookups || !seen.insert(url.clone()) {
3004            continue;
3005        }
3006        match lifecycle(&repo, &url).await {
3007            Ok(state) => {
3008                known.insert(url, state);
3009            }
3010            Err(e) => {
3011                tracing::warn!("repair pr state of {url}: {e:#}");
3012                failed += 1;
3013            }
3014        }
3015    }
3016    (apply_pr_states(home, &known), failed)
3017}
3018
3019async fn correct_merge(state: &mut RunState, url: &str) -> Result<(RunStatus, RunStatus)> {
3020    match lifecycle(&state.repo, url).await? {
3021        PrLifecycle::Merged => {}
3022        other => bail!(
3023            "{url} is {}, not merged; refusing to record {} as merged on a guess",
3024            other.as_str(),
3025            state.id
3026        ),
3027    }
3028    let before = state.status;
3029    if let Err(e) = land(state, url).await {
3030        // `land` sets `status` to `Landing` and saves before its first read
3031        // of the pull request — see its own doc — so a failure here (a
3032        // transient `gh` hiccup between the two forge reads this function
3033        // makes) can leave the run stuck on that in-between value with
3034        // nothing left driving it. Land it on the same terminal shape an
3035        // automated `land` failure lands on instead of leaving it stuck.
3036        state.status = RunStatus::Blocked;
3037        state.event("fold", format!("manual-merge correction failed: {e:#}"));
3038        state.save()?;
3039        return Err(e).context(format!("confirming the merge of {url}"));
3040    }
3041    state.event(
3042        "fold",
3043        "operator recorded this pull request as a manual merge; this run never \
3044         re-entered `land`, so `bump::after_merge` did not run for it - a release \
3045         bump this change might warrant has to be filed by hand",
3046    );
3047    // Unlike the bump, the findings the merge left open are filed on this
3048    // path too: nothing else would ever carry them forward.
3049    if state.status == RunStatus::Merged {
3050        crate::followup::after_merge(state, url).await;
3051    }
3052    state.save()?;
3053    Ok((before, state.status))
3054}
3055
3056/// Parse `gh api repos/{owner}/{repo}/pulls/<n>/comments` into inline review
3057/// comments. No I/O.
3058///
3059/// `gh pr view` does not surface inline comments, and inline is exactly where
3060/// both review bots put their findings - a landing loop that read only the
3061/// top-level thread would never see the thing it is supposed to fix.
3062pub fn parse_inline_comments(json: &str) -> Result<Vec<ReviewComment>> {
3063    let raw: Vec<GhInline> =
3064        serde_json::from_str(json).context("parse `gh api .../pulls/<n>/comments` output")?;
3065    let mut out = Vec::new();
3066    for c in raw {
3067        push_if_outstanding(
3068            &mut out,
3069            ReviewComment {
3070                author: c.user.login,
3071                path: c.path,
3072                line: c.line,
3073                body: c.body,
3074            },
3075        );
3076    }
3077    Ok(out)
3078}
3079
3080/// Keep a comment only when it asks for something.
3081///
3082/// An inline comment always does: it names a file and a line. A top-level
3083/// comment is dropped when it is empty, when it is magi's own, or when it is
3084/// [noise](is_noise).
3085fn push_if_outstanding(out: &mut Vec<ReviewComment>, comment: ReviewComment) {
3086    if comment.body.trim().is_empty() || comment.body.contains(MARKER) {
3087        return;
3088    }
3089    if comment.path.is_none() && is_noise(&comment.body) {
3090        return;
3091    }
3092    out.push(comment);
3093}
3094
3095/// Is this comment body machinery rather than a finding?
3096///
3097/// Two tests, both structural, because guessing from prose is how a "looks
3098/// good to me" turns into a fix round:
3099///
3100/// 1. The bot said so - the body carries one of the [`NOT_A_REVIEW`] markers
3101///    with which CodeRabbit labels its trigger notice, its walkthrough, and its
3102///    footer.
3103/// 2. It asks for nothing - once HTML comments, `<details>` blocks, headings,
3104///    horizontal rules, and the bot's own status banner are removed, every
3105///    remaining line is a task-list item. That is exactly the shape of the
3106///    comment the Claude review job posts while it is still working.
3107///
3108/// Anything else is input, including bot prose. A bot that writes a paragraph
3109/// has said something, and the fix prompt tells the fixer it may decline a
3110/// comment with an argument - a wasted sentence in a prompt is cheaper than a
3111/// missed finding.
3112pub fn is_noise(body: &str) -> bool {
3113    if NOT_A_REVIEW.iter().any(|m| body.contains(m)) {
3114        return true;
3115    }
3116    let mut content = false;
3117    for line in strip_blocks(body).lines() {
3118        let line = unquote(line);
3119        if line.is_empty() || is_checklist(line) || is_decoration(line) || is_banner(line) {
3120            continue;
3121        }
3122        content = true;
3123        break;
3124    }
3125    !content
3126}
3127
3128/// Remove HTML comments and collapsed `<details>` blocks.
3129fn strip_blocks(body: &str) -> String {
3130    let mut out = String::with_capacity(body.len());
3131    let mut rest = body;
3132    loop {
3133        let open = ["<!--", "<details>"]
3134            .iter()
3135            .filter_map(|tag| rest.find(tag).map(|i| (i, *tag)))
3136            .min_by_key(|(i, _)| *i);
3137        let Some((at, tag)) = open else {
3138            out.push_str(rest);
3139            return out;
3140        };
3141        out.push_str(&rest[..at]);
3142        let after = &rest[at + tag.len()..];
3143        let close = if tag == "<!--" { "-->" } else { "</details>" };
3144        match after.find(close) {
3145            Some(end) => rest = &after[end + close.len()..],
3146            // Unterminated: the rest of the body is inside the block.
3147            None => return out,
3148        }
3149    }
3150}
3151
3152/// Strip blockquote markers, which both bots wrap their callouts in.
3153fn unquote(line: &str) -> &str {
3154    let mut s = line.trim();
3155    while let Some(rest) = s.strip_prefix('>') {
3156        s = rest.trim_start();
3157    }
3158    s.trim()
3159}
3160
3161/// `- [ ]` / `- [x]`, in any of the bullet styles GitHub renders.
3162fn is_checklist(line: &str) -> bool {
3163    let rest = line
3164        .strip_prefix("- ")
3165        .or_else(|| line.strip_prefix("* "))
3166        .unwrap_or("");
3167    let rest = rest.trim_start();
3168    matches!(
3169        rest.get(..3),
3170        Some("[ ]") | Some("[x]") | Some("[X]") | Some("[*]")
3171    )
3172}
3173
3174/// A heading, a horizontal rule, or a callout tag - shape, never content.
3175fn is_decoration(line: &str) -> bool {
3176    line.starts_with('#')
3177        || line.starts_with("[!")
3178        || (line.len() >= 3 && line.chars().all(|c| matches!(c, '-' | '=' | '*' | '_')))
3179}
3180
3181/// A line that is nothing but emphasis and links.
3182///
3183/// Both review jobs open with a status banner
3184/// (`**Claude finished ... in 4m 14s** —— [View job](url)`). It reads as prose
3185/// to a line-based test and asks for nothing, so it is measured the same way a
3186/// heading is: strip the markup, and if no word survives, it was decoration.
3187fn is_banner(line: &str) -> bool {
3188    let plain = drop_spans(line, "**", "**");
3189    let plain = if plain.contains("](") {
3190        drop_spans(&plain, "[", ")")
3191    } else {
3192        plain
3193    };
3194    !plain.chars().any(char::is_alphanumeric)
3195}
3196
3197/// Remove every `open` .. `close` span, including the delimiters. An
3198/// unterminated span swallows the rest of the input, which is what a reader
3199/// sees too.
3200fn drop_spans(s: &str, open: &str, close: &str) -> String {
3201    let mut out = String::with_capacity(s.len());
3202    let mut rest = s;
3203    while let Some(at) = rest.find(open) {
3204        out.push_str(&rest[..at]);
3205        let after = &rest[at + open.len()..];
3206        match after.find(close) {
3207            Some(end) => rest = &after[end + close.len()..],
3208            None => return out,
3209        }
3210    }
3211    out.push_str(rest);
3212    out
3213}
3214
3215/// The lock that keeps at most one run per repository actually moving the
3216/// base branch at a time: a rebase push, or `gh pr merge`.
3217///
3218/// Deliberately narrow. Everything else in [`land`]'s loop - watching CI,
3219/// running a fix round in the winner's own worktree, waiting on the owner's
3220/// approval - touches nothing a *different* run in the same repository could
3221/// collide with, and holding a lock across any of that would serialise one
3222/// run's CI wait (up to [`WAIT_CEILING`]) against another run's land-approval
3223/// resume, which is precisely the "must not wait on another task" property
3224/// the daemon's slot-freeing exists to give a resume. Only the two moments
3225/// that actually write to the shared base branch need mutual exclusion, and
3226/// both are brief.
3227///
3228/// One entry per repository, each its own `tokio::sync::Mutex`, so two
3229/// different repositories' runs never wait on each other. The outer
3230/// `std::sync::Mutex` guards only the map itself, held long enough to find or
3231/// insert an entry and clone its `Arc`, never across an `.await`.
3232fn repo_merge_lock(repo: &Path) -> Arc<tokio::sync::Mutex<()>> {
3233    static LOCKS: std::sync::LazyLock<
3234        std::sync::Mutex<BTreeMap<PathBuf, Arc<tokio::sync::Mutex<()>>>>,
3235    > = std::sync::LazyLock::new(|| std::sync::Mutex::new(BTreeMap::new()));
3236    LOCKS
3237        .lock()
3238        .unwrap_or_else(std::sync::PoisonError::into_inner)
3239        .entry(repo.to_path_buf())
3240        .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
3241        .clone()
3242}
3243
3244/// `owner/repo` out of a pull request url, falling back to the checkout's
3245/// directory name when the url is not the usual `host/owner/repo/pull/N`.
3246fn repo_label(repo: &Path, pr_url: &str) -> String {
3247    let parts: Vec<&str> = pr_url.split('/').collect();
3248    if let Some(at) = parts.iter().rposition(|p| *p == "pull")
3249        && at >= 2
3250        && !parts[at - 1].is_empty()
3251        && !parts[at - 2].is_empty()
3252    {
3253        return format!("{}/{}", parts[at - 2], parts[at - 1]);
3254    }
3255    repo.file_name()
3256        .map(|n| n.to_string_lossy().into_owned())
3257        .unwrap_or_default()
3258}
3259
3260/// The operator-facing sentence for a merge that went ahead with red checks,
3261/// or `None` when the checks were not red. Judged on `checks`, not on
3262/// `failing`, which can be non-empty on a green observation.
3263fn red_merge_summary(repo_name: &str, pr: &PrState) -> Option<String> {
3264    (pr.checks == Checks::Red).then(|| {
3265        let details = crate::notices::format_list(&pr.failing)
3266            .map(|names| format!(": {names}"))
3267            .unwrap_or_default();
3268        format!(
3269            "Merged {repo_name} PR #{} with red checks{details} ({})",
3270            pr.number, pr.url
3271        )
3272    })
3273}
3274
3275/// After a merge that succeeded: record which checks were red and tell the
3276/// operator. The decision to merge is already made; this only makes it audible.
3277/// Best-effort - a broken notifier never fails the run.
3278async fn announce_red_merge(state: &mut RunState, pr: &PrState) {
3279    let repo_name = repo_label(&state.repo, &pr.url);
3280    let Some(summary) = red_merge_summary(&repo_name, pr) else {
3281        return;
3282    };
3283    if let Some(rec) = state.pr.as_mut() {
3284        rec.red_at_merge = pr.failing.clone();
3285    }
3286    state.event("land", summary.clone());
3287    // The notice pages through `[notify]` itself, once, unless a question
3288    // already carries the cause.
3289    crate::notices::raise_with(
3290        crate::notices::merged_red(&state.id, &summary),
3291        &state.config.notify,
3292    );
3293}
3294
3295/// Run the loop against a real pull request until it merges or the budget runs
3296/// out.
3297///
3298/// The caller decides whether landing happens at all: this is only reached when
3299/// `graph.land` is on. Returns the last observation, so the caller can report
3300/// what magi was looking at when it stopped.
3301pub async fn land(state: &mut RunState, pr_url: &str) -> Result<PrState> {
3302    land_with(state, pr_url, &GhForge).await
3303}
3304
3305/// The forge calls whose timing the loop's decisions depend on, behind a seam
3306/// so a test can script what the pull request looks like from one observation
3307/// to the next. Comments, logs and rebases stay on `gh` and `git` directly.
3308trait Forge {
3309    async fn close(&self, repo: &Path, pr_url: &str, comment: &str) -> Result<()> {
3310        let out = gh(
3311            repo,
3312            &[
3313                "pr".into(),
3314                "close".into(),
3315                pr_url.into(),
3316                "--comment".into(),
3317                comment.into(),
3318            ],
3319        )
3320        .await?;
3321        if !out.ok {
3322            bail!("PR closure failed: {}", out.combined());
3323        }
3324        Ok(())
3325    }
3326    async fn attribution(&self, _state: &RunState, _seen: &Seen) -> Option<CiEvidence> {
3327        None
3328    }
3329    async fn view(&self, repo: &Path, pr_url: &str) -> Result<Seen>;
3330    async fn merge(&self, repo: &Path, argv: &[String]) -> Result<(bool, String)>;
3331    async fn poll(&self);
3332    /// Rerun the failed jobs of one workflow run.
3333    async fn rerun(&self, repo: &Path, run: &str) -> Result<()>;
3334    /// Unix seconds, behind the seam so a test owns the clock.
3335    fn now(&self) -> i64;
3336    /// The check contexts the base branch requires, for a stop reason only.
3337    /// `None` when they could not be read, which is not the same as none.
3338    async fn required_contexts(&self, repo: &Path, base: &str) -> Option<BTreeSet<String>>;
3339    #[allow(clippy::too_many_arguments)]
3340    async fn fix(
3341        &self,
3342        state: &mut RunState,
3343        pr: &PrState,
3344        round: usize,
3345        budget: usize,
3346        reason: &str,
3347        logs: &str,
3348    ) -> Result<Fixed>;
3349}
3350
3351struct GhForge;
3352
3353impl Forge for GhForge {
3354    async fn attribution(&self, state: &RunState, seen: &Seen) -> Option<CiEvidence> {
3355        collect_ci_evidence(state, seen).await
3356    }
3357    async fn view(&self, repo: &Path, pr_url: &str) -> Result<Seen> {
3358        observe(repo, pr_url).await
3359    }
3360    async fn merge(&self, repo: &Path, argv: &[String]) -> Result<(bool, String)> {
3361        let out = gh(repo, argv).await?;
3362        Ok((out.ok, out.combined()))
3363    }
3364    async fn poll(&self) {
3365        tokio::time::sleep(POLL).await;
3366    }
3367    async fn rerun(&self, repo: &Path, run: &str) -> Result<()> {
3368        let args = [
3369            "run".to_owned(),
3370            "rerun".to_owned(),
3371            run.to_owned(),
3372            "--failed".to_owned(),
3373        ];
3374        let out = gh(repo, &args).await?;
3375        if !out.ok {
3376            bail!("gh run rerun {run}: {}", out.combined());
3377        }
3378        Ok(())
3379    }
3380    fn now(&self) -> i64 {
3381        jiff::Timestamp::now().as_second()
3382    }
3383    async fn required_contexts(&self, repo: &Path, base: &str) -> Option<BTreeSet<String>> {
3384        required_contexts_of(repo, base).await
3385    }
3386    async fn fix(
3387        &self,
3388        state: &mut RunState,
3389        pr: &PrState,
3390        round: usize,
3391        budget: usize,
3392        reason: &str,
3393        logs: &str,
3394    ) -> Result<Fixed> {
3395        fix_round(state, pr, round, budget, reason, logs).await
3396    }
3397}
3398
3399/// Percent-encode a branch name for a URL path segment (`/` included).
3400fn encode_path_segment(s: &str) -> String {
3401    let mut out = String::new();
3402    for b in s.bytes() {
3403        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
3404            out.push(b as char);
3405        } else {
3406            let _ = write!(out, "%{b:02X}");
3407        }
3408    }
3409    out
3410}
3411
3412/// Read the required contexts of `base` from classic branch protection and
3413/// from rulesets, once, for a stop reason. Organisation-level rulesets that
3414/// these two endpoints do not list are missed. Any unreadable source makes the
3415/// whole answer `None`: a partial set would read as a complete one.
3416async fn required_contexts_of(repo: &Path, base: &str) -> Option<BTreeSet<String>> {
3417    let enc = encode_path_segment(base);
3418    let mut all = BTreeSet::new();
3419    // Classic protection answers 404 for an unprotected branch, which is
3420    // "nothing required here", not a failure to read.
3421    let classic = gh(
3422        repo,
3423        &[
3424            "api".to_owned(),
3425            format!("repos/{{owner}}/{{repo}}/branches/{enc}/protection/required_status_checks"),
3426        ],
3427    )
3428    .await
3429    .ok()?;
3430    if classic.ok {
3431        all.extend(parse_classic_required(&classic.stdout)?);
3432    } else if !classic.combined().contains("404") {
3433        return None;
3434    }
3435    let rules = gh(
3436        repo,
3437        &[
3438            "api".to_owned(),
3439            format!("repos/{{owner}}/{{repo}}/rules/branches/{enc}"),
3440        ],
3441    )
3442    .await
3443    .ok()?;
3444    if !rules.ok {
3445        return None;
3446    }
3447    all.extend(parse_ruleset_required(&rules.stdout)?);
3448    Some(all)
3449}
3450
3451/// `required_status_checks` of classic protection: `contexts` plus the
3452/// `checks[].context` form.
3453fn parse_classic_required(json: &str) -> Option<BTreeSet<String>> {
3454    let v: serde_json::Value = serde_json::from_str(json).ok()?;
3455    let mut out = BTreeSet::new();
3456    for c in v.get("contexts")?.as_array()? {
3457        out.insert(c.as_str()?.to_owned());
3458    }
3459    for c in v
3460        .get("checks")
3461        .and_then(|c| c.as_array())
3462        .into_iter()
3463        .flatten()
3464    {
3465        if let Some(name) = c.get("context").and_then(|n| n.as_str()) {
3466            out.insert(name.to_owned());
3467        }
3468    }
3469    Some(out)
3470}
3471
3472/// `rules/branches/<base>`: every `required_status_checks` rule's contexts.
3473fn parse_ruleset_required(json: &str) -> Option<BTreeSet<String>> {
3474    let v: serde_json::Value = serde_json::from_str(json).ok()?;
3475    let mut out = BTreeSet::new();
3476    for rule in v.as_array()? {
3477        if rule.get("type").and_then(|t| t.as_str()) != Some("required_status_checks") {
3478            continue;
3479        }
3480        let checks = rule
3481            .pointer("/parameters/required_status_checks")?
3482            .as_array()?;
3483        for c in checks {
3484            out.insert(c.get("context")?.as_str()?.to_owned());
3485        }
3486    }
3487    Some(out)
3488}
3489
3490/// Is the observation older than the commit a fix round pushed?
3491///
3492/// The forge takes a few seconds to move the pull request to a new head and
3493/// attach that head's check runs, and until it has, the rollup is the previous
3494/// head's - all green, which is exactly what a merge decision must not read.
3495/// An absent or different head counts as not yet: guessing "close enough"
3496/// would reopen the hole.
3497fn awaiting_new_head(awaiting: Option<&str>, observed: &str) -> bool {
3498    awaiting.is_some_and(|want| !observed.eq_ignore_ascii_case(want))
3499}
3500
3501/// The commit an observation may be decided on, or `None` while it cannot be
3502/// trusted to describe one.
3503///
3504/// `None` when a pushed commit is awaited and the pull request is not on it,
3505/// when the head is unreadable, or when the rollup (`statusCheckRollup` is the
3506/// last commit's) is not the head's: that is the previous commit's checks. The
3507/// caller re-polls on `None`. A rollup that cannot be read (including one
3508/// longer than a page) leaves `rollup_head` empty, so the wait runs to
3509/// [`WAIT_CEILING`] and stops - a safe failure, never a merge.
3510fn bound_head<'a>(
3511    seen_head: &'a str,
3512    rollup_head: &str,
3513    awaiting: Option<&str>,
3514) -> Option<&'a str> {
3515    if seen_head.is_empty()
3516        || awaiting_new_head(awaiting, seen_head)
3517        || !rollup_head.eq_ignore_ascii_case(seen_head)
3518    {
3519        return None;
3520    }
3521    Some(seen_head)
3522}
3523
3524/// What a refused `gh pr merge` means.
3525#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3526enum Refused {
3527    /// An open PR on the observed head has a proven stale base.
3528    Behind,
3529    /// The branch policy is not satisfied *yet*: go back to waiting.
3530    Pending,
3531    /// Checks have settled and the merge state still says no, seen for the
3532    /// first time. The forge updates `mergeStateStatus` a moment after the last
3533    /// check finishes, so one more look is allowed before believing it.
3534    Recheck,
3535    /// Nothing is in flight and the policy still refuses: a person has to
3536    /// supply what it asks for (a review, say).
3537    Final,
3538}
3539
3540/// Judged from the pull request's state after the refusal, never from the
3541/// refusal's wording, which belongs to the forge and changes.
3542fn classify_refusal(
3543    after: Option<&Seen>,
3544    rechecked: bool,
3545    observed_head: &str,
3546    ci: CiExpectation,
3547) -> Refused {
3548    let Some(after) = after else {
3549        // Unreadable is not evidence of anything; the next loop reads again.
3550        return Refused::Pending;
3551    };
3552    if after.pr.state != PrLifecycle::Open {
3553        return Refused::Final;
3554    }
3555    // The branch moved after it was observed (the forge refuses a merge pinned
3556    // to the old commit): not a verdict on anything, look again.
3557    if !after.head.eq_ignore_ascii_case(observed_head) {
3558        return Refused::Pending;
3559    }
3560    if Blocking::of(&after.merge_state) == Blocking::Behind {
3561        return Refused::Behind;
3562    }
3563    // The same binding the loop applies: checks of another commit say nothing.
3564    if bound_head(&after.head, &after.rollup_head, None).is_none() {
3565        return Refused::Pending;
3566    }
3567    let state = after.merge_state.to_ascii_uppercase();
3568    if (ci == CiExpectation::Expected
3569        && matches!(after.pr.checks, Checks::Pending | Checks::Unknown))
3570        || state.is_empty()
3571        || state == "UNKNOWN"
3572    {
3573        return Refused::Pending;
3574    }
3575    if rechecked {
3576        Refused::Final
3577    } else {
3578        Refused::Recheck
3579    }
3580}
3581
3582/// Take auto-merge back from the forge and forget that it was armed.
3583///
3584/// `Err` carries the forge's message: the caller must not push or move on, as
3585/// an armed merge left behind could still fire for a commit nobody approved.
3586async fn disarm<F: Forge>(
3587    forge: &F,
3588    state: &mut RunState,
3589    repo: &Path,
3590    number: u64,
3591) -> std::result::Result<(), String> {
3592    let argv = disable_automerge_argv(number);
3593    let out = {
3594        let merge_lock = repo_merge_lock(repo);
3595        let _merge_slot = merge_lock.lock().await;
3596        forge.merge(repo, &argv).await
3597    };
3598    match out {
3599        Ok((true, _)) => {
3600            state.land_armed_head = None;
3601            state.event("land", "auto-merge disabled");
3602            state.save().map_err(|e| format!("{e:#}"))?;
3603            Ok(())
3604        }
3605        Ok((false, msg)) => Err(msg),
3606        Err(e) => Err(format!("{e:#}")),
3607    }
3608}
3609
3610/// [`stop`], first taking back an armed auto-merge so a pull request magi
3611/// gave up on does not merge on its own later. A failure to disarm is added
3612/// to the reason rather than hiding it.
3613async fn stop_disarmed<F: Forge>(
3614    forge: &F,
3615    state: &mut RunState,
3616    repo: &Path,
3617    pr: &PrState,
3618    why: &str,
3619) -> Result<()> {
3620    if state.land_armed_head.is_none() {
3621        return stop(state, repo, pr, why).await;
3622    }
3623    match disarm(forge, state, repo, pr.number).await {
3624        Ok(()) => stop(state, repo, pr, why).await,
3625        Err(e) => {
3626            let why = format!("{why} (auto-merge could not be disabled and may still fire: {e})");
3627            stop(state, repo, pr, &why).await
3628        }
3629    }
3630}
3631
3632/// Check the persisted card again around awaits that can outlive an owner tap.
3633fn owner_requested_stop(state: &RunState) -> Result<bool> {
3634    let Some(binding) = &state.land_approval else {
3635        return Ok(false);
3636    };
3637    let q = ask::Questions::open().get_for_effects(&binding.question)?;
3638    Ok(q.run == state.id
3639        && q.node == APPROVAL_NODE
3640        && q.resolution()
3641            .as_deref()
3642            .is_some_and(crate::merge_decision::stops))
3643}
3644
3645/// Read stop choices before checks, repair or rebase. These are about stopping
3646/// ownership, so a changed head never cancels them as it cancels merge consent.
3647async fn owner_stop<F: Forge>(state: &mut RunState, pr: &mut PrState, forge: &F) -> Result<bool> {
3648    use crate::merge_decision as md;
3649    let Some(binding) = &state.land_approval else {
3650        return Ok(false);
3651    };
3652    let q = ask::Questions::open().get_for_effects(&binding.question)?;
3653    let Some(choice) = q.resolution().filter(|c| md::stops(c)) else {
3654        return Ok(false);
3655    };
3656    if q.run != state.id || q.node != APPROVAL_NODE {
3657        bail!("stop decision names another run");
3658    }
3659    let target = q.merge_target.clone().unwrap_or_else(|| md::Target {
3660        pr: pr.url.clone(),
3661        head: binding.head.clone(),
3662        language: state.config.graph.language.clone(),
3663    });
3664    if target.pr != pr.url {
3665        bail!("stop decision names another PR");
3666    }
3667    if state.merge_decision.is_none() {
3668        state.merge_decision = Some(md::Decision {
3669            question: q.id.clone(),
3670            target,
3671            choice: choice.clone(),
3672            closed: false,
3673            replacement_run: None,
3674            replacement_pr: None,
3675        });
3676        state.save()?;
3677    }
3678    let repo = state.repo.clone();
3679    // Always disable, including arms left by an older driver.
3680    if let Err(e) = disarm(forge, state, &repo, pr.number).await {
3681        stop(state, &repo, pr, &format!("owner stop requested, but auto-merge could not be disabled: {e}; no repair or replacement started")).await?;
3682        return Ok(true);
3683    }
3684    if choice.eq_ignore_ascii_case(HOLD) {
3685        stop(
3686            state,
3687            &repo,
3688            pr,
3689            "owner held the decision: PR left open; no further repair or merge work",
3690        )
3691        .await?;
3692        return Ok(true);
3693    }
3694    if md::selected_agent(&choice).is_some()
3695        || state
3696            .origin
3697            .as_ref()
3698            .and_then(|o| o.task.as_ref())
3699            .is_some()
3700    {
3701        let owners: Vec<_> = crate::queue::Queue::open()
3702            .list()
3703            .into_iter()
3704            .filter(|task| task.execution_runs().last() == Some(&state.id))
3705            .collect();
3706        let owner = (owners.len() == 1).then(|| &owners[0]);
3707        if !owner.is_some_and(|task| {
3708            task.execution_runs().last() == Some(&state.id)
3709                && (!task
3710                    .operator_decided_at
3711                    .is_some_and(|at| at > q.answered_at.unwrap_or(q.asked_at))
3712                    || task.resumption.as_ref().is_some_and(|release| {
3713                        release.question_id.as_deref() == Some(q.id.as_str())
3714                            && task.operator_decided_at == Some(release.at)
3715                    }))
3716        }) {
3717            stop(state, &repo, pr, "replacement requires the current original queue task owner and an unsuperseded answer; PR left open").await?;
3718            return Ok(true);
3719        }
3720    }
3721    if pr.state == PrLifecycle::Merged {
3722        stop(
3723            state,
3724            &repo,
3725            pr,
3726            "PR already merged; withdrawal/replacement cannot be applied",
3727        )
3728        .await?;
3729        return Ok(true);
3730    }
3731    let comment = format!(
3732        "{MARKER}\nOwner decision on question {}: {}. Previous attempt: `{}`. Original instruction and review history remain in the task record.",
3733        q.id, choice, state.id
3734    );
3735    if pr.state == PrLifecycle::Open {
3736        if let Err(e) = forge.close(&repo, &pr.url, &comment).await {
3737            stop(
3738                state,
3739                &repo,
3740                pr,
3741                &format!(
3742                    "owner requested closure but it failed: {e}; task held, no replacement started"
3743                ),
3744            )
3745            .await?;
3746            return Ok(true);
3747        }
3748    }
3749    let confirmed = forge.view(&repo, &pr.url).await?;
3750    if confirmed.pr.state != PrLifecycle::Closed {
3751        stop(
3752            state,
3753            &repo,
3754            pr,
3755            "PR closure was not confirmed; task held, no replacement started",
3756        )
3757        .await?;
3758        return Ok(true);
3759    }
3760    *pr = confirmed.pr;
3761    state.merge_decision.as_mut().unwrap().closed = true;
3762    if let Some(record) = &mut state.pr {
3763        record.state = "closed".into();
3764    }
3765    state.status = RunStatus::Superseded;
3766    state.merge = Some(MergeOutcome {
3767        mode: MergeMode::Pr,
3768        ok: false,
3769        detail: format!("owner decision: {choice}; PR closure confirmed"),
3770        empty: false,
3771    });
3772    state.event(
3773        "land",
3774        format!(
3775            "{} applied: PR closure confirmed; old execution retired",
3776            choice
3777        ),
3778    );
3779    state.save()?;
3780    Ok(true)
3781}
3782
3783/// Keep an unstarted verification resumable without charging a task attempt.
3784fn check_landing_resources(
3785    state: &mut RunState,
3786    node: &str,
3787    outcomes: &[crate::run::CommandOutcome],
3788) -> Result<()> {
3789    if let Some(blocked) = outcomes.iter().find(|outcome| outcome.resource_blocked) {
3790        let detail = format!("{}: {}", blocked.command, blocked.output_tail);
3791        state
3792            .resource_block
3793            .get_or_insert_with(|| crate::run::ResourceBlock {
3794                cause: crate::run::ResourceBlockCause::Other,
3795                node: node.into(),
3796                kind: "shared build cache".into(),
3797                detail: detail.clone(),
3798                at: jiff::Timestamp::now(),
3799            });
3800        state.event("resource", &detail);
3801        state.save()?;
3802        bail!("landing verification could not start: {detail}");
3803    }
3804    Ok(())
3805}
3806
3807/// Gate the local winner and publish that exact SHA, retaining the saved lease.
3808/// A push completed before a crash is recoverable only when its SHA was gated.
3809async fn publish_landing_head<F: Forge>(
3810    state: &mut RunState,
3811    observed: &str,
3812    pr_url: &str,
3813    forge: &F,
3814) -> Result<String> {
3815    crate::pr_head::ensure_owner(state)?;
3816    let winner = state.winner().cloned().context("landing has no winner")?;
3817    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
3818    let expected = state.pr_pushed_head.as_deref().unwrap_or(observed);
3819    anyhow::ensure!(
3820        observed == expected
3821            || (observed == head
3822                && state.gate_head.as_deref() == Some(&head)
3823                && state.gate_allows_progress()),
3824        "public head moved outside this run; refusing to overwrite it"
3825    );
3826    anyhow::ensure!(
3827        git::is_clean(&winner.worktree).await?,
3828        "landing worktree is dirty"
3829    );
3830    if state.gate_head.as_deref() != Some(&head)
3831        || !state.gate_ran
3832        || !state.gate_commands_allow_progress()
3833    {
3834        state.reconcile_verification_head(&head);
3835        state.gate.clear();
3836        state.gate_head = None;
3837        state.gate_ran = false;
3838        state.pre_gate.clear();
3839        state.pre_gate_commit = None;
3840        state.save()?;
3841        let inherited = crate::repo_lock::WaitPolicy::current();
3842        let wait = crate::repo_lock::WaitPolicy::new(
3843            Duration::from_secs(state.config.graph.timeout_resource_wait),
3844            move || inherited.cancelled(),
3845        );
3846        let mut outcomes = crate::graph::run_landing_gate(state, &winner, &wait).await?;
3847        loop {
3848            if outcomes.iter().any(|outcome| outcome.resource_blocked) {
3849                state.gate = outcomes.clone();
3850                check_landing_resources(state, "gate", &outcomes)?;
3851            }
3852            if outcomes.iter().all(|o| o.ok()) {
3853                break;
3854            }
3855            match Box::pin(crate::graph::repair_landing_gate(state, &winner, &outcomes)).await? {
3856                crate::graph::GateFix::Retry => {
3857                    outcomes = crate::graph::run_landing_gate(state, &winner, &wait).await?;
3858                }
3859                crate::graph::GateFix::Stop => break,
3860                crate::graph::GateFix::Defer => {
3861                    // The repair checks e2e immediately, before the next gate.
3862                    // Preserve a cache wait here as well as below; otherwise
3863                    // the daemon charges an attempt for unstarted verification.
3864                    if let Some(e2e) = &state.gate_repair_e2e {
3865                        let outcomes = e2e.outcomes.clone();
3866                        check_landing_resources(state, "e2e", &outcomes)?;
3867                    }
3868                    bail!("landing gate repair deferred");
3869                }
3870            }
3871        }
3872        state.gate = outcomes;
3873        state.gate_ran = true;
3874        state.save()?;
3875    }
3876    let inherited = crate::repo_lock::WaitPolicy::current();
3877    let wait = crate::repo_lock::WaitPolicy::new(
3878        Duration::from_secs(state.config.graph.timeout_resource_wait),
3879        move || inherited.cancelled(),
3880    );
3881    let checked = state
3882        .gate_head
3883        .clone()
3884        .context("landing gate has no checked SHA")?;
3885    anyhow::ensure!(
3886        git::rev_parse(&winner.worktree, "HEAD").await? == checked
3887            && git::is_clean(&winner.worktree).await?,
3888        "landing tree changed after gate"
3889    );
3890    let e2e = crate::graph::check_gate_repair_e2e(state, &winner, &wait).await?;
3891    if matches!(e2e, crate::graph::GateFix::Defer) {
3892        let outcomes = state
3893            .gate_repair_e2e
3894            .as_ref()
3895            .context("deferred landing e2e has no outcomes")?
3896            .outcomes
3897            .clone();
3898        check_landing_resources(state, "e2e", &outcomes)?;
3899    }
3900    anyhow::ensure!(
3901        matches!(e2e, crate::graph::GateFix::Retry),
3902        "post-repair e2e has not passed on the landing head; nothing published"
3903    );
3904    anyhow::ensure!(
3905        git::rev_parse(&winner.worktree, "HEAD").await? == checked
3906            && git::is_clean(&winner.worktree).await?,
3907        "landing tree changed during post-repair e2e"
3908    );
3909    anyhow::ensure!(
3910        crate::graph::verify_current_head(state, &winner, &wait).await?,
3911        "current head e2e has not passed; nothing published"
3912    );
3913    anyhow::ensure!(
3914        state.gate_allows_progress(),
3915        "landing gate failed; nothing published"
3916    );
3917    crate::pr_head::ensure_owner(state)?;
3918    if owner_requested_stop(state)? {
3919        bail!("owner requested stop before publication");
3920    }
3921    let current = forge.view(&state.repo, pr_url).await?;
3922    anyhow::ensure!(
3923        current.pr.state == PrLifecycle::Open,
3924        "PR closed or merged while gating; nothing published"
3925    );
3926    anyhow::ensure!(
3927        current.head == observed || current.head == checked,
3928        "PR head changed while gating; nothing published"
3929    );
3930    anyhow::ensure!(
3931        crate::foreign_checkout::write_back(state, &checked).await?,
3932        "foreign checkout delivery is blocked; see the run events"
3933    );
3934    let public = state.pr_branch().unwrap_or(&winner.branch).to_owned();
3935    let lease = format!("--force-with-lease=refs/heads/{public}:{observed}");
3936    let refspec = format!("{checked}:refs/heads/{public}");
3937    let lock = repo_merge_lock(&state.repo);
3938    let _slot = lock.lock().await;
3939    let pushed = git::git_raw(
3940        &winner.worktree,
3941        &["push", &lease, &state.config.merge.remote, &refspec],
3942    )
3943    .await?;
3944    anyhow::ensure!(
3945        pushed.ok(),
3946        "publishing gated landing head failed: {}",
3947        pushed.stderr
3948    );
3949    state.pr_pushed_head = Some(checked.clone());
3950    state.land_sync_pending = false;
3951    state.save()?;
3952    Ok(checked)
3953}
3954
3955/// A scratch rebase moves the winner ref before its index and files. Recover
3956/// only a tree proven unchanged since the saved start; never discard edits.
3957async fn restore_landing_worktree(state: &mut RunState) -> Result<()> {
3958    let winner = state.winner().cloned().context("landing has no winner")?;
3959    let inherited = crate::repo_lock::WaitPolicy::current();
3960    let wait = crate::repo_lock::WaitPolicy::new(
3961        Duration::from_secs(state.config.graph.timeout_resource_wait),
3962        move || inherited.cancelled(),
3963    );
3964    let _coordination = crate::repo_lock::SeatLease::operation_with(
3965        &winner.worktree,
3966        state.config.coordination.as_ref(),
3967        &wait,
3968    )
3969    .await?;
3970    if !git::is_clean(&winner.worktree).await? {
3971        let from = state
3972            .land_rebase_from
3973            .as_deref()
3974            .context("landing worktree is dirty")?;
3975        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
3976        anyhow::ensure!(head != from, "landing worktree is dirty");
3977        for args in [
3978            vec!["diff", "--cached", "--quiet", from],
3979            vec!["diff", "--quiet"],
3980        ] {
3981            anyhow::ensure!(
3982                git::git_raw(&winner.worktree, &args).await?.ok(),
3983                "landing worktree has edits beyond the interrupted rebase"
3984            );
3985        }
3986        // Preserve build artifacts and local files, including ignored ones.
3987        // read-tree can overwrite ignored paths, so reject collisions with
3988        // the new tree (including file/directory conflicts) before updating.
3989        let untracked = git::git(&winner.worktree, &["ls-files", "--others", "-z"]).await?;
3990        let tracked = git::git(
3991            &winner.worktree,
3992            &["ls-tree", "-r", "--name-only", "-z", "HEAD"],
3993        )
3994        .await?;
3995        for local in untracked.split('\0').filter(|p| !p.is_empty()) {
3996            anyhow::ensure!(
3997                !tracked.split('\0').filter(|p| !p.is_empty()).any(|path| {
3998                    path == local
3999                        || path
4000                            .strip_prefix(local)
4001                            .is_some_and(|rest| rest.starts_with('/'))
4002                        || local
4003                            .strip_prefix(path)
4004                            .is_some_and(|rest| rest.starts_with('/'))
4005                }),
4006                "landing worktree has an untracked or ignored path conflicting with HEAD: {local}"
4007            );
4008        }
4009        git::git(&winner.worktree, &["read-tree", "-m", "-u", "HEAD"]).await?;
4010    }
4011    if let (Some(checkout), Some(from)) = (&state.foreign_checkout, &state.land_rebase_from) {
4012        anyhow::ensure!(
4013            git::is_ancestor(&winner.worktree, &checkout.synced_head, from).await,
4014            "landing synchronization started outside the foreign checkout history"
4015        );
4016        if !git::is_ancestor(&winner.worktree, from, "HEAD").await {
4017            // The rebase's tree already includes the base and the fixer's
4018            // resolutions. Retain that exact tree, but join the pre-sync
4019            // history so delivery remains fast-forward. Keep the checkpoint
4020            // until this succeeds: a crash after rebase (or after this merge)
4021            // must recover through this same idempotent path before gating.
4022            git::git(
4023                &winner.worktree,
4024                &[
4025                    "-c",
4026                    "core.hooksPath=/dev/null",
4027                    "merge",
4028                    "--strategy=ours",
4029                    "--no-ff",
4030                    "--no-autostash",
4031                    "--no-edit",
4032                    "-m",
4033                    "Merge pre-sync history into the repaired landing tree",
4034                    from,
4035                ],
4036            )
4037            .await?;
4038        }
4039    }
4040    crate::worktree_setup::prepare_with(
4041        &state.config,
4042        &state.repo,
4043        &winner.worktree,
4044        crate::build_target::Coordination::Held(_coordination.as_ref()),
4045    )
4046    .await?;
4047    state.land_rebase_from = None;
4048    state.save()?;
4049    Ok(())
4050}
4051
4052async fn rebase_landing_worktree(
4053    state: &mut RunState,
4054    onto: &str,
4055) -> Result<crate::rebase::Rebased> {
4056    restore_landing_worktree(state).await?;
4057    let winner = state.winner().cloned().context("landing has no winner")?;
4058    let scratch = state.dir().join("rebase");
4059    let target = match state.land_sync_target.clone() {
4060        Some(target) => {
4061            crate::rebase::prepare(state, &scratch, &winner.branch).await?;
4062            target
4063        }
4064        // Older records lack the target checkpoint, but Git retains the
4065        // exact target of an interrupted operation. It is a continuation too.
4066        None if crate::rebase::checked_progress(state, &scratch, "").await? => {
4067            crate::rebase::rebase_target(&scratch).await?
4068        }
4069        None => {
4070            anyhow::ensure!(
4071                state.land_sync_attempts < state.config.graph.land_rounds,
4072                "landing base synchronization budget exhausted"
4073            );
4074            let target = git::rev_parse(&state.repo, onto).await?;
4075            crate::rebase::prepare(state, &scratch, &winner.branch).await?;
4076            state.land_sync_attempts += 1;
4077            state.land_sync_target = Some(target.clone());
4078            target
4079        }
4080    };
4081    state.land_sync_target = Some(target.clone());
4082    state.land_sync_pending = true;
4083    state.land_rebase_from = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
4084    state.save()?;
4085    // A continuation owns the attempt already charged above, including a
4086    // crash before the scratch rebase started. Finish its pinned base first;
4087    // a newer base must use another attempt on the next observation.
4088    let result = crate::rebase::rebase_prepared(state, &scratch, &winner.branch, &target).await?;
4089    state.land_sync_target = None;
4090    state.save()?;
4091    if result == crate::rebase::Rebased::Applied {
4092        restore_landing_worktree(state).await?;
4093    }
4094    Ok(result)
4095}
4096
4097/// Reconcile a stopped landing before changing its branch. This also handles
4098/// old records whose graph status or merge detail no longer identifies land.
4099async fn resume_landing_head<F: Forge>(
4100    state: &mut RunState,
4101    observed: &str,
4102    pr_url: &str,
4103    forge: &F,
4104    reason: Option<Blocking>,
4105) -> Result<String> {
4106    crate::pr_head::ensure_owner(state)?;
4107    let winner = state.winner().cloned().context("landing has no winner")?;
4108    let local = git::rev_parse(&winner.worktree, "HEAD").await?;
4109    let expected = state
4110        .pr_pushed_head
4111        .as_deref()
4112        .or(state.gate_head.as_deref())
4113        .context("missing public head lease")?;
4114    anyhow::ensure!(
4115        observed == expected
4116            || (observed == local
4117                && ((state.gate_head.as_deref() == Some(&local) && state.gate_allows_progress())
4118                    || git::is_ancestor(&winner.worktree, expected, &local).await)),
4119        "public head moved outside this run; refusing to sync"
4120    );
4121    // An operator may have extended and published the winner while approval
4122    // was pending. Matching local/public history can be adopted as the lease,
4123    // but publish_landing_head must gate its new SHA before proceeding. A
4124    // remote-only or divergent update still cannot be overwritten.
4125    // Save reconciliation before rebasing again; a prior push may have reached
4126    // the remote immediately before the previous driver's last save.
4127    state.pr_pushed_head = Some(observed.to_owned());
4128    state.save()?;
4129    restore_landing_worktree(state).await?;
4130    // Recover a rebase that finished before its completion checkpoint was
4131    // saved. Restoration above has already reconciled its files and ancestry.
4132    let scratch = state.dir().join("rebase");
4133    if let Some(target) = state.land_sync_target.clone()
4134        && !crate::rebase::checked_progress(state, &scratch, "").await?
4135        && git::ancestry(&winner.worktree, &target, &local).await?
4136    {
4137        state.land_sync_target = None;
4138        state.save()?;
4139    }
4140    let remote = state.config.merge.remote.clone();
4141    let base = state.base_branch.clone();
4142    let fetched = git::fetch(&state.repo, &remote, &base).await?;
4143    anyhow::ensure!(
4144        fetched.ok(),
4145        "cannot fetch landing base: {}",
4146        fetched.stderr
4147    );
4148    anyhow::ensure!(
4149        !owner_requested_stop(state)?,
4150        "owner requested stop before base synchronization"
4151    );
4152    let onto = format!("{remote}/{base}");
4153    let tip = git::rev_parse(&state.repo, &onto).await?;
4154    let contains_base = git::ancestry(&state.repo, &tip, &local)
4155        .await
4156        .context("could not determine whether the landing head contains the fetched base")?;
4157    anyhow::ensure!(
4158        reason != Some(Blocking::Behind) || !contains_base,
4159        "BEHIND reported but the fetched base is already included; synchronization made no progress"
4160    );
4161    if !contains_base || reason == Some(Blocking::Conflict) {
4162        match rebase_landing_worktree(state, &onto).await? {
4163            crate::rebase::Rebased::Applied => {}
4164            crate::rebase::Rebased::Stopped(why) => bail!("landing rebase stopped: {why}"),
4165        }
4166    }
4167    if reason == Some(Blocking::Behind) {
4168        anyhow::ensure!(
4169            git::rev_parse(&winner.worktree, "HEAD").await? != local,
4170            "BEHIND synchronization left the head unchanged"
4171        );
4172    }
4173    publish_landing_head(state, observed, pr_url, forge).await
4174}
4175
4176/// Share the synchronization path with structured evidence retained after a refusal.
4177async fn synchronize_landing<F: Forge>(
4178    state: &mut RunState,
4179    pr: &mut PrState,
4180    observed: &str,
4181    pr_url: &str,
4182    forge: &F,
4183) -> Result<Option<String>> {
4184    if owner_stop(state, pr, forge).await? {
4185        return Ok(None);
4186    }
4187    state.event(
4188        "land",
4189        format!("{} base synchronization: {:?}", pr.url, pr.blocking),
4190    );
4191    state.save()?;
4192    let synced = resume_landing_head(state, observed, pr_url, forge, Some(pr.blocking)).await;
4193    if owner_stop(state, pr, forge).await? {
4194        return Ok(None);
4195    }
4196    match synced {
4197        Ok(head) => {
4198            if let Some(branch) = state.winner().map(|w| w.branch.clone()) {
4199                crate::graph::refresh_reviewed_commits(state, &branch).await;
4200            }
4201            Ok(Some(head))
4202        }
4203        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => Err(e),
4204        Err(e) => {
4205            let repo = state.repo.clone();
4206            stop(
4207                state,
4208                &repo,
4209                pr,
4210                &format!("could not synchronize landing base: {e:#}"),
4211            )
4212            .await?;
4213            Ok(None)
4214        }
4215    }
4216}
4217
4218async fn land_with<F: Forge>(state: &mut RunState, pr_url: &str, forge: &F) -> Result<PrState> {
4219    crate::pr_head::ensure_owner(state)?;
4220    state.land_unrelated = None;
4221    let reopening_hold = crate::merge_decision::resumable_hold(state);
4222    let repo = state.repo.clone();
4223    let budget = state.config.graph.land_rounds;
4224    let mut round = 0usize;
4225    let ci = state.config.merge.ci.expectation();
4226    if ci == CiExpectation::Absent {
4227        state.event(
4228            "land",
4229            "CI not expected ([merge] ci = \"none\"); check status ignored",
4230        );
4231    }
4232    let mut waited = Duration::ZERO;
4233    // Comment bodies the fixer has already been shown. A comment is
4234    // outstanding until it has been handed over once; after that it is a
4235    // recorded decision, not an open question, and re-feeding it would loop the
4236    // budget away on a comment the fixer already declined with an argument.
4237    let mut shown: BTreeSet<String> = BTreeSet::new();
4238    // Await the last successfully published head, including across resumes.
4239    let mut awaiting_head: Option<String> = state.pr_pushed_head.clone();
4240    // Whether a settled-checks refusal has already been given its one re-look.
4241    let mut rechecked = false;
4242
4243    // Marks the run resumable through exactly this function, not through a
4244    // fresh competition: `RunStatus::resumable` excludes only `Merged`,
4245    // `Ready` and `Failed`, and `merge`'s own re-entry guard looks for this
4246    // status specifically to know a resumed run belongs back in `land`
4247    // rather than at a second `gh pr create`. Set on every entry - fresh or
4248    // resumed - because a resume that parked here again must keep reading
4249    // `Landing`, not whatever a first pass through `merge` left behind.
4250    state.status = RunStatus::Landing;
4251    state.event("land", format!("watching {pr_url}"));
4252    state.save()?;
4253
4254    // An armed merge recorded by an earlier pass may or may not have reached
4255    // the forge (the record is written before the call). It is taken back on
4256    // the first observation, where a pull request is known to stop with.
4257    let mut resumed_armed = state.land_armed_head.is_some();
4258
4259    'landing: loop {
4260        let seen = forge.view(&repo, pr_url).await?;
4261        let mut pr = seen.pr.clone();
4262        pr.review_comments.retain(|c| !shown.contains(&c.body));
4263        state.pr = Some(crate::run::PrRecord {
4264            url: pr.url.clone(),
4265            number: pr.number,
4266            state: pr.state.as_str().to_owned(),
4267            checks: pr.checks.as_str().to_owned(),
4268            round,
4269            rounds: budget,
4270            red_at_merge: Vec::new(),
4271        });
4272        state.save()?;
4273
4274        if pr.state == PrLifecycle::Open {
4275            state.observe_branch_owner_holds(&seen.head).await;
4276            state.save()?;
4277        }
4278        crate::pr_head::ensure_owner(state)?;
4279        if reopening_hold {
4280            anyhow::ensure!(
4281                pr.state == PrLifecycle::Open,
4282                "held PR is no longer open; cannot request a fresh decision"
4283            );
4284            // An explicit resume authorizes a fresh question only. Preserve the
4285            // answered card, and never enter repair/rebase/merge on this pass.
4286            disarm(forge, state, &repo, pr.number)
4287                .await
4288                .map_err(anyhow::Error::msg)?;
4289            let previous = state.merge_decision.take();
4290            let binding = state.land_approval.take();
4291            state.config.graph.land_approval = true;
4292            let subject = merge_subject(
4293                crate::graph::landing_title(state, &seen.title),
4294                &crate::graph::landing_subject_source(state),
4295            );
4296            let contested = contested_to_ask(state);
4297            if let Err(error) =
4298                approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head).await
4299            {
4300                state.merge_decision = previous;
4301                state.land_approval = binding;
4302                return Err(error);
4303            }
4304            state.end_pass_parked(crate::run::ParkCause::Question);
4305            state.parked = true;
4306            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()));
4307            state.save()?;
4308            return Ok(pr);
4309        }
4310        if owner_stop(state, &mut pr, forge).await? {
4311            return Ok(pr);
4312        }
4313
4314        if std::mem::take(&mut resumed_armed) && pr.state == PrLifecycle::Open {
4315            // An approval already given for the same head is reused, so
4316            // nothing is asked twice. A failed disable
4317            // stops the run with the record kept: pushing on could change the
4318            // head under an arm that is still live.
4319            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4320                let why = format!(
4321                    "a previous pass may have armed auto-merge and it could not be disabled \
4322                     on resume: {e}"
4323                );
4324                stop(state, &repo, &pr, &why).await?;
4325                return Ok(pr);
4326            }
4327        }
4328
4329        // The head moved away from the one auto-merge was armed on, by
4330        // someone other than this loop. The arm is pinned and would refuse to
4331        // merge the new commit, but the approval was for the old one: take it
4332        // back and go through the normal path again.
4333        if pr.state == PrLifecycle::Open
4334            && !seen.head.is_empty()
4335            && state
4336                .land_armed_head
4337                .as_deref()
4338                .is_some_and(|armed| !armed.eq_ignore_ascii_case(&seen.head))
4339        {
4340            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4341                let why = format!(
4342                    "the head moved while auto-merge was armed and it could not be disabled: {e}"
4343                );
4344                stop(state, &repo, &pr, &why).await?;
4345                return Ok(pr);
4346            }
4347        }
4348
4349        if state.land_sync_pending && pr.state == PrLifecycle::Open {
4350            // Disarming can outlive an owner answer. Consume it before our
4351            // own rebase invalidates the head shown on the decision card.
4352            if owner_stop(state, &mut pr, forge).await? {
4353                return Ok(pr);
4354            }
4355            let repair_answer = state.land_approval.as_ref().is_some_and(|binding| {
4356                binding.head.eq_ignore_ascii_case(&seen.head)
4357                    && ask::Questions::open()
4358                        .get_for_effects(&binding.question)
4359                        .is_ok_and(|q| {
4360                            q.run == state.id
4361                                && q.node == APPROVAL_NODE
4362                                && q.status == ask::QuestionStatus::Answered
4363                                && matches!(approval(q.resolution().as_deref()), Approval::Repair)
4364                        })
4365            });
4366            if repair_answer {
4367                let subject = merge_subject(
4368                    crate::graph::landing_title(state, &seen.title),
4369                    &crate::graph::landing_subject_source(state),
4370                );
4371                let contested = contested_to_ask(state);
4372                if matches!(
4373                    approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head).await?,
4374                    ApprovalGate::Repair
4375                ) {
4376                    if let Err(why) = disarm(forge, state, &repo, pr.number).await {
4377                        state.event("repair", format!("auto-merge could not be disabled: {why}; repair preflight will retry"));
4378                        state.save()?;
4379                    }
4380                    return Ok(pr);
4381                }
4382            }
4383            let synced = resume_landing_head(state, &seen.head, pr_url, forge, None).await;
4384            // A stop detected before publication must apply its durable
4385            // decision, even when verification returned an error meanwhile.
4386            if owner_stop(state, &mut pr, forge).await? {
4387                return Ok(pr);
4388            }
4389            let head = synced?;
4390            awaiting_head = Some(head);
4391            waited = Duration::ZERO;
4392            rechecked = false;
4393            // Read CI and approvals afresh, never from the pre-push observation.
4394            continue;
4395        }
4396
4397        // A stale base is independent of the CI rollup. Keep the public-head
4398        // lease, but synchronize before waiting for checks on the old tree.
4399        if pr.state == PrLifecycle::Open
4400            && pr.blocking == Blocking::Behind
4401            && bound_head(&seen.head, &seen.head, awaiting_head.as_deref()).is_some()
4402        {
4403            let synced = synchronize_landing(state, &mut pr, &seen.head, pr_url, forge).await?;
4404            let Some(head) = synced else {
4405                return Ok(pr);
4406            };
4407            awaiting_head = Some(head);
4408            rechecked = false;
4409            waited = Duration::ZERO;
4410            continue;
4411        }
4412
4413        if pr.state == PrLifecycle::Open {
4414            if bound_head(&seen.head, &seen.rollup_head, awaiting_head.as_deref()).is_none() {
4415                if waited >= WAIT_CEILING {
4416                    let want = awaiting_head.as_deref().unwrap_or_default();
4417                    let why = format!(
4418                        "the pull request's checks were still not about one readable head after \
4419                         {} minutes (expected {}, pull request points at {}, checks are for {}); \
4420                         someone may have pushed over it",
4421                        WAIT_CEILING.as_secs() / 60,
4422                        if want.is_empty() { "any" } else { want },
4423                        if seen.head.is_empty() {
4424                            "nothing readable"
4425                        } else {
4426                            &seen.head
4427                        },
4428                        if seen.rollup_head.is_empty() {
4429                            "nothing readable"
4430                        } else {
4431                            &seen.rollup_head
4432                        },
4433                    );
4434                    stop_disarmed(forge, state, &repo, &pr, &why).await?;
4435                    return Ok(pr);
4436                }
4437                waited += POLL;
4438                forge.poll().await;
4439                continue;
4440            }
4441            // Reset once, when the awaited head first shows up; resetting on
4442            // every re-observation would let a standing refusal wait forever.
4443            if awaiting_head.take().is_some() {
4444                // The checks now being read belong to the new head; give them
4445                // the same grace a fresh pull request gets.
4446                waited = Duration::ZERO;
4447            }
4448        }
4449
4450        // The merge-state grace is head-bound and durable. Reruns reset the
4451        // checks clock, but must not extend this deadline across resumes.
4452        let decision_wait = if pr.checks == Checks::Red && pr.blocking == Blocking::Unsaid {
4453            let first = state
4454                .land_unsaid
4455                .get_or_insert_with(|| (seen.head.clone(), forge.now()));
4456            if !first.0.eq_ignore_ascii_case(&seen.head) {
4457                *first = (seen.head.clone(), forge.now());
4458            }
4459            let elapsed = Duration::from_secs(forge.now().saturating_sub(first.1).max(0) as u64);
4460            state.save()?;
4461            elapsed
4462        } else {
4463            waited
4464        };
4465        let proposed = decide_with(&pr, round, budget, decision_wait, ci);
4466        if pr.checks == Checks::Red && pr.blocking == Blocking::Unsaid && proposed == Step::Wait {
4467            if waited >= WAIT_CEILING {
4468                stop_disarmed(
4469                    forge,
4470                    state,
4471                    &repo,
4472                    &pr,
4473                    "merge state remained unreadable; refusing to merge on a guess",
4474                )
4475                .await?;
4476                return Ok(pr);
4477            }
4478            waited += POLL;
4479            forge.poll().await;
4480            continue;
4481        }
4482
4483        // A failed workflow run is rerun once, judged by its own run rather
4484        // than by the rollup's aggregate: another run still pending, or a fix
4485        // budget already spent, must not keep a flaky failure from its one
4486        // rerun. It spends no round and no attempt.
4487        if ci == CiExpectation::Expected
4488            && pr.state == PrLifecycle::Open
4489            && state.config.graph.rerun_flaky_checks
4490        {
4491            let include_optional = pr.checks == Checks::Red
4492                && matches!(proposed, Step::Fix { .. } | Step::GiveUp { .. });
4493            let failing = rerunnable_with(&seen.contexts, include_optional);
4494            let now = forge.now();
4495            match rerun_step(&failing, state.land_reruns.as_ref(), &seen.head, now) {
4496                RerunStep::Rerun(runs) => {
4497                    let rec = state.land_reruns.get_or_insert_with(Default::default);
4498                    if !rec.head.eq_ignore_ascii_case(&seen.head) {
4499                        *rec = LandReruns {
4500                            head: seen.head.clone(),
4501                            runs: BTreeMap::new(),
4502                        };
4503                    }
4504                    for run in &runs {
4505                        rec.runs.insert(run.clone(), now);
4506                    }
4507                    // Durable before the call: a restart must not
4508                    // rerun the same run twice. A save that fails
4509                    // means no rerun.
4510                    state.save()?;
4511                    let mut any = false;
4512                    for run in &runs {
4513                        let names = failing
4514                            .iter()
4515                            .filter(|(_, r)| r.as_deref() == Some(run))
4516                            .map(|(l, _)| l.as_str())
4517                            .collect::<Vec<_>>()
4518                            .join(", ");
4519                        match forge.rerun(&repo, run).await {
4520                            Ok(()) => {
4521                                any = true;
4522                                state.event(
4523                                    "land",
4524                                    format!("reran failed check(s) {names} (run {run})"),
4525                                );
4526                            }
4527                            // Stays recorded: never a retry loop.
4528                            Err(e) => state.event(
4529                                "land",
4530                                format!("could not rerun check(s) {names} (run {run}): {e:#}"),
4531                            ),
4532                        }
4533                    }
4534                    state.save()?;
4535                    if any {
4536                        waited = Duration::ZERO;
4537                        forge.poll().await;
4538                        continue;
4539                    }
4540                }
4541                RerunStep::Grace => {
4542                    if waited >= WAIT_CEILING {
4543                        let why = format!(
4544                            "checks were still failing after a rerun and {} minutes",
4545                            WAIT_CEILING.as_secs() / 60
4546                        );
4547                        stop(state, &repo, &pr, &why).await?;
4548                        return Ok(pr);
4549                    }
4550                    waited += POLL;
4551                    forge.poll().await;
4552                    continue;
4553                }
4554                RerunStep::Fix => {}
4555            }
4556        }
4557
4558        let step = proposed;
4559        // Armed on exactly this head: the forge is doing the waiting. A
4560        // decision to merge (or keep waiting) is only watched, never re-armed
4561        // and never re-approved; anything else - a red check, a comment, a
4562        // conflict - falls through to its own arm, which disarms first.
4563        let armed_here = state
4564            .land_armed_head
4565            .as_deref()
4566            .is_some_and(|armed| armed.eq_ignore_ascii_case(&seen.head));
4567        if armed_here && matches!(step, Step::Merge | Step::Wait) {
4568            if waited >= WAIT_CEILING {
4569                let required = if seen.base.is_empty() {
4570                    None
4571                } else {
4572                    forge.required_contexts(&repo, &seen.base).await
4573                };
4574                let why = format!(
4575                    "auto-merge was armed on {} but the pull request did not merge within {} \
4576                     minutes ({})",
4577                    seen.head,
4578                    WAIT_CEILING.as_secs() / 60,
4579                    waiting_on(&seen.merge_state, &seen.contexts, required.as_ref())
4580                );
4581                stop_disarmed(forge, state, &repo, &pr, &why).await?;
4582                return Ok(pr);
4583            }
4584            waited += POLL;
4585            forge.poll().await;
4586            continue;
4587        }
4588        if armed_here && !matches!(step, Step::Done { .. }) {
4589            // Not merging or waiting any more: whatever is next may change the
4590            // head or give up, and neither may leave the arm standing.
4591            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4592                let why = format!("auto-merge could not be disabled: {e}");
4593                stop(state, &repo, &pr, &why).await?;
4594                return Ok(pr);
4595            }
4596        }
4597        if pr.checks == Checks::Red
4598            && matches!(step, Step::Fix { .. } | Step::GiveUp { .. })
4599            && pr.review_comments.is_empty()
4600            && let Some(evidence) = forge.attribution(state, &seen).await
4601            && evidence.unrelated(&seen.head, &pr.failing)
4602        {
4603            if owner_stop(state, &mut pr, forge).await? {
4604                return Ok(pr);
4605            }
4606            // Attribution does not authorize action against an unseen push.
4607            let fresh = forge.view(&repo, pr_url).await?;
4608            if fresh.head != seen.head
4609                || fresh.rollup_head != seen.rollup_head
4610                || fresh.pr.state != PrLifecycle::Open
4611                || fresh.pr.checks != Checks::Red
4612                || fresh.pr.failing != pr.failing
4613                || fresh
4614                    .pr
4615                    .review_comments
4616                    .iter()
4617                    .any(|c| !shown.contains(&c.body))
4618            {
4619                continue;
4620            }
4621            hold_unrelated(state, &pr, evidence).await?;
4622            return Ok(pr);
4623        }
4624        match step {
4625            Step::Wait => {
4626                if waited >= WAIT_CEILING {
4627                    let why = format!(
4628                        "checks were still running after {} minutes",
4629                        WAIT_CEILING.as_secs() / 60
4630                    );
4631                    stop(state, &repo, &pr, &why).await?;
4632                    return Ok(pr);
4633                }
4634                waited += POLL;
4635                forge.poll().await;
4636            }
4637            Step::Done { merged } => {
4638                if merged {
4639                    state.pr_merged_head = (!seen.head.is_empty()).then(|| seen.head.clone());
4640                }
4641                // Auto-merge is pinned to the approved head, but the forge's
4642                // own handling of a later push is not something magi can
4643                // see: if the pull request merged on another commit, say so
4644                // loudly rather than record a clean landing.
4645                if let Some(armed) = state.land_armed_head.take() {
4646                    if merged && !seen.head.is_empty() && !armed.eq_ignore_ascii_case(&seen.head) {
4647                        let msg = format!(
4648                            "{} merged on {} but the owner approved {armed}; review what landed",
4649                            pr.url, seen.head
4650                        );
4651                        tracing::warn!("{msg}");
4652                        state.event("land", msg);
4653                        // Only an arm left by an older build can get here.
4654                        // The wording is fixed so a repeat does not relight
4655                        // the notice.
4656                        crate::notices::raise_with(
4657                            crate::notices::Notice::warn(
4658                                &format!("merged-unapproved-head:{}", state.id),
4659                                "A pull request merged on a commit the owner did not approve; \
4660                                 review what landed",
4661                            )
4662                            .link(crate::notices::Link::Run {
4663                                id: state.id.clone(),
4664                            }),
4665                            &state.config.notify,
4666                        );
4667                    }
4668                }
4669                state.status = if merged {
4670                    RunStatus::Merged
4671                } else {
4672                    RunStatus::Ready
4673                };
4674                let detail = if merged {
4675                    format!("{} was merged", pr.url)
4676                } else {
4677                    format!("{} was closed without merging", pr.url)
4678                };
4679                state.merge = Some(MergeOutcome {
4680                    mode: MergeMode::Pr,
4681                    ok: merged,
4682                    detail: detail.clone(),
4683                    empty: false,
4684                });
4685                state.event("land", detail);
4686                state.save()?;
4687                write_pr_state_through(state, pr.state);
4688                return Ok(pr);
4689            }
4690            Step::Merge => {
4691                state.check_delivery_evidence(&seen.head)?;
4692                let subject = merge_subject(
4693                    crate::graph::landing_title(state, &seen.title),
4694                    &crate::graph::landing_subject_source(state),
4695                );
4696                // The owner sees the panel before the one irreversible step,
4697                // and an unanswered question is a hold: silence never merges.
4698                //
4699                // The dedicated policy includes existing consent and post-repair
4700                // decisions; repair choice availability never grants merge authority.
4701                let contested = contested_to_ask(state);
4702                if !approval_reasons(state).is_empty() {
4703                    match approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head)
4704                        .await?
4705                    {
4706                        ApprovalGate::Approved => {}
4707                        ApprovalGate::Repair => {
4708                            // The driver consumes the saved request under the existing
4709                            // run/task claim. No merge, no second run or task.
4710                            if let Err(why) = disarm(forge, state, &repo, pr.number).await {
4711                                state.event("repair", format!("auto-merge could not be disabled: {why}; repair preflight will retry"));
4712                                state.save()?;
4713                            }
4714                            return Ok(pr);
4715                        }
4716                        ApprovalGate::Held => {
4717                            // Another entry point may have saved a stop after
4718                            // the first read above. Apply its durable action.
4719                            if owner_stop(state, &mut pr, forge).await? {
4720                                return Ok(pr);
4721                            }
4722                            stop(
4723                                state,
4724                                &repo,
4725                                &pr,
4726                                "the owner did not approve the merge (held or unanswered)",
4727                            )
4728                            .await?;
4729                            return Ok(pr);
4730                        }
4731                        // Filed (or still standing from an earlier visit) and
4732                        // not yet answered. Park here rather than wait: the
4733                        // question survives on disk, the daemon hands this
4734                        // run's slot to something else, and a later resume
4735                        // re-enters `land`, finds the same question, and
4736                        // either merges or stops depending on what it says
4737                        // by then.
4738                        ApprovalGate::Pending => {
4739                            state.end_pass_parked(crate::run::ParkCause::Question);
4740                            state.parked = true;
4741                            state.event(
4742                                "land",
4743                                "parked awaiting merge approval - resumes once answered",
4744                            );
4745                            state.save()?;
4746                            return Ok(pr);
4747                        }
4748                    }
4749                }
4750                // Open and past the gate above, so `seen.head` is the commit
4751                // the checks were bound to and the owner approved.
4752                //
4753                // Merge directly, bound to that commit. Auto-merge is not
4754                // armed any more: the forge checks `--match-head-commit` only
4755                // when the request is made, so an arm outlives the head it
4756                // was made for, and a push of another commit whose
4757                // requirements are met first would merge without approval.
4758                // A direct merge is checked by the forge at the moment it
4759                // happens, so only the approved head can land.
4760                let observed_head = seen.head.clone();
4761                // Read the pull request again just before: the state seen
4762                // above can be a moment old.
4763                {
4764                    let fresh = forge.view(&repo, pr_url).await.ok();
4765                    if fresh.as_ref().is_some_and(|current| {
4766                        current.pr.state == PrLifecycle::Open
4767                            && current.head.eq_ignore_ascii_case(&observed_head)
4768                            && Blocking::of(&current.merge_state) == Blocking::Behind
4769                    }) {
4770                        pr.blocking = Blocking::Behind;
4771                        let synced =
4772                            synchronize_landing(state, &mut pr, &observed_head, pr_url, forge)
4773                                .await?;
4774                        let Some(head) = synced else {
4775                            return Ok(pr);
4776                        };
4777                        awaiting_head = Some(head);
4778                        rechecked = false;
4779                        waited = Duration::ZERO;
4780                        continue 'landing;
4781                    }
4782                    if !direct_merge_is_safe(
4783                        fresh.as_ref(),
4784                        &observed_head,
4785                        &shown,
4786                        round,
4787                        budget,
4788                        waited,
4789                        ci,
4790                    ) {
4791                        if waited >= WAIT_CEILING {
4792                            let why = "the pull request did not settle on the approved head \
4793                                       before it could be merged";
4794                            stop(state, &repo, &pr, why).await?;
4795                            return Ok(pr);
4796                        }
4797                        state.event(
4798                            "land",
4799                            "the pull request changed before merging; looking again",
4800                        );
4801                        waited += POLL;
4802                        forge.poll().await;
4803                        continue;
4804                    }
4805                }
4806                let argv = merge_argv_at(pr.number, &subject, &observed_head);
4807                let out = {
4808                    let merge_lock = repo_merge_lock(&repo);
4809                    let _merge_slot = merge_lock.lock().await;
4810                    crate::pr_head::ensure_owner(state)?;
4811                    if let Some(task_id) = state
4812                        .origin
4813                        .as_ref()
4814                        .and_then(|origin| origin.task.as_ref())
4815                    {
4816                        let task = crate::queue::Queue::open()
4817                            .get(task_id)
4818                            .context("cannot verify the task owner immediately before merge")?;
4819                        if task.execution_runs().last() != Some(&state.id)
4820                            || task.operator_held()
4821                            || task.status == crate::queue::TaskStatus::Done
4822                        {
4823                            bail!(
4824                                "task ownership or an operator hold superseded this merge approval"
4825                            );
4826                        }
4827                    }
4828                    if let Some(binding) = &state.land_approval {
4829                        let current = ask::Questions::open().get_for_effects(&binding.question)?;
4830                        if merge_consent_superseded(state, &current)?
4831                            || current.run != state.id
4832                            || !binding.head.eq_ignore_ascii_case(&observed_head)
4833                            || approval(current.resolution().as_deref()) != Approval::Merge
4834                            || current.merge_target.as_ref().is_some_and(|t| {
4835                                t.pr != pr.url || !t.head.eq_ignore_ascii_case(&observed_head)
4836                            })
4837                        {
4838                            bail!(
4839                                "merge decision is stale or no longer authorizes the reviewed head"
4840                            );
4841                        }
4842                    }
4843                    forge.merge(&repo, &argv).await?
4844                };
4845                if out.0 {
4846                    // Exit 0 is not proof of a merge: with a merge queue `gh`
4847                    // enqueues (or reports the pull request already queued)
4848                    // and succeeds while it is still open. Ask the forge; an
4849                    // unreadable answer is not a confirmation either, so it
4850                    // is looked at again rather than recorded as merged.
4851                    let confirmed = forge.view(&repo, pr_url).await.is_ok_and(|c| {
4852                        if c.pr.state == PrLifecycle::Merged {
4853                            state.pr_merged_head = (!c.head.is_empty()).then_some(c.head);
4854                            true
4855                        } else {
4856                            false
4857                        }
4858                    });
4859                    if !confirmed {
4860                        if waited >= WAIT_CEILING {
4861                            let why = "the merge request succeeded but the pull request \
4862                                       could not be confirmed merged after waiting";
4863                            stop(state, &repo, &pr, why).await?;
4864                            return Ok(pr);
4865                        }
4866                        state.event(
4867                            "land",
4868                            "merge accepted but the pull request is not confirmed merged yet; waiting",
4869                        );
4870                        state.save()?;
4871                        waited += POLL;
4872                        forge.poll().await;
4873                        continue;
4874                    }
4875                    pr.state = PrLifecycle::Merged;
4876                    state.status = RunStatus::Merged;
4877                    state.merge = Some(MergeOutcome {
4878                        mode: MergeMode::Pr,
4879                        ok: true,
4880                        detail: format!("gh {}", argv.join(" ")),
4881                        empty: false,
4882                    });
4883                    // The last `state.pr` snapshot is whatever the poll before
4884                    // this merge observed - still `open` - and nothing below
4885                    // refreshes it from GitHub again, so the UI's round rail
4886                    // would otherwise keep animating a merged run forever.
4887                    if let Some(pr_record) = state.pr.as_mut() {
4888                        pr_record.state = pr.state.as_str().to_owned();
4889                    }
4890                    state.event("land", format!("merged {} as `{subject}`", pr.url));
4891                    announce_red_merge(state, &pr).await;
4892                    state.save()?;
4893                    write_pr_state_through(state, pr.state);
4894                    return Ok(pr);
4895                }
4896                let after_seen = forge.view(&repo, pr_url).await.ok();
4897                let after = after_seen.as_ref().map(|s| s.pr.state);
4898                if let Some(outcome) = merged_after_all(&argv, &out.1, after) {
4899                    state.pr_merged_head = after_seen
4900                        .as_ref()
4901                        .map(|s| s.head.clone())
4902                        .filter(|h| !h.is_empty());
4903                    pr.state = PrLifecycle::Merged;
4904                    state.status = RunStatus::Merged;
4905                    state.merge = Some(outcome);
4906                    if let Some(pr_record) = state.pr.as_mut() {
4907                        pr_record.state = pr.state.as_str().to_owned();
4908                    }
4909                    state.event("land", format!("merged {} as `{subject}`", pr.url));
4910                    announce_red_merge(state, &pr).await;
4911                    state.save()?;
4912                    write_pr_state_through(state, pr.state);
4913                    return Ok(pr);
4914                }
4915                let verdict = classify_refusal(after_seen.as_ref(), rechecked, &observed_head, ci);
4916                match verdict {
4917                    Refused::Behind => {
4918                        pr.blocking = Blocking::Behind;
4919                        let synced =
4920                            synchronize_landing(state, &mut pr, &observed_head, pr_url, forge)
4921                                .await?;
4922                        let Some(head) = synced else {
4923                            return Ok(pr);
4924                        };
4925                        awaiting_head = Some(head);
4926                        rechecked = false;
4927                        waited = Duration::ZERO;
4928                        continue 'landing;
4929                    }
4930                    Refused::Final => {
4931                        let merge_state = after_seen
4932                            .as_ref()
4933                            .map(|s| s.merge_state.as_str())
4934                            .filter(|m| !m.is_empty())
4935                            .unwrap_or("unknown");
4936                        // Which refusal this was decides what a person has to
4937                        // do about it, so the two are worded apart; both carry
4938                        // the forge's own message.
4939                        let why = format!(
4940                            "the merge was refused: {} (merge state: {merge_state})",
4941                            out.1
4942                        );
4943                        stop(state, &repo, &pr, &why).await?;
4944                        return Ok(pr);
4945                    }
4946                    verdict => {
4947                        // Back to the top, which re-decides and passes the
4948                        // approval gate again, a poll later. `waited` is not
4949                        // reset here: only a pushed fix restarts it, or a
4950                        // standing refusal would wait forever.
4951                        if waited >= WAIT_CEILING {
4952                            let why = format!(
4953                                "the merge was still refused after {} minutes: {}",
4954                                WAIT_CEILING.as_secs() / 60,
4955                                out.1
4956                            );
4957                            stop(state, &repo, &pr, &why).await?;
4958                            return Ok(pr);
4959                        }
4960                        if verdict == Refused::Recheck {
4961                            rechecked = true;
4962                        }
4963                        state.event(
4964                            "land",
4965                            "merge refused while the branch policy is not satisfied yet; waiting",
4966                        );
4967                        state.save()?;
4968                        waited += POLL;
4969                        forge.poll().await;
4970                    }
4971                }
4972            }
4973            Step::Rebase => {
4974                let synced = synchronize_landing(state, &mut pr, &seen.head, pr_url, forge).await?;
4975                let Some(head) = synced else {
4976                    return Ok(pr);
4977                };
4978                awaiting_head = Some(head);
4979                rechecked = false;
4980                waited = Duration::ZERO;
4981                continue 'landing;
4982            }
4983            Step::GiveUp { reason } => {
4984                stop(state, &repo, &pr, &reason).await?;
4985                return Ok(pr);
4986            }
4987            Step::Fix { reason } => {
4988                round += 1;
4989                waited = Duration::ZERO;
4990                for c in &pr.review_comments {
4991                    shown.insert(c.body.clone());
4992                }
4993                state.event("land", format!("round {round}: {reason}"));
4994                state.save()?;
4995
4996                let logs = failing_logs(&repo, &seen.failing_urls).await;
4997                let was_red = pr.checks == Checks::Red;
4998                if owner_stop(state, &mut pr, forge).await? {
4999                    return Ok(pr);
5000                }
5001                let fixed = forge.fix(state, &pr, round, budget, &reason, &logs).await?;
5002                if owner_stop(state, &mut pr, forge).await? {
5003                    return Ok(pr);
5004                }
5005                match fixed {
5006                    Fixed::Committed { head } => {
5007                        // Whatever the next look shows may still be the
5008                        // previous head; see `awaiting_new_head`.
5009                        state.pr_pushed_head = Some(head.clone());
5010                        awaiting_head = Some(head);
5011                        rechecked = false;
5012                        waited = Duration::ZERO;
5013                        forge.poll().await;
5014                    }
5015                    Fixed::Declined if was_red => {
5016                        // Review comments may have required this round even
5017                        // when CI was unrelated. Once the fixer has read them,
5018                        // use the same structural attribution before charging
5019                        // a no-commit stop to the task.
5020                        if let Some(evidence) = forge.attribution(state, &seen).await
5021                            && evidence.unrelated(&seen.head, &pr.failing)
5022                        {
5023                            let fresh = forge.view(&repo, pr_url).await?;
5024                            if fresh.head != seen.head
5025                                || fresh.rollup_head != seen.rollup_head
5026                                || fresh.pr.state != PrLifecycle::Open
5027                                || fresh.pr.checks != Checks::Red
5028                                || fresh.pr.failing != pr.failing
5029                                || fresh
5030                                    .pr
5031                                    .review_comments
5032                                    .iter()
5033                                    .any(|c| !shown.contains(&c.body))
5034                            {
5035                                continue;
5036                            }
5037                            if owner_stop(state, &mut pr, forge).await? {
5038                                return Ok(pr);
5039                            }
5040                            hold_unrelated(state, &pr, evidence).await?;
5041                            return Ok(pr);
5042                        }
5043                        let why = format!(
5044                            "the fixer produced no commit while {} check(s) were failing \
5045                             ({}); stopping instead of looping on an unchanged tree",
5046                            pr.failing.len(),
5047                            pr.failing.join(", ")
5048                        );
5049                        stop(state, &repo, &pr, &why).await?;
5050                        return Ok(pr);
5051                    }
5052                    // Comment-driven round with no commit: the fixer read the
5053                    // comments and changed nothing, which is a decision it is
5054                    // allowed to make. The comments are recorded as shown, so
5055                    // the next observation sees a clean pull request.
5056                    Fixed::Declined => state.event(
5057                        "land",
5058                        format!("round {round}: fixer declined the comments, nothing committed"),
5059                    ),
5060                    Fixed::Deferred => {
5061                        // No fixer was available to judge these comments or
5062                        // checks. Keep the previous completed-round count and
5063                        // return without handing the PR off as a task failure.
5064                        state.status = RunStatus::Blocked;
5065                        state.save()?;
5066                        return Ok(pr);
5067                    }
5068                    Fixed::Failed(why) => {
5069                        stop(state, &repo, &pr, &format!("the fix round failed: {why}")).await?;
5070                        return Ok(pr);
5071                    }
5072                }
5073                state.save()?;
5074            }
5075        }
5076    }
5077}
5078
5079/// Owner decision for a CI failure independently reproduced on the base.
5080pub const CI_HOLD_NODE: &str = "land-ci-unrelated";
5081
5082/// Durable machine-hold evidence, bound to one observed PR head.
5083#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5084pub struct CiHold {
5085    /// Head that exhibited the independently reproduced failures.
5086    pub head: String,
5087    /// Typed owner question controlling resumption.
5088    pub question: String,
5089    /// Complete structured facts used to attribute the failures.
5090    pub evidence: CiEvidence,
5091}
5092
5093/// Only structured forge annotations are compared, never log prose.
5094#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
5095struct CiFailure {
5096    path: String,
5097    start_line: u64,
5098    end_line: u64,
5099    title: String,
5100    message: String,
5101}
5102
5103#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5104struct CiCheckEvidence {
5105    label: String,
5106    head_check: u64,
5107    base_check: u64,
5108    app: u64,
5109    run: String,
5110    base_run: String,
5111    head_failures: Vec<CiFailure>,
5112    base_failures: Vec<CiFailure>,
5113    rerun_exhausted: bool,
5114}
5115
5116/// Pinned Git diff and forge failure annotations used for CI attribution.
5117#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5118pub struct CiEvidence {
5119    head: String,
5120    base: String,
5121    changed: Vec<String>,
5122    checks: Vec<CiCheckEvidence>,
5123}
5124
5125impl CiEvidence {
5126    /// Every red check must have the same located failure on the base, outside
5127    /// the diff. Changes to CI/build configuration invalidate this inference.
5128    fn unrelated(&self, head: &str, failing: &[String]) -> bool {
5129        if self.head != head
5130            || self.base.is_empty()
5131            || failing.is_empty()
5132            || self.changed.iter().any(|p| {
5133                p.starts_with(".github/")
5134                    || p.starts_with(".config/")
5135                    || p.starts_with(".cargo/")
5136                    || matches!(
5137                        p.rsplit('/').next().unwrap_or(p),
5138                        "Cargo.toml"
5139                            | "Cargo.lock"
5140                            | "Makefile.toml"
5141                            | "build.rs"
5142                            | "rust-toolchain.toml"
5143                    )
5144            })
5145        {
5146            return false;
5147        }
5148        failing.iter().all(|label| {
5149            let matches: Vec<_> = self.checks.iter().filter(|c| &c.label == label).collect();
5150            matches.len() == 1
5151                && matches[0].rerun_exhausted
5152                && !matches[0].head_failures.is_empty()
5153                && matches[0].head_failures.iter().all(|f| {
5154                    // Workflow-level exit-code annotations do not identify a
5155                    // failing test or source file, and prove nothing here.
5156                    !f.path.is_empty()
5157                        && !f.path.starts_with('.')
5158                        && !f.path.contains("..")
5159                        && !f.path.starts_with('/')
5160                        && !self.changed.contains(&f.path)
5161                        && matches[0].base_failures.contains(f)
5162                })
5163        })
5164    }
5165}
5166
5167async fn ci_json(repo: &Path, endpoint: String) -> Option<serde_json::Value> {
5168    let out = gh(repo, &["api".into(), endpoint]).await.ok()?;
5169    if !out.ok {
5170        return None;
5171    }
5172    serde_json::from_str(&out.stdout).ok()
5173}
5174
5175async fn ci_annotations(repo: &Path, check: &serde_json::Value) -> Option<Vec<CiFailure>> {
5176    let count = check.pointer("/output/annotations_count")?.as_u64()?;
5177    if count == 0 || count >= 100 {
5178        return None;
5179    }
5180    let id = check.get("id")?.as_u64()?;
5181    let value = ci_json(
5182        repo,
5183        format!("repos/{{owner}}/{{repo}}/check-runs/{id}/annotations?per_page=100"),
5184    )
5185    .await?;
5186    let annotations = value.as_array()?;
5187    if annotations.len() != count as usize {
5188        return None;
5189    }
5190    annotations
5191        .iter()
5192        .filter(|a| a["annotation_level"] == "failure")
5193        .map(|a| {
5194            Some(CiFailure {
5195                path: a["path"].as_str()?.into(),
5196                start_line: a["start_line"].as_u64()?,
5197                end_line: a["end_line"].as_u64()?,
5198                title: a["title"].as_str()?.into(),
5199                message: a["message"].as_str()?.into(),
5200            })
5201        })
5202        .collect()
5203}
5204
5205async fn ci_runs(repo: &Path, sha: &str) -> Option<Vec<serde_json::Value>> {
5206    let value = ci_json(
5207        repo,
5208        format!("repos/{{owner}}/{{repo}}/commits/{sha}/check-runs?per_page=100&filter=latest"),
5209    )
5210    .await?;
5211    let runs = value["check_runs"].as_array()?;
5212    if value["total_count"].as_u64()? != runs.len() as u64 || runs.len() >= 100 {
5213        return None;
5214    }
5215    Some(runs.clone())
5216}
5217
5218async fn collect_ci_evidence(state: &RunState, seen: &Seen) -> Option<CiEvidence> {
5219    let repo = &state.repo;
5220    let base_ref = format!("refs/remotes/{}/{}", state.config.merge.remote, seen.base);
5221    let base = git::git_raw(repo, &["rev-parse", "--verify", &base_ref])
5222        .await
5223        .ok()?;
5224    if !base.ok() {
5225        return None;
5226    }
5227    let range = format!("{}...{}", base.stdout, seen.head);
5228    // No rename detection: both old and new paths must count as changed.
5229    let diff = git::git_raw(
5230        repo,
5231        &["diff", "--no-renames", "--name-only", "-z", &range, "--"],
5232    )
5233    .await
5234    .ok()?;
5235    if !diff.ok() {
5236        return None;
5237    }
5238    let head_runs = ci_runs(repo, &seen.head).await?;
5239    let base_runs = ci_runs(repo, &base.stdout).await?;
5240    let mut checks = Vec::new();
5241    for label in &seen.pr.failing {
5242        let matching = |runs: &[serde_json::Value]| {
5243            runs.iter()
5244                .filter(|r| r["name"].as_str() == Some(label))
5245                .cloned()
5246                .collect::<Vec<_>>()
5247        };
5248        let heads = matching(&head_runs);
5249        let bases = matching(&base_runs);
5250        if heads.len() != 1 || bases.len() != 1 {
5251            return None;
5252        }
5253        let h = &heads[0];
5254        let b = &bases[0];
5255        if h["conclusion"] != "failure"
5256            || b["conclusion"] != "failure"
5257            || h["status"] != "completed"
5258            || b["status"] != "completed"
5259            || h["head_sha"].as_str()? != seen.head
5260            || b["head_sha"].as_str()? != base.stdout
5261            || h.pointer("/app/id")?.as_u64()? != b.pointer("/app/id")?.as_u64()?
5262        {
5263            return None;
5264        }
5265        let run = run_of(h["details_url"].as_str()?)?;
5266        let contexts: Vec<_> = seen.contexts.iter().filter(|c| &c.label == label).collect();
5267        if contexts.len() != 1
5268            || contexts[0].run.as_ref() != Some(&run)
5269            || contexts[0].verdict != Verdict::Fail
5270        {
5271            return None;
5272        }
5273        // A persisted request alone is not a completed rerun: require the
5274        // workflow's structured attempt number as well.
5275        let workflow =
5276            ci_json(repo, format!("repos/{{owner}}/{{repo}}/actions/runs/{run}")).await?;
5277        let base_run = run_of(b["details_url"].as_str()?)?;
5278        let base_workflow = ci_json(
5279            repo,
5280            format!("repos/{{owner}}/{{repo}}/actions/runs/{base_run}"),
5281        )
5282        .await?;
5283        if base_workflow["head_sha"].as_str()? != base.stdout
5284            || base_workflow["head_branch"].as_str()? != seen.base
5285            || base_workflow["status"] != "completed"
5286            || base_workflow["conclusion"] != "failure"
5287            || base_workflow["workflow_id"].as_u64()? != workflow["workflow_id"].as_u64()?
5288        {
5289            return None;
5290        }
5291        let exhausted = state
5292            .land_reruns
5293            .as_ref()
5294            .is_some_and(|r| r.head == seen.head && r.runs.contains_key(&run))
5295            && workflow["head_sha"].as_str()? == seen.head
5296            && workflow["run_attempt"].as_u64()? > 1
5297            && workflow["status"] == "completed";
5298        checks.push(CiCheckEvidence {
5299            label: label.clone(),
5300            head_check: h["id"].as_u64()?,
5301            base_check: b["id"].as_u64()?,
5302            app: h.pointer("/app/id")?.as_u64()?,
5303            run,
5304            base_run,
5305            head_failures: ci_annotations(repo, h).await?,
5306            base_failures: ci_annotations(repo, b).await?,
5307            rerun_exhausted: exhausted,
5308        });
5309    }
5310    Some(CiEvidence {
5311        head: seen.head.clone(),
5312        base: base.stdout,
5313        changed: diff
5314            .stdout
5315            .split('\0')
5316            .filter(|p| !p.is_empty())
5317            .map(str::to_owned)
5318            .collect(),
5319        checks,
5320    })
5321}
5322
5323async fn hold_unrelated(state: &mut RunState, pr: &PrState, evidence: CiEvidence) -> Result<()> {
5324    let detail = serde_json::to_string(&evidence)?;
5325    let resume = "daemon: CI を確認して同じ run を再開する".to_owned();
5326    let hold = "operator: 保留して後で判断する".to_owned();
5327    let mut q = ask::Question::new(
5328        state.id.clone(),
5329        CI_HOLD_NODE.into(),
5330        "land".into(),
5331        "base でも再現する CI の失敗を検出したため、試行を消費せず保留しました".into(),
5332        format!(
5333            "必須チェックや承認は省略しません。再開時にも同じ workflow run は自動再実行しません。\n構造化された判定根拠:\n{detail}"
5334        ),
5335        vec![resume.clone(), hold.clone()],
5336    );
5337    q.actions.insert(
5338        resume,
5339        ask::ChoiceAction::Resume {
5340            run: state.id.clone(),
5341        },
5342    );
5343    q.actions.insert(hold, ask::ChoiceAction::Hold);
5344    ask::Questions::open().put_executable(&mut q)?;
5345    state.land_unrelated = Some(CiHold {
5346        head: evidence.head.clone(),
5347        question: q.id.clone(),
5348        evidence,
5349    });
5350    state.event("land", format!("[ci-unrelated] base reproduces every located failure after rerun; owner question {}: {detail}", q.id));
5351    state.end_pass_parked(crate::run::ParkCause::Question);
5352    state.parked = true;
5353    state.save()?;
5354    if let Err(e) = ask::notify(&state.config.notify, &q).await {
5355        tracing::warn!("could not notify about CI hold: {e:#}");
5356    }
5357    // A durable question and evidence are sufficient even if commenting fails.
5358    let body = stop_comment(
5359        &state.id,
5360        "CI failures independently reproduced on the base; awaiting an owner decision without charging the task attempt",
5361    );
5362    let (_, body) = crate::github_text::prepare(state, "", &body);
5363    gh(
5364        &state.repo,
5365        &[
5366            "pr".into(),
5367            "comment".into(),
5368            pr.number.to_string(),
5369            "--body".into(),
5370            body,
5371        ],
5372    )
5373    .await
5374    .ok();
5375    Ok(())
5376}
5377
5378/// One observation, plus the two things [`PrState`] deliberately does not carry:
5379/// the title (needed for the squash subject) and where the failing checks'
5380/// logs live.
5381#[derive(Clone)]
5382struct Seen {
5383    pr: PrState,
5384    title: String,
5385    failing_urls: Vec<(String, String)>,
5386    /// `headRefOid`: the commit this observation, checks included, is about.
5387    head: String,
5388    /// The commit the checks belong to, read from the same GraphQL node as
5389    /// the checks themselves. Empty when unreadable.
5390    rollup_head: String,
5391    /// `mergeStateStatus` as the forge spelled it. [`Blocking`] folds BLOCKED
5392    /// and DRAFT together, and a stop reason has to say which.
5393    merge_state: String,
5394    /// Every check of the rollup, for naming what an armed merge waits on.
5395    contexts: Vec<CheckInfo>,
5396    /// `baseRefName`, to look up which contexts the base requires.
5397    base: String,
5398}
5399
5400/// One check of the rollup as far as a stop reason needs it.
5401#[derive(Clone)]
5402struct CheckInfo {
5403    label: String,
5404    verdict: Verdict,
5405    required: Option<bool>,
5406    /// The workflow run the check belongs to; `None` for an external status.
5407    run: Option<String>,
5408}
5409
5410/// What to do with a red head before a fix round is spent on it.
5411#[derive(Debug, Clone, PartialEq, Eq)]
5412enum RerunStep {
5413    /// Rerun these workflow runs (each not yet rerun for this head).
5414    Rerun(Vec<String>),
5415    /// Reran already and the forge may still report the old failure: wait.
5416    Grace,
5417    /// Nothing to rerun, or the rerun did not help: the fixer's turn.
5418    Fix,
5419}
5420
5421/// Failed checks a rerun may help: a failure of a check that blocks (`required`
5422/// unreadable counts), as `(label, run)`. Judged one workflow run at a time;
5423/// pending checks in another run do not delay this run's rerun.
5424#[cfg(test)]
5425fn rerunnable(contexts: &[CheckInfo]) -> Vec<(String, Option<String>)> {
5426    rerunnable_with(contexts, false)
5427}
5428
5429fn rerunnable_with(
5430    contexts: &[CheckInfo],
5431    include_optional: bool,
5432) -> Vec<(String, Option<String>)> {
5433    contexts
5434        .iter()
5435        .filter(|c| c.verdict == Verdict::Fail && (include_optional || c.required != Some(false)))
5436        // `gh run rerun --failed` refuses a run with a job still going.
5437        .filter(|c| {
5438            c.run.as_ref().is_none_or(|r| {
5439                !contexts.iter().any(|o| {
5440                    matches!(o.verdict, Verdict::Pending | Verdict::Unknown)
5441                        && o.run.as_ref() == Some(r)
5442                })
5443            })
5444        })
5445        .map(|c| (c.label.clone(), c.run.clone()))
5446        .collect()
5447}
5448
5449/// Pure: rerun once per run id, wait out the grace, then hand over.
5450fn rerun_step(
5451    failing: &[(String, Option<String>)],
5452    record: Option<&LandReruns>,
5453    head: &str,
5454    now: i64,
5455) -> RerunStep {
5456    // A failure with no workflow run (an external status) cannot be rerun, and
5457    // the fixer's push re-runs everything anyway.
5458    if failing.is_empty() || failing.iter().any(|(_, run)| run.is_none()) {
5459        return RerunStep::Fix;
5460    }
5461    // Reruns belong to the head they were made on.
5462    let record = record.filter(|r| r.head.eq_ignore_ascii_case(head));
5463    let mut fresh: Vec<String> = Vec::new();
5464    let mut recent = false;
5465    for run in failing.iter().filter_map(|(_, run)| run.as_deref()) {
5466        match record.and_then(|r| r.runs.get(run)) {
5467            None => {
5468                if !fresh.iter().any(|f| f == run) {
5469                    fresh.push(run.to_owned());
5470                }
5471            }
5472            Some(&at) if now - at < crate::release_watch::RERUN_GRACE => recent = true,
5473            Some(_) => {}
5474        }
5475    }
5476    if !fresh.is_empty() {
5477        RerunStep::Rerun(fresh)
5478    } else if recent {
5479        RerunStep::Grace
5480    } else {
5481        RerunStep::Fix
5482    }
5483}
5484
5485/// Read the pull request: `gh pr view` for the top-level thread and merge
5486/// state, `gh api graphql` for the last commit and its checks, `gh api` for the
5487/// inline review comments `gh pr view` does not report.
5488async fn observe(repo: &Path, pr_url: &str) -> Result<Seen> {
5489    let view = gh(
5490        repo,
5491        &[
5492            "pr".to_owned(),
5493            "view".to_owned(),
5494            pr_url.to_owned(),
5495            "--json".to_owned(),
5496            "url,number,state,title,reviews,comments,mergeStateStatus,headRefOid,baseRefName"
5497                .to_owned(),
5498        ],
5499    )
5500    .await?;
5501    if !view.ok {
5502        bail!("gh pr view {pr_url}: {}", view.combined());
5503    }
5504    let number = parse_pr(&view.stdout)?.number;
5505    let node = last_commit_node(repo, number).await;
5506    let mut seen = seen_from(&view.stdout, node.as_deref())?;
5507
5508    let inline = gh(
5509        repo,
5510        &[
5511            "api".to_owned(),
5512            format!("repos/{{owner}}/{{repo}}/pulls/{}/comments", seen.pr.number),
5513        ],
5514    )
5515    .await?;
5516    if inline.ok {
5517        match parse_inline_comments(&inline.stdout) {
5518            Ok(mut comments) => seen.pr.review_comments.append(&mut comments),
5519            // An unreadable inline thread must not end a landing: the rollup
5520            // and the top-level thread are still real signal.
5521            Err(e) => tracing::warn!("inline review comments unreadable: {e}"),
5522        }
5523    } else {
5524        tracing::warn!(
5525            "gh api pulls/{}/comments: {}",
5526            seen.pr.number,
5527            inline.combined()
5528        );
5529    }
5530    Ok(seen)
5531}
5532
5533/// Build a [`Seen`] from the `gh pr view` json and the last-commit node
5534/// response. No I/O.
5535///
5536/// The commit oid and the checks are read from the *same* node, so the rollup
5537/// is bound to the commit it belongs to by construction; two reads that agree
5538/// before and after another response prove nothing about what that response
5539/// held. The view's own rollup is never used. A node that is missing,
5540/// unreadable, carries GraphQL errors, or whose checks run past the page
5541/// leaves `rollup_head` empty and the checks `Unknown`, which the loop treats
5542/// as "look again" and never as a reason to merge.
5543fn seen_from(view_json: &str, node_json: Option<&str>) -> Result<Seen> {
5544    let mut pr = parse_pr(view_json)?;
5545    let raw: GhPr = serde_json::from_str(view_json).context("re-read pull request json")?;
5546
5547    let mut rollup_head = String::new();
5548    let mut failing_urls = Vec::new();
5549    let mut contexts = Vec::new();
5550    let mut checks = Checks::Unknown;
5551    let mut failing = Vec::new();
5552    if let Some((oid, rollup)) = node_json.and_then(parse_last_commit_node) {
5553        (checks, failing) = rollup_verdict(&rollup);
5554        failing_urls = rollup
5555            .iter()
5556            .filter(|c| c.verdict() == Verdict::Fail)
5557            .filter_map(|c| c.url().map(|u| (c.label(), u.to_owned())))
5558            .collect();
5559        contexts = rollup
5560            .iter()
5561            .map(|c| CheckInfo {
5562                label: c.label(),
5563                verdict: c.verdict(),
5564                required: c.is_required,
5565                run: c.url().and_then(run_of),
5566            })
5567            .collect();
5568        rollup_head = oid;
5569    }
5570    pr.checks = checks;
5571    pr.failing = failing;
5572
5573    Ok(Seen {
5574        pr,
5575        title: raw.title,
5576        failing_urls,
5577        head: raw.head_ref_oid,
5578        rollup_head,
5579        merge_state: raw.merge_state_status,
5580        contexts,
5581        base: raw.base_ref_name,
5582    })
5583}
5584
5585/// The last commit's oid and its checks from one GraphQL response, `None`
5586/// when anything about it cannot be trusted.
5587fn parse_last_commit_node(json: &str) -> Option<(String, Vec<GhCheck>)> {
5588    let v: serde_json::Value = serde_json::from_str(json).ok()?;
5589    if v.get("errors").is_some_and(|e| !e.is_null()) {
5590        return None;
5591    }
5592    let commit = v.pointer("/data/repository/pullRequest/commits/nodes/0/commit")?;
5593    let oid = commit.get("oid")?.as_str().filter(|o| !o.is_empty())?;
5594    let contexts = commit.pointer("/statusCheckRollup/contexts");
5595    let Some(contexts) = contexts.filter(|c| !c.is_null()) else {
5596        // No rollup at all: the commit has no checks.
5597        return Some((oid.to_owned(), Vec::new()));
5598    };
5599    if contexts.pointer("/pageInfo/hasNextPage")?.as_bool()? {
5600        return None;
5601    }
5602    let nodes = contexts.get("nodes")?.as_array()?;
5603    let rollup = nodes
5604        .iter()
5605        .map(|n| serde_json::from_value::<GhCheck>(n.clone()))
5606        .collect::<Result<Vec<_>, _>>()
5607        .ok()?;
5608    Some((oid.to_owned(), rollup))
5609}
5610
5611/// The pull request's last commit and its checks, in one response. `None`
5612/// when the forge could not be asked.
5613async fn last_commit_node(repo: &Path, number: u64) -> Option<String> {
5614    let out = gh(
5615        repo,
5616        &[
5617            "api".to_owned(),
5618            "graphql".to_owned(),
5619            "-F".to_owned(),
5620            "owner={owner}".to_owned(),
5621            "-F".to_owned(),
5622            "repo={repo}".to_owned(),
5623            "-F".to_owned(),
5624            format!("number={number}"),
5625            "-f".to_owned(),
5626            "query=query($owner:String!,$repo:String!,$number:Int!){repository(owner:$owner,\
5627             name:$repo){pullRequest(number:$number){commits(last:1){nodes{commit{oid \
5628             statusCheckRollup{contexts(first:100){pageInfo{hasNextPage} nodes{\
5629             ... on CheckRun{name status conclusion detailsUrl \
5630             isRequired(pullRequestNumber:$number)} \
5631             ... on StatusContext{context state targetUrl \
5632             isRequired(pullRequestNumber:$number)}}}}}}}}}}"
5633                .to_owned(),
5634        ],
5635    )
5636    .await
5637    .ok()?;
5638    out.ok.then_some(out.stdout)
5639}
5640
5641/// What a fix round did.
5642#[doc(hidden)]
5643#[derive(Debug, PartialEq)]
5644pub enum Fixed {
5645    /// The fixer committed something, and this is the head that was pushed.
5646    Committed {
5647        /// The commit now at the tip of the pushed branch.
5648        head: String,
5649    },
5650    /// The fixer ran and chose to change nothing.
5651    Declined,
5652    /// Machine availability prevented a result; retry this round on resume.
5653    Deferred,
5654    /// The fixer could not run, or said nothing usable.
5655    Failed(String),
5656}
5657
5658/// Hand the failures and the comments to the fixer, then commit and push.
5659///
5660/// The fixer works in the winner's own worktree so its commits land on the
5661/// branch the pull request is built from, and it runs with `allow_write` for
5662/// the same reason.
5663#[doc(hidden)]
5664pub async fn fix_round(
5665    state: &mut RunState,
5666    pr: &PrState,
5667    round: usize,
5668    budget: usize,
5669    reason: &str,
5670    logs: &str,
5671) -> Result<Fixed> {
5672    let winner = state
5673        .winner()
5674        .cloned()
5675        .context("landing needs a winning candidate; none is recorded on this run")?;
5676    let roles = state
5677        .config
5678        .resolve_roles()
5679        .context("resolve the roster for the fix round")?;
5680    // Same chain as the review loop (see `crate::fixer`): the configured
5681    // fixers in order, otherwise the winner's own author continuing its own
5682    // conversation - the competition is over, so its context is pure benefit.
5683    let attempts = crate::fixer::attempts(state, &roles, &winner);
5684    let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
5685
5686    let prompt = fix_prompt(state, pr, round, budget, reason, logs);
5687    let mut artifacts = agent::artifacts_dir(&state.dir());
5688    if let Some(request) = state
5689        .merge_repairs
5690        .last()
5691        .filter(|r| r.phase == crate::run::MergeRepairPhase::Fixing)
5692    {
5693        artifacts = artifacts.join(format!("merge-repair-{}", request.question));
5694    }
5695    let prompt =
5696        if !crate::build_target::isolated(&state.config) && state.config.cache_dir().is_some() {
5697            format!("{prompt}\n\n{}", prompt::build_cache_note("fix", true))
5698        } else {
5699            prompt
5700        };
5701    // Read before the fixer runs: it normally commits for itself, so HEAD has
5702    // already moved by the time it returns and a later read would see no
5703    // progress (run 20261004-041622-5769 stopped on a fix that had landed).
5704    let before = git::rev_parse(&winner.worktree, "HEAD").await?;
5705    // Each id at most once, forward only: the next one is asked only when the
5706    // call advances, and only the last attempt's result is judged below, so an
5707    // exhausted chain ends as a single failed fixer does.
5708    let mut last = None;
5709    for (i, (spec, seat_key)) in attempts.into_iter().enumerate() {
5710        if owner_requested_stop(state)? {
5711            return Ok(Fixed::Declined);
5712        }
5713        let mut seat = seat_of(state, &seat_key, &spec.id);
5714        let stem = if i == 0 {
5715            format!("land-{round}")
5716        } else {
5717            format!("land-{round}-{}", spec.id)
5718        };
5719        let out = agent::invoke(
5720            &spec,
5721            &mut seat,
5722            &Invocation {
5723                coordination: state.config.coordination.as_ref(),
5724                fetched_base: state.fetched_base.as_ref(),
5725                cwd: &winner.worktree,
5726                prompt: &prompt,
5727                timeout: Duration::from_secs(state.config.graph.timeout_fix),
5728                allow_write: true,
5729                sessions: state.config.graph.sessions,
5730                artifacts: &artifacts,
5731                stem: &stem,
5732                run: &state.id,
5733                node: "land",
5734                cache_dir: state.config.cache_dir().as_deref(),
5735                attachments: &[],
5736                writable: &[],
5737            },
5738        )
5739        .await;
5740        state.seats.insert(seat.key.clone(), seat);
5741        if let Some(next) = ids.get(i + 1)
5742            && agent::chain_advances(&out)
5743        {
5744            let (class, why) = crate::fixer::failure_of(&out);
5745            crate::graph::record_handover(state, "land", &seat_key, &spec.id, next, &class, &why);
5746            continue;
5747        }
5748        last = Some((seat_key, out));
5749        break;
5750    }
5751    let (seat_key, out) = last.expect("the fixer chain always has an entry");
5752
5753    match out {
5754        Ok(o) if o.quota_exhausted() => {
5755            let loss = crate::run::QuotaLoss::from_report(seat_key, "land", o.quota.as_ref());
5756            crate::graph::block_machine_outage(state, "land", std::slice::from_ref(&loss));
5757            state.quota.push(loss);
5758            state.status = RunStatus::Blocked;
5759            state.save()?;
5760            // Keep partial edits reachable on the winner branch and leave a
5761            // clean tree for resume_landing_head. The resumed landing gates
5762            // this new commit before it can publish it; no push happens here.
5763            let inherited = crate::repo_lock::WaitPolicy::current();
5764            let wait = crate::repo_lock::WaitPolicy::new(
5765                Duration::from_secs(state.config.graph.timeout_resource_wait),
5766                move || inherited.cancelled(),
5767            );
5768            let _coordination = crate::repo_lock::SeatLease::operation_with(
5769                &winner.worktree,
5770                state.config.coordination.as_ref(),
5771                &wait,
5772            )
5773            .await?;
5774            let rescue = git::rescue_commit(
5775                &winner.worktree,
5776                &format!("magi: deferred land round {round} (uncommitted work)"),
5777            )
5778            .await?;
5779            state.note_withheld("land", &rescue.withheld);
5780            state.save()?;
5781            return Ok(Fixed::Deferred);
5782        }
5783        Ok(o) if !o.usable() => {
5784            return Ok(Fixed::Failed(format!(
5785                "the fixer produced nothing usable ({})",
5786                crate::notices::turn_status(o.exit_code, o.timed_out, o.quota_exhausted())
5787            )));
5788        }
5789        Ok(_) => {}
5790        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => return Err(e),
5791        Err(e) => return Ok(Fixed::Failed(format!("{e:#}"))),
5792    }
5793
5794    if owner_requested_stop(state)? {
5795        return Ok(Fixed::Declined);
5796    }
5797
5798    // An agent that edited files but never committed would otherwise push
5799    // nothing and look like a refusal.
5800    let wait = crate::repo_lock::WaitPolicy::new(
5801        Duration::from_secs(state.config.graph.timeout_resource_wait),
5802        || false,
5803    );
5804    let coordination = crate::repo_lock::SeatLease::operation_with(
5805        &winner.worktree,
5806        state.config.coordination.as_ref(),
5807        &wait,
5808    )
5809    .await?;
5810    match git::rescue_commit(
5811        &winner.worktree,
5812        &format!("magi: land round {round} fixes (uncommitted work)"),
5813    )
5814    .await
5815    {
5816        Ok(r) => state.note_withheld("land", &r.withheld),
5817        Err(e)
5818            if state
5819                .merge_repairs
5820                .last()
5821                .is_some_and(|r| r.phase == crate::run::MergeRepairPhase::Fixing) =>
5822        {
5823            return Ok(Fixed::Failed(format!("saving repair commit failed: {e:#}")));
5824        }
5825        Err(_) => {}
5826    }
5827    let after = git::rev_parse(&winner.worktree, "HEAD").await?;
5828    drop(coordination);
5829    if after == before {
5830        return Ok(Fixed::Declined);
5831    }
5832
5833    if owner_requested_stop(state)? {
5834        return Ok(Fixed::Declined);
5835    }
5836    crate::pr_head::ensure_owner(state)?;
5837    let remote = state.config.merge.remote.clone();
5838    anyhow::ensure!(
5839        crate::foreign_checkout::write_back(state, &after).await?,
5840        "foreign checkout delivery is blocked; see the run events"
5841    );
5842    let public_head = state.pr_branch().unwrap_or(&winner.branch).to_owned();
5843    let push = if state.pr_head.is_some() {
5844        let expected = state
5845            .pr_pushed_head
5846            .as_deref()
5847            .context("missing public head lease")?;
5848        git::push_as(
5849            &winner.worktree,
5850            &remote,
5851            &winner.branch,
5852            &public_head,
5853            expected,
5854        )
5855        .await?
5856    } else {
5857        git::push(&winner.worktree, &remote, &winner.branch).await?
5858    };
5859    if !push.ok() {
5860        return Ok(Fixed::Failed(format!(
5861            "pushing {} to {remote} failed: {}",
5862            public_head, push.stderr
5863        )));
5864    }
5865    state.event(
5866        "land",
5867        format!("round {round}: pushed a fix to {public_head}"),
5868    );
5869    state.pr_pushed_head = Some(after.clone());
5870    state.save()?;
5871    Ok(Fixed::Committed { head: after })
5872}
5873
5874/// Fetch or create a seat, keeping its conversation across nodes.
5875pub(crate) fn seat_of(state: &mut RunState, key: &str, agent: &str) -> SeatState {
5876    crate::fixer::seat_for(state, key, agent)
5877}
5878
5879/// Recheck the live PR and local worktree before spending the requested fix.
5880/// A moved/closed PR is held, never repaired using obsolete evidence.
5881pub(crate) async fn repair_preflight(state: &RunState, url: &str, head: &str) -> Result<PrState> {
5882    let seen = observe(&state.repo, url).await?;
5883    let winner = state.winner().context("no winning branch to repair")?;
5884    if seen.pr.state != PrLifecycle::Open || seen.head != head {
5885        anyhow::bail!(
5886            "PR is closed or its head changed; review the current head before requesting repair again"
5887        );
5888    }
5889    if git::rev_parse(&winner.worktree, "HEAD").await? != head
5890        || !git::is_clean(&winner.worktree).await?
5891    {
5892        anyhow::bail!(
5893            "repair worktree is missing, dirty or at a different head; restore the reviewed branch and resume this run"
5894        );
5895    }
5896    // Always disable any forge-side reservation, including one not recorded
5897    // by this run. A repair request is never merge authorization.
5898    let view = gh(
5899        &state.repo,
5900        &[
5901            "pr".into(),
5902            "view".into(),
5903            url.into(),
5904            "--json".into(),
5905            "autoMergeRequest,headRefOid,state,headRefName,baseRefName,isCrossRepository".into(),
5906        ],
5907    )
5908    .await?;
5909    if !view.ok {
5910        bail!("cannot check auto-merge: {}", view.combined());
5911    }
5912    let live: serde_json::Value = serde_json::from_str(&view.stdout)?;
5913    let public = state.pr_branch().unwrap_or(&winner.branch);
5914    if live["state"] != "OPEN"
5915        || live["headRefOid"] != head
5916        || live["headRefName"] != public
5917        || live["baseRefName"] != state.base_branch
5918        || live["isCrossRepository"] != false
5919    {
5920        bail!("PR changed during repair preflight; review its current head explicitly");
5921    }
5922    let auto_merge = live
5923        .get("autoMergeRequest")
5924        .context("cannot read the PR auto-merge reservation; repair held")?;
5925    if !auto_merge.is_null() {
5926        let out = gh(&state.repo, &disable_automerge_argv(seen.pr.number)).await?;
5927        if !out.ok {
5928            bail!("cannot disable auto-merge; repair held: {}", out.combined());
5929        }
5930    }
5931    Ok(seen.pr)
5932}
5933
5934/// What the fixer is told.
5935fn fix_prompt(
5936    state: &RunState,
5937    pr: &PrState,
5938    round: usize,
5939    budget: usize,
5940    reason: &str,
5941    logs: &str,
5942) -> String {
5943    let mut s = format!(
5944        "Your patch is open as a pull request and it is not landing. Land round \
5945         {round} of {budget}.\n\n\
5946         Pull request: {}\n\n\
5947         What is holding it: {reason}\n\n\
5948         # The task\n\n{}\n",
5949        pr.url, state.instruction
5950    );
5951
5952    if pr.failing.is_empty() {
5953        s.push_str("\n# Failing checks\n\n(none)\n");
5954    } else {
5955        let _ = write!(s, "\n# Failing checks\n\n- {}\n", pr.failing.join("\n- "));
5956        if logs.trim().is_empty() {
5957            s.push_str(
5958                "\nNo log could be read; investigate the failure with necessary focused checks.\n",
5959            );
5960        } else {
5961            let _ = write!(s, "\n## Failing log tails\n\n{logs}\n");
5962        }
5963    }
5964
5965    if pr.review_comments.is_empty() {
5966        s.push_str("\n# Review comments\n\n(none)\n");
5967    } else {
5968        s.push_str("\n# Review comments\n");
5969        for c in &pr.review_comments {
5970            let where_ = match (&c.path, c.line) {
5971                (Some(p), Some(l)) => format!(" ({p}:{l})"),
5972                (Some(p), None) => format!(" ({p})"),
5973                _ => String::new(),
5974            };
5975            let _ = write!(s, "\n## {}{where_}\n\n{}\n", c.author, c.body.trim());
5976        }
5977    }
5978
5979    s.push_str(
5980        "\n# Rules\n\n\
5981         1. Fix the cause, never the symptom. Do not delete, skip, or weaken a \
5982            failing test; do not silence a lint with an allow attribute; do not \
5983            stretch a timeout to hide a race. If the check is right, the code is \
5984            wrong.\n\
5985         2. Change nothing the checks and the comments did not raise. A \
5986            drive-by refactor turns a one-line fix into a pull request that \
5987            needs reviewing again.\n\
5988         3. If a comment is wrong, say so with a checkable argument and change \
5989            nothing for it. A declined comment with a reason is a correct \
5990            outcome; a change made to appease a reviewer is not.\n\
5991         4. Commit in this worktree. magi pushes to the pull request's branch \
5992            for you; do not push, merge, or close anything yourself.\n\
5993         5. Never name yourself, your vendor, or your model, anywhere.\n\n\
5994         # Output\n\n\
5995         Say what you changed and why, and what you declined and why.",
5996    );
5997
5998    let language = &state.config.graph.language;
5999    if !(language.trim().is_empty() || language.eq_ignore_ascii_case("en")) {
6000        let _ = write!(s, "\n\nWrite all prose in {language}.");
6001    }
6002    // After the language line, so the exception is the last word on it.
6003    s.push_str(&crate::prompt::github_rule(
6004        language,
6005        &state.config.graph.github_language,
6006    ));
6007    if let Some(overlay) = state.config.prompts.overlay("fix") {
6008        let _ = write!(s, "\n\n{overlay}");
6009    }
6010    s.push('\n');
6011    s.push_str(crate::prompt::child_run_ownership());
6012    s
6013}
6014
6015/// Failing log tails, the way the operator collects them by hand:
6016/// `gh run view --log-failed`.
6017async fn failing_logs(repo: &Path, failing: &[(String, String)]) -> String {
6018    let mut out = String::new();
6019    for (name, url) in failing.iter().take(MAX_LOGS) {
6020        let args = match (job_of(url), run_of(url)) {
6021            (Some(job), _) => vec![
6022                "run".to_owned(),
6023                "view".to_owned(),
6024                "--log-failed".to_owned(),
6025                "--job".to_owned(),
6026                job,
6027            ],
6028            (None, Some(run)) => vec![
6029                "run".to_owned(),
6030                "view".to_owned(),
6031                run,
6032                "--log-failed".to_owned(),
6033            ],
6034            // Not a GitHub Actions check - an external status has no log here.
6035            (None, None) => continue,
6036        };
6037        let (ok, body) = match gh(repo, &args).await {
6038            Ok(v) => (v.ok, v.combined()),
6039            Err(e) => (false, format!("{e:#}")),
6040        };
6041        if !ok && body.trim().is_empty() {
6042            continue;
6043        }
6044        let _ = write!(out, "### {name}\n\n```\n{}\n```\n\n", tail(&body, LOG_TAIL));
6045    }
6046    out
6047}
6048
6049/// Job id out of a check's `detailsUrl`
6050/// (`https://github.com/o/r/actions/runs/<run>/job/<job>`).
6051fn job_of(details_url: &str) -> Option<String> {
6052    let after = details_url.split("/job/").nth(1)?;
6053    let id: String = after.chars().take_while(char::is_ascii_digit).collect();
6054    (!id.is_empty()).then_some(id)
6055}
6056
6057/// Workflow run id out of a check's `detailsUrl`.
6058pub(crate) fn run_of(details_url: &str) -> Option<String> {
6059    let after = details_url.split("/actions/runs/").nth(1)?;
6060    let id: String = after.chars().take_while(char::is_ascii_digit).collect();
6061    (!id.is_empty()).then_some(id)
6062}
6063
6064/// The comment `stop` posts. Fixed English, whatever `[graph] language` says:
6065/// it lands on GitHub, not in front of the operator. Pure so a test can hold
6066/// it to that.
6067fn stop_comment(run_id: &str, why: &str) -> String {
6068    format!(
6069        "{MARKER}\nmagi stopped landing this pull request: {why}\n\n\
6070         The branch is untouched and the run is `{run_id}`. Nothing was merged."
6071    )
6072}
6073
6074/// Leave the pull request open, say why on it, and mark the run blocked.
6075///
6076/// The comment is what makes an unattended stop actionable: the operator wakes
6077/// up to a pull request that explains itself rather than to a silent queue.
6078async fn stop(state: &mut RunState, repo: &Path, pr: &PrState, why: &str) -> Result<()> {
6079    let body = stop_comment(&state.id, why);
6080    let (_, mut body) = crate::github_text::prepare(state, "", &body);
6081    if !body.contains(MARKER) {
6082        body = format!("{MARKER}\n{body}");
6083    }
6084    let posted = gh(
6085        repo,
6086        &[
6087            "pr".to_owned(),
6088            "comment".to_owned(),
6089            pr.number.to_string(),
6090            "--body".to_owned(),
6091            body,
6092        ],
6093    )
6094    .await;
6095    match posted {
6096        Ok(out) if out.ok => {}
6097        Ok(out) => tracing::warn!("could not comment on {}: {}", pr.url, out.combined()),
6098        Err(e) => tracing::warn!("could not comment on {}: {e:#}", pr.url),
6099    }
6100    state.status = RunStatus::Blocked;
6101    state.merge = Some(MergeOutcome {
6102        mode: MergeMode::Pr,
6103        ok: false,
6104        detail: why.to_owned(),
6105        empty: false,
6106    });
6107    state.event("land", format!("stopped: {why}"));
6108    state.save()?;
6109    Ok(())
6110}
6111
6112/// Output of a `gh` subprocess, keeping machine-readable `stdout` separate from
6113/// diagnostic `stderr`.
6114///
6115/// Newer `gh` releases (for example `gh` 2.105.0) can emit advisory hints on
6116/// `stderr` even when a read-only `--json` or API command succeeds with exit
6117/// status 0. Appending `stderr` onto `stdout` before deserialization breaks
6118/// strict JSON parsing (for example `trailing characters at line 2 column 1`).
6119///
6120/// Output contract:
6121/// - **Successful structured reads** (`--json`, REST `gh api`, GraphQL, etc.):
6122///   check [`Self::ok`], then pass [`Self::stdout`] straight to a strict parser.
6123///   Never fall back to [`Self::stderr`] when `stdout` is empty, and never strip
6124///   specific hint text or heuristically extract JSON substrings.
6125/// - **Failed invocations (`!ok`)**: use [`Self::combined`] so both `stdout`
6126///   and `stderr` diagnostics stay actionable (for example `404` detection and
6127///   refused-merge details).
6128/// - **Human-facing or mutating commands** (`pr merge`, `pr close`, `pr edit`,
6129///   `pr comment`, `run rerun`, `run view --log-failed`): use
6130///   [`Self::combined`] for failure diagnostics or human-readable output.
6131#[derive(Debug, Clone, PartialEq, Eq)]
6132pub(crate) struct GhOutput {
6133    /// Whether `gh` exited with status 0.
6134    pub(crate) ok: bool,
6135    /// Process `stdout`, decoded lossily as UTF-8.
6136    pub(crate) stdout: String,
6137    /// Process `stderr`, decoded lossily as UTF-8.
6138    pub(crate) stderr: String,
6139}
6140
6141impl GhOutput {
6142    /// Build from a completed subprocess output and log non-empty `stderr`
6143    /// emitted on exit status 0 at debug level without logging command
6144    /// arguments.
6145    pub(crate) fn from_output(output: std::process::Output) -> Self {
6146        let parsed = Self {
6147            ok: output.status.success(),
6148            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
6149            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
6150        };
6151        if parsed.ok && !parsed.stderr.trim().is_empty() {
6152            tracing::debug!(
6153                stderr = parsed.stderr.trim(),
6154                "gh exited successfully with stderr diagnostics"
6155            );
6156        }
6157        parsed
6158    }
6159
6160    /// Combined trimmed `stdout` and `stderr` for failure diagnostics and
6161    /// human-facing commands.
6162    pub(crate) fn combined(&self) -> String {
6163        let out = self.stdout.trim();
6164        let err = self.stderr.trim();
6165        match (out.is_empty(), err.is_empty()) {
6166            (true, true) => String::new(),
6167            (false, true) => out.to_owned(),
6168            (true, false) => err.to_owned(),
6169            (false, false) => format!("{out}\n{err}"),
6170        }
6171    }
6172}
6173
6174/// Run `gh` in `cwd`, returning exit status with separated `stdout` and
6175/// `stderr` in [`GhOutput`].
6176///
6177/// Structured callers must check [`GhOutput::ok`] and parse [`GhOutput::stdout`]
6178/// strictly without substituting [`GhOutput::stderr`]. Failed invocations and
6179/// human-facing or mutating commands should use [`GhOutput::combined`] so both
6180/// streams remain available as diagnostics.
6181///
6182/// `GH_REPO` is stripped from the child's environment: every call site here
6183/// passes an explicit `cwd` (or a full pull request URL) meaning to operate
6184/// on *that* checkout's own remote, and `gh` prefers `GH_REPO` over the
6185/// checkout it is sitting in when no `--repo` flag is given. Left unset, a
6186/// `GH_REPO` the operator happens to have exported for an unrelated script
6187/// would silently redirect [`repo_slug`] (and every other cwd-scoped call
6188/// below) to a different repository than the one actually on disk - which
6189/// for the same-repo guard in [`correct_manual_merge`] would mean the check
6190/// could be made to agree with whatever repository a forged `--merged` URL
6191/// claims, defeating it entirely.
6192pub(crate) async fn gh(cwd: &Path, args: &[String]) -> Result<GhOutput> {
6193    gh_with(Path::new("gh"), cwd, args).await
6194}
6195
6196pub(crate) async fn gh_with(program: &Path, cwd: &Path, args: &[String]) -> Result<GhOutput> {
6197    let out = tokio::process::Command::new(program)
6198        .args(args)
6199        .current_dir(cwd)
6200        .env_remove("GH_REPO")
6201        .quiet()
6202        .stdin(std::process::Stdio::null())
6203        .output()
6204        .await
6205        .with_context(|| format!("spawn gh {}", args.join(" ")))?;
6206    Ok(GhOutput::from_output(out))
6207}
6208
6209/// Verdict of one entry in the status rollup.
6210#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6211pub(crate) enum Verdict {
6212    Pass,
6213    Fail,
6214    Pending,
6215    Unknown,
6216}
6217
6218impl Verdict {
6219    /// Short operator-facing check result.
6220    pub(crate) fn label(self) -> &'static str {
6221        match self {
6222            Self::Pass => "passed",
6223            Self::Fail => "failed",
6224            Self::Pending => "pending",
6225            Self::Unknown => "unknown",
6226        }
6227    }
6228}
6229
6230#[derive(Debug, Deserialize)]
6231#[serde(rename_all = "camelCase")]
6232struct GhPr {
6233    #[serde(default)]
6234    url: String,
6235    #[serde(default)]
6236    number: u64,
6237    #[serde(default)]
6238    state: String,
6239    #[serde(default)]
6240    title: String,
6241    #[serde(default)]
6242    status_check_rollup: Vec<GhCheck>,
6243    /// GitHub's own verdict on whether the pull request can be merged.
6244    ///
6245    /// Worth asking for because it is the only place the *required* check set
6246    /// is applied: the rollup lists every check equally, so a repository that
6247    /// deliberately does not require `coverage` still looks red here. See
6248    /// [`Blocking`].
6249    #[serde(default)]
6250    merge_state_status: String,
6251    /// The commit the pull request currently points at. Compared with the
6252    /// commit a fix round pushed, it is how the loop knows the forge has moved
6253    /// on and the rollup belongs to the new head.
6254    #[serde(default)]
6255    head_ref_oid: String,
6256    #[serde(default)]
6257    base_ref_name: String,
6258    #[serde(default)]
6259    reviews: Vec<GhReview>,
6260    #[serde(default)]
6261    comments: Vec<GhComment>,
6262}
6263
6264/// One rollup entry. `gh` mixes two GraphQL types in this array: a `CheckRun`
6265/// has `name`/`status`/`conclusion`, while a `StatusContext` - the old commit
6266/// status API, which is how CodeRabbit reports - has `context`/`state` and no
6267/// conclusion at all.
6268#[derive(Debug, Deserialize)]
6269#[serde(rename_all = "camelCase")]
6270struct GhCheck {
6271    #[serde(default)]
6272    name: Option<String>,
6273    #[serde(default)]
6274    context: Option<String>,
6275    #[serde(default)]
6276    status: Option<String>,
6277    #[serde(default)]
6278    conclusion: Option<String>,
6279    #[serde(default)]
6280    state: Option<String>,
6281    #[serde(default)]
6282    details_url: Option<String>,
6283    #[serde(default)]
6284    target_url: Option<String>,
6285    /// Whether the base branch requires this check. Only the GraphQL node
6286    /// carries it; `None` is "not read", never "not required".
6287    #[serde(default)]
6288    is_required: Option<bool>,
6289}
6290
6291impl GhCheck {
6292    /// Name to show a human and hand to the fixer.
6293    fn label(&self) -> String {
6294        self.name
6295            .clone()
6296            .or_else(|| self.context.clone())
6297            .unwrap_or_else(|| "(unnamed check)".to_owned())
6298    }
6299
6300    /// Where this check's logs live, when it has any.
6301    fn url(&self) -> Option<&str> {
6302        self.details_url
6303            .as_deref()
6304            .or(self.target_url.as_deref())
6305            .filter(|u| !u.is_empty())
6306    }
6307
6308    /// Did it pass?
6309    ///
6310    /// `SKIPPED` and `NEUTRAL` count as passed: the Claude review workflow
6311    /// skips release and bot pull requests by design, and a skip that blocked
6312    /// landing would block exactly the pull requests that need no review.
6313    /// `CANCELLED` counts as failed - a cancelled check did not pass, and
6314    /// merging over one is merging over a check that never ran.
6315    fn verdict(&self) -> Verdict {
6316        if let Some(status) = self.status.as_deref() {
6317            if !status.eq_ignore_ascii_case("COMPLETED") {
6318                return Verdict::Pending;
6319            }
6320        }
6321        let outcome = self
6322            .conclusion
6323            .as_deref()
6324            .or(self.state.as_deref())
6325            .unwrap_or("");
6326        match outcome.to_ascii_uppercase().as_str() {
6327            "SUCCESS" | "SKIPPED" | "NEUTRAL" => Verdict::Pass,
6328            "FAILURE" | "ERROR" | "TIMED_OUT" | "CANCELLED" | "STARTUP_FAILURE"
6329            | "ACTION_REQUIRED" => Verdict::Fail,
6330            "PENDING" | "EXPECTED" | "QUEUED" | "IN_PROGRESS" | "WAITING" | "REQUESTED" => {
6331                Verdict::Pending
6332            }
6333            _ => Verdict::Unknown,
6334        }
6335    }
6336}
6337
6338#[derive(Debug, Deserialize)]
6339struct GhAuthor {
6340    #[serde(default)]
6341    login: String,
6342}
6343
6344#[derive(Debug, Deserialize)]
6345struct GhReview {
6346    #[serde(default)]
6347    author: GhAuthor,
6348    #[serde(default)]
6349    body: String,
6350}
6351
6352#[derive(Debug, Deserialize)]
6353struct GhComment {
6354    #[serde(default)]
6355    author: GhAuthor,
6356    #[serde(default)]
6357    body: String,
6358}
6359
6360#[derive(Debug, Deserialize)]
6361struct GhUser {
6362    #[serde(default)]
6363    login: String,
6364}
6365
6366#[derive(Debug, Deserialize)]
6367struct GhInline {
6368    #[serde(default)]
6369    user: GhUser,
6370    #[serde(default)]
6371    path: Option<String>,
6372    #[serde(default)]
6373    line: Option<u64>,
6374    #[serde(default)]
6375    body: String,
6376}
6377
6378impl Default for GhAuthor {
6379    fn default() -> Self {
6380        Self {
6381            login: "(unknown)".to_owned(),
6382        }
6383    }
6384}
6385
6386impl Default for GhUser {
6387    fn default() -> Self {
6388        Self {
6389            login: "(unknown)".to_owned(),
6390        }
6391    }
6392}
6393
6394#[cfg(test)]
6395pub(crate) mod tests {
6396    use super::*;
6397    use crate::run::{Candidate, ReviewRecord, ReviewRound, Tally};
6398
6399    fn head_json(head: &str, base: &str, state: &str, cross: bool) -> String {
6400        format!(
6401            r#"{{"headRefName":"{head}","headRefOid":"aaa","baseRefName":"{base}","state":"{state}","isCrossRepository":{cross}}}"#
6402        )
6403    }
6404
6405    #[test]
6406    fn a_pull_request_is_closed_only_when_its_head_is_exactly_the_runs_branch() {
6407        let ok = head_json("magi/27b2/A", "main", "OPEN", false);
6408        assert_eq!(
6409            closable(&ok, "magi/27b2/A", "main", &["aaa".to_owned()]),
6410            Ok(())
6411        );
6412        for (json, why) in [
6413            (head_json("magi/27b2/B", "main", "OPEN", false), "head"),
6414            (head_json("magi/27b2/A-2", "main", "OPEN", false), "head"),
6415            (head_json("magi/27b2/A", "main", "OPEN", true), "fork"),
6416            (head_json("magi/27b2/A", "dev", "OPEN", false), "targets"),
6417            (head_json("magi/27b2/A", "main", "MERGED", false), "already"),
6418            (head_json("magi/27b2/A", "main", "CLOSED", false), "already"),
6419        ] {
6420            let err = closable(&json, "magi/27b2/A", "main", &["aaa".to_owned()])
6421                .unwrap_err()
6422                .why;
6423            assert!(err.contains(why), "{json}: {err}");
6424        }
6425        // A head that moved on past what was verified is left alone.
6426        let moved = head_json("magi/27b2/A", "main", "OPEN", false);
6427        let err = closable(&moved, "magi/27b2/A", "main", &["bbb".to_owned()]).unwrap_err();
6428        assert!(err.retry && err.why.contains("not a commit"), "{err:?}");
6429        assert!(
6430            !closable(
6431                &head_json("x", "main", "OPEN", false),
6432                "magi/27b2/A",
6433                "main",
6434                &[]
6435            )
6436            .unwrap_err()
6437            .retry
6438        );
6439        assert!(is_forge_url("https://github.com/o/r.git"));
6440        assert!(is_forge_url("git@github.com:o/r.git"));
6441        assert!(!is_forge_url("/tmp/origin.git"));
6442        assert!(!is_forge_url("C:\\work\\origin.git"));
6443        assert!(!is_forge_url("file:///tmp/origin.git"));
6444        assert!(forge_unavailable(
6445            "gh pr list failed: none of the git remotes configured for this repository point to a known GitHub host."
6446        ));
6447        assert!(!forge_unavailable(
6448            "gh pr list failed: error connecting to api.github.com"
6449        ));
6450        assert!(closable("not json", "magi/27b2/A", "main", &[]).is_err());
6451        // A record that does not say whether it is a fork is not trusted.
6452        assert!(
6453            closable(
6454                r#"{"headRefName":"b","headRefOid":"aaa","baseRefName":"main","state":"OPEN"}"#,
6455                "b",
6456                "main",
6457                &["aaa".to_owned()]
6458            )
6459            .is_err()
6460        );
6461    }
6462
6463    #[test]
6464    fn the_close_comment_names_the_commit_on_the_base() {
6465        let e = crate::already::Evidence {
6466            proof: crate::already::Proof::PatchId,
6467            tip: "1234567890".to_owned(),
6468            commits: vec!["0e368de0000".to_owned()],
6469        };
6470        let c = superseded_comment("main", &e);
6471        assert!(c.contains("0e368de") && c.contains("`main`"), "{c}");
6472    }
6473
6474    /// 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.
6475    const GREEN_OPEN: &str = r####"{
6476  "url": "https://github.com/yukimemi/magi/pull/10",
6477  "number": 10,
6478  "state": "OPEN",
6479  "mergeStateStatus": "CLEAN",
6480  "statusCheckRollup": [
6481    {
6482      "__typename": "CheckRun",
6483      "conclusion": "SKIPPED",
6484      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278334/job/99378963755",
6485      "name": "review",
6486      "status": "COMPLETED",
6487      "workflowName": "claude-review"
6488    },
6489    {
6490      "__typename": "CheckRun",
6491      "conclusion": "SUCCESS",
6492      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278338/job/99378963144",
6493      "name": "check (ubuntu-latest)",
6494      "status": "COMPLETED",
6495      "workflowName": "CI"
6496    },
6497    {
6498      "__typename": "CheckRun",
6499      "conclusion": "SUCCESS",
6500      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278338/job/99378963095",
6501      "name": "rustfmt",
6502      "status": "COMPLETED",
6503      "workflowName": "CI"
6504    },
6505    {
6506      "__typename": "StatusContext",
6507      "context": "CodeRabbit",
6508      "state": "SUCCESS",
6509      "targetUrl": ""
6510    }
6511  ],
6512  "reviews": [],
6513  "comments": [
6514    {
6515      "author": {
6516        "login": "coderabbitai"
6517      },
6518      "authorAssociation": "NONE",
6519      "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"
6520    }
6521  ]
6522}"####;
6523
6524    /// Real output for the open pull request #9 (the daily kata-apply), whose `editorconfig` check failed while everything else passed.
6525    const RED_OPEN: &str = r####"{
6526  "url": "https://github.com/yukimemi/magi/pull/9",
6527  "number": 9,
6528  "state": "OPEN",
6529  "mergeStateStatus": "UNSTABLE",
6530  "statusCheckRollup": [
6531    {
6532      "__typename": "CheckRun",
6533      "conclusion": "SUCCESS",
6534      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323744",
6535      "name": "check (ubuntu-latest)",
6536      "status": "COMPLETED",
6537      "workflowName": "CI"
6538    },
6539    {
6540      "__typename": "CheckRun",
6541      "conclusion": "SUCCESS",
6542      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323811",
6543      "name": "rustfmt",
6544      "status": "COMPLETED",
6545      "workflowName": "CI"
6546    },
6547    {
6548      "__typename": "CheckRun",
6549      "conclusion": "FAILURE",
6550      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572",
6551      "name": "editorconfig",
6552      "status": "COMPLETED",
6553      "workflowName": "CI"
6554    },
6555    {
6556      "__typename": "StatusContext",
6557      "context": "CodeRabbit",
6558      "state": "SUCCESS",
6559      "targetUrl": ""
6560    }
6561  ],
6562  "reviews": [],
6563  "comments": [
6564    {
6565      "author": {
6566        "login": "coderabbitai"
6567      },
6568      "authorAssociation": "NONE",
6569      "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"
6570    }
6571  ]
6572}"####;
6573
6574    /// 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.
6575    const PENDING_OPEN: &str = r####"{
6576  "url": "https://github.com/yukimemi/magi/pull/9",
6577  "number": 9,
6578  "state": "OPEN",
6579  "statusCheckRollup": [
6580    {
6581      "__typename": "CheckRun",
6582      "conclusion": "SUCCESS",
6583      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323744",
6584      "name": "check (ubuntu-latest)",
6585      "status": "COMPLETED",
6586      "workflowName": "CI"
6587    },
6588    {
6589      "__typename": "CheckRun",
6590      "conclusion": "SUCCESS",
6591      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323811",
6592      "name": "rustfmt",
6593      "status": "COMPLETED",
6594      "workflowName": "CI"
6595    },
6596    {
6597      "__typename": "CheckRun",
6598      "conclusion": null,
6599      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572",
6600      "name": "editorconfig",
6601      "status": "IN_PROGRESS",
6602      "workflowName": "CI"
6603    },
6604    {
6605      "__typename": "StatusContext",
6606      "context": "CodeRabbit",
6607      "state": "SUCCESS",
6608      "targetUrl": ""
6609    }
6610  ],
6611  "reviews": [],
6612  "comments": []
6613}"####;
6614
6615    /// Real output for pull request #16 after it was merged - the shape landing sees when a person merged underneath it.
6616    const MERGED: &str = r####"{
6617  "url": "https://github.com/yukimemi/magi/pull/16",
6618  "number": 16,
6619  "state": "MERGED",
6620  "statusCheckRollup": [
6621    {
6622      "__typename": "CheckRun",
6623      "conclusion": "SUCCESS",
6624      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33636587933/job/100268878095",
6625      "name": "check (ubuntu-latest)",
6626      "status": "COMPLETED",
6627      "workflowName": "CI"
6628    },
6629    {
6630      "__typename": "CheckRun",
6631      "conclusion": "SUCCESS",
6632      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33636587918/job/100268876427",
6633      "name": "review",
6634      "status": "COMPLETED",
6635      "workflowName": "claude-review"
6636    }
6637  ],
6638  "reviews": [],
6639  "comments": []
6640}"####;
6641
6642    /// 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.
6643    const REVIEWED_OPEN: &str = r####"{
6644  "url": "https://github.com/yukimemi/magi/pull/12",
6645  "number": 12,
6646  "state": "OPEN",
6647  "statusCheckRollup": [
6648    {
6649      "__typename": "CheckRun",
6650      "conclusion": "SUCCESS",
6651      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33571212506/job/100065355258",
6652      "name": "check (ubuntu-latest)",
6653      "status": "COMPLETED",
6654      "workflowName": "CI"
6655    },
6656    {
6657      "__typename": "CheckRun",
6658      "conclusion": "SUCCESS",
6659      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33571212566/job/100065355810",
6660      "name": "review",
6661      "status": "COMPLETED",
6662      "workflowName": "claude-review"
6663    }
6664  ],
6665  "reviews": [
6666    {
6667      "author": {
6668        "login": "claude"
6669      },
6670      "state": "COMMENTED",
6671      "body": ""
6672    }
6673  ],
6674  "comments": [
6675    {
6676      "author": {
6677        "login": "coderabbitai"
6678      },
6679      "authorAssociation": "NONE",
6680      "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"
6681    },
6682    {
6683      "author": {
6684        "login": "claude"
6685      },
6686      "authorAssociation": "NONE",
6687      "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"
6688    }
6689  ]
6690}"####;
6691
6692    /// Real `gh api repos/{owner}/{repo}/pulls/12/comments` output: one inline finding with its file and line.
6693    const INLINE: &str = r####"[
6694  {
6695    "user": {
6696      "login": "claude[bot]"
6697    },
6698    "path": "src/graph.rs",
6699    "line": 231,
6700    "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"
6701  }
6702]"####;
6703
6704    /// CodeRabbit's real trigger notice: a checkbox, a `<details>` block, and its own "skip review" marker.
6705    const CODERABBIT_TRIGGER: &str = r####"<!-- This is an auto-generated comment: summarize by coderabbit.ai -->
6706<!-- This is an auto-generated comment: skip review by coderabbit.ai -->
6707
6708> [!IMPORTANT]
6709> - [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> 🔍 Trigger review
6710> 
6711> This repository does not receive automatic reviews because it has fewer than 10 stars.
6712> 
6713> <details>
6714> <summary>⚙️ Run configuration</summary>
6715> 
6716> **Configuration used**: defaults
6717> 
6718> **Review profile**: CHILL
6719> 
6720> **Plan**: Team
6721> 
6722> **Run ID**: `c1e2a68f-87fc-4b35-9ec4-e75c7854966a`
6723> 
6724> </details>
6725
6726<!-- end of auto-generated comment: skip review by coderabbit.ai -->
6727
6728<!-- tips_start -->
6729
6730---
6731
6732Thanks 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.
6733
6734<details>
6735<summary>❤️ Share</summary>
6736
6737- [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"####;
6738
6739    /// 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.
6740    const CLAUDE_CHECKLIST: &str = r####"**Claude finished @yukimemi's task in 4m 14s** —— [View job](https://github.com/yukimemi/magi/actions/runs/33636587918)
6741
6742---
6743### Reviewing PR #16
6744
6745- [x] Read AGENTS.md conventions
6746- [x] Review `src/daemon.rs` changes
6747- [x] Review `src/main.rs` changes (new `doctor` reporting)
6748- [x] Review `src/web.rs` changes (reuse of unreadable-run count)
6749- [x] Check test coverage for new behavior
6750- [x] Run verification commands (blocked — see note)
6751- [x] Post findings"####;
6752
6753    /// The same job's real comment on pull request #12 once it had something to say.
6754    const CLAUDE_FINDING: &str = r####"**Claude finished @yukimemi's task in 3m 52s** —— [View job](https://github.com/yukimemi/magi/actions/runs/33571212566)
6755
6756---
6757### Review: `magi review <branch>` — cheap-half-only graph
6758
6759Read 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.
6760
6761**Correctness**
6762
6763- 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"####;
6764
6765    fn pr(checks: Checks, failing: &[&str], comments: usize) -> PrState {
6766        PrState {
6767            url: "https://github.com/yukimemi/magi/pull/16".to_owned(),
6768            number: 16,
6769            state: PrLifecycle::Open,
6770            checks,
6771            // These tests are about red-means-fix, so a red here is one the
6772            // forge gates on. Without saying so they would assert the new
6773            // "merge past a check nobody requires" path by accident.
6774            blocking: if matches!(checks, Checks::Red) {
6775                Blocking::Yes
6776            } else {
6777                Blocking::No
6778            },
6779            failing: failing.iter().map(|s| (*s).to_owned()).collect(),
6780            review_comments: (0..comments)
6781                .map(|i| ReviewComment {
6782                    author: "coderabbitai".to_owned(),
6783                    path: Some("src/graph.rs".to_owned()),
6784                    line: Some(231),
6785                    body: format!("finding {i}"),
6786                })
6787                .collect(),
6788        }
6789    }
6790
6791    #[test]
6792    fn expected_ci_is_exactly_decide_and_absent_ci_never_waits_for_checks() {
6793        use CiExpectation::{Absent, Expected};
6794        for checks in [Checks::Pending, Checks::Unknown, Checks::Green, Checks::Red] {
6795            let p = pr(checks, &["x"], 0);
6796            for waited in [Duration::ZERO, CHECKS_GRACE] {
6797                assert_eq!(
6798                    decide_with(&p, 0, 4, waited, Expected),
6799                    decide(&p, 0, 4, waited)
6800                );
6801            }
6802        }
6803        // Nothing will ever report: no wait, no give-up, no fix round.
6804        for checks in [Checks::Pending, Checks::Unknown, Checks::Red] {
6805            let p = pr(checks, &["x"], 0);
6806            assert_eq!(decide_with(&p, 0, 4, Duration::ZERO, Absent), Step::Merge);
6807            assert_eq!(decide_with(&p, 4, 4, CHECKS_GRACE, Absent), Step::Merge);
6808        }
6809        // Third-party statuses never change the review decision, even at budget.
6810        for comments in [0, 1] {
6811            for round in [0, 4] {
6812                let absent = decide_with(
6813                    &pr(Checks::Unknown, &[], comments),
6814                    round,
6815                    4,
6816                    CHECKS_GRACE,
6817                    Absent,
6818                );
6819                for checks in [Checks::Green, Checks::Red, Checks::Pending] {
6820                    assert_eq!(
6821                        decide_with(
6822                            &pr(checks, &["third-party"], comments),
6823                            round,
6824                            4,
6825                            Duration::ZERO,
6826                            Absent
6827                        ),
6828                        absent
6829                    );
6830                }
6831                if comments != 0 {
6832                    assert!(matches!(absent, Step::Fix { .. } | Step::GiveUp { .. }));
6833                    assert_eq!(matches!(absent, Step::GiveUp { .. }), round == 4);
6834                }
6835            }
6836        }
6837        let empty = pr(Checks::Unknown, &[], 0);
6838        for waited in [Duration::ZERO, CHECKS_GRACE + POLL] {
6839            assert_eq!(decide_with(&empty, 0, 4, waited, Absent), Step::Merge);
6840        }
6841        assert_eq!(
6842            decide_with(&empty, 0, 4, Duration::ZERO, Expected),
6843            Step::Wait
6844        );
6845        assert_eq!(
6846            decide_with(&empty, 0, 4, CHECKS_GRACE, Expected),
6847            Step::GiveUp { reason: "no check status is readable on the pull request after 3 minute(s); refusing to merge on a guess".to_owned() }
6848        );
6849        // A conflict is not a check: it still wants the rebase.
6850        let mut p = pr(Checks::Unknown, &[], 0);
6851        p.blocking = Blocking::Conflict;
6852        assert_eq!(decide_with(&p, 0, 4, Duration::ZERO, Absent), Step::Rebase);
6853        // And a pull request that left our hands is still done.
6854        p.state = PrLifecycle::Merged;
6855        assert_eq!(
6856            decide_with(&p, 0, 4, Duration::ZERO, Absent),
6857            Step::Done { merged: true }
6858        );
6859    }
6860
6861    #[test]
6862    fn a_green_pull_request_with_nothing_outstanding_parses_as_ready_to_merge() {
6863        let state = parse_pr(GREEN_OPEN).expect("green fixture parses");
6864        assert_eq!(state.number, 10);
6865        assert_eq!(state.state, PrLifecycle::Open);
6866        assert_eq!(state.checks, Checks::Green);
6867        assert!(state.failing.is_empty());
6868        assert!(
6869            state.review_comments.is_empty(),
6870            "the only comment is CodeRabbit's trigger notice: {:?}",
6871            state.review_comments
6872        );
6873        assert_eq!(decide(&state, 0, 4, Duration::ZERO), Step::Merge);
6874    }
6875
6876    #[test]
6877    fn a_failing_check_parses_as_red_and_is_named() {
6878        let state = parse_pr(RED_OPEN).expect("red fixture parses");
6879        assert_eq!(state.checks, Checks::Red);
6880        assert_eq!(state.failing, vec!["editorconfig".to_owned()]);
6881        // The captured payload says `UNSTABLE` - mergeable, with a check
6882        // nobody requires red - which is exactly the shape that had to be
6883        // merged by hand. Asserted separately, in
6884        // `a_red_check_nobody_requires_does_not_buy_a_fix_round`. What this
6885        // test is about is that a red check is *named*, so the reason a fixer
6886        // is handed says which one; so it asks the blocking question here.
6887        let mut blocking = state.clone();
6888        blocking.blocking = Blocking::Yes;
6889        match decide(&blocking, 0, 4, Duration::ZERO) {
6890            Step::Fix { reason } => {
6891                assert!(reason.contains("editorconfig"), "reason: {reason}");
6892                assert!(reason.contains("failing"), "reason: {reason}");
6893            }
6894            other => panic!("expected a fix round, got {other:?}"),
6895        }
6896    }
6897
6898    #[test]
6899    fn a_check_still_running_parses_as_pending_and_is_waited_for() {
6900        let state = parse_pr(PENDING_OPEN).expect("pending fixture parses");
6901        assert_eq!(state.checks, Checks::Pending);
6902        assert_eq!(decide(&state, 0, 4, Duration::ZERO), Step::Wait);
6903    }
6904
6905    #[test]
6906    fn a_pull_request_merged_underneath_us_is_done_rather_than_a_failure() {
6907        let state = parse_pr(MERGED).expect("merged fixture parses");
6908        assert_eq!(state.state, PrLifecycle::Merged);
6909        assert_eq!(
6910            decide(&state, 0, 4, Duration::ZERO),
6911            Step::Done { merged: true }
6912        );
6913    }
6914
6915    #[test]
6916    fn a_review_that_found_something_is_outstanding_and_holds_the_merge() {
6917        let state = parse_pr(REVIEWED_OPEN).expect("reviewed fixture parses");
6918        assert_eq!(state.checks, Checks::Green);
6919        let authors: Vec<&str> = state
6920            .review_comments
6921            .iter()
6922            .map(|c| c.author.as_str())
6923            .collect();
6924        assert_eq!(
6925            authors,
6926            vec!["claude"],
6927            "CodeRabbit's walkthrough is machinery; Claude's review is a finding"
6928        );
6929        match decide(&state, 0, 4, Duration::ZERO) {
6930            Step::Fix { reason } => assert!(reason.contains("unresolved"), "reason: {reason}"),
6931            other => panic!("expected a fix round, got {other:?}"),
6932        }
6933    }
6934
6935    #[test]
6936    fn inline_review_comments_keep_their_file_and_line() {
6937        let comments = parse_inline_comments(INLINE).expect("inline fixture parses");
6938        assert_eq!(comments.len(), 1);
6939        assert_eq!(comments[0].author, "claude[bot]");
6940        assert_eq!(comments[0].path.as_deref(), Some("src/graph.rs"));
6941        assert_eq!(comments[0].line, Some(231));
6942        assert!(comments[0].body.contains("empty"), "{}", comments[0].body);
6943    }
6944
6945    #[test]
6946    fn a_status_only_bot_comment_does_not_trigger_a_fix_round() {
6947        assert!(
6948            is_noise(CODERABBIT_TRIGGER),
6949            "CodeRabbit's trigger notice declares itself not a review"
6950        );
6951        assert!(
6952            is_noise(CLAUDE_CHECKLIST),
6953            "a progress checklist asks for nothing"
6954        );
6955        assert!(
6956            !is_noise(CLAUDE_FINDING),
6957            "a review that names a bug is input, not noise"
6958        );
6959
6960        let mut clean = pr(Checks::Green, &[], 0);
6961        clean.review_comments.push(ReviewComment {
6962            author: "coderabbitai".to_owned(),
6963            path: None,
6964            line: None,
6965            body: CODERABBIT_TRIGGER.to_owned(),
6966        });
6967        clean.review_comments.retain(|c| !is_noise(&c.body));
6968        assert_eq!(decide(&clean, 0, 4, Duration::ZERO), Step::Merge);
6969
6970        let mut found = pr(Checks::Green, &[], 0);
6971        found.review_comments.push(ReviewComment {
6972            author: "claude".to_owned(),
6973            path: None,
6974            line: None,
6975            body: CLAUDE_FINDING.to_owned(),
6976        });
6977        found.review_comments.retain(|c| !is_noise(&c.body));
6978        assert!(matches!(
6979            decide(&found, 0, 4, Duration::ZERO),
6980            Step::Fix { .. }
6981        ));
6982    }
6983
6984    #[test]
6985    fn the_policy_table_holds_for_every_combination_that_matters() {
6986        let cases: Vec<(&str, PrState, usize, usize, Duration, Step)> = vec![
6987            (
6988                "pending checks are waited for, even on the last round",
6989                pr(Checks::Pending, &[], 0),
6990                4,
6991                4,
6992                Duration::ZERO,
6993                Step::Wait,
6994            ),
6995            (
6996                "red checks are fixed",
6997                pr(Checks::Red, &["editorconfig"], 0),
6998                0,
6999                4,
7000                Duration::ZERO,
7001                Step::Fix {
7002                    reason: "1 check(s) failing: editorconfig".to_owned(),
7003                },
7004            ),
7005            (
7006                "green with comments is fixed, not merged",
7007                pr(Checks::Green, &[], 2),
7008                1,
7009                4,
7010                Duration::ZERO,
7011                Step::Fix {
7012                    reason: "checks are green but 2 review comment(s) are unresolved: coderabbitai"
7013                        .to_owned(),
7014                },
7015            ),
7016            (
7017                "green and clean merges",
7018                pr(Checks::Green, &[], 0),
7019                3,
7020                4,
7021                Duration::ZERO,
7022                Step::Merge,
7023            ),
7024            (
7025                "an unreadable rollup is waited on while the grace lasts",
7026                pr(Checks::Unknown, &[], 0),
7027                0,
7028                4,
7029                Duration::ZERO,
7030                Step::Wait,
7031            ),
7032            (
7033                "an unreadable rollup is never merged once the grace is spent",
7034                pr(Checks::Unknown, &[], 0),
7035                0,
7036                4,
7037                CHECKS_GRACE,
7038                Step::GiveUp {
7039                    reason: "no check status is readable on the pull request after 3 minute(s); \
7040                             refusing to merge on a guess"
7041                        .to_owned(),
7042                },
7043            ),
7044        ];
7045        for (what, state, round, budget, waited, want) in cases {
7046            assert_eq!(decide(&state, round, budget, waited), want, "{what}");
7047        }
7048    }
7049
7050    #[test]
7051    fn the_forge_verdict_survives_the_round_trip_from_gh() {
7052        // Read off `gh pr view --json ...,mergeStateStatus`, because a field
7053        // requested but never parsed is the kind of thing that looks wired up
7054        // and answers `Unsaid` forever.
7055        let green = parse_pr(GREEN_OPEN).expect("parse");
7056        assert_eq!(green.blocking, Blocking::No);
7057        let red = parse_pr(RED_OPEN).expect("parse");
7058        assert_eq!(
7059            red.blocking,
7060            Blocking::No,
7061            "`UNSTABLE` is mergeable: the red check is one nobody requires"
7062        );
7063        assert_eq!(red.checks, Checks::Red, "and it is still reported as red");
7064        // A payload from an older `gh` has no such field at all.
7065        let quiet =
7066            parse_pr(&GREEN_OPEN.replace("\"mergeStateStatus\": \"CLEAN\",", "")).expect("parse");
7067        assert_eq!(quiet.blocking, Blocking::Unsaid);
7068    }
7069
7070    #[test]
7071    fn a_red_check_nobody_requires_does_not_buy_a_fix_round() {
7072        // Pull request 37's only red check was `editorconfig`, failing
7073        // because the action could not fetch its own binary after
7074        // editorconfig-checker v4 renamed its release assets. The repository
7075        // does not require it. magi answered by asking a fixer to repair a
7076        // change that was fine, and the pull request had to be merged by hand.
7077        let mut nonblocking = pr(Checks::Red, &["editorconfig", "coverage"], 0);
7078        nonblocking.blocking = Blocking::No;
7079        assert_eq!(
7080            decide(&nonblocking, 0, 4, Duration::ZERO),
7081            Step::Merge,
7082            "the forge says nothing is in the way, so nothing is"
7083        );
7084
7085        // The same red, gated on: that is a fix round, as before.
7086        let mut blocking = pr(Checks::Red, &["test (ubuntu-latest)"], 0);
7087        blocking.blocking = Blocking::Yes;
7088        assert!(matches!(
7089            decide(&blocking, 0, 4, Duration::ZERO),
7090            Step::Fix { .. }
7091        ));
7092
7093        // A review comment still outranks green-enough: a non-required red
7094        // must not become a way to merge past an unanswered reviewer.
7095        let mut commented = pr(Checks::Red, &["coverage"], 1);
7096        commented.blocking = Blocking::No;
7097        assert!(matches!(
7098            decide(&commented, 0, 4, Duration::ZERO),
7099            Step::Fix { .. }
7100        ));
7101
7102        // And silence from the forge is not consent.
7103        let mut unsaid = pr(Checks::Red, &["coverage"], 0);
7104        unsaid.blocking = Blocking::Unsaid;
7105        assert_eq!(decide(&unsaid, 0, 4, Duration::ZERO), Step::Wait);
7106        assert!(matches!(
7107            decide(&unsaid, 0, 4, CHECKS_GRACE),
7108            Step::Fix { .. }
7109        ));
7110    }
7111
7112    #[test]
7113    fn a_red_merge_is_announced_with_every_failing_check_and_a_green_one_is_not() {
7114        let mut red = pr(Checks::Red, &["test (windows-latest)", "coverage"], 0);
7115        red.blocking = Blocking::No;
7116        assert_eq!(
7117            decide(&red, 0, 4, Duration::ZERO),
7118            Step::Merge,
7119            "announcing must not change the decision"
7120        );
7121        let said = red_merge_summary("yukimemi/magi", &red).expect("red merge is announced");
7122        assert!(said.contains("yukimemi/magi"), "{said}");
7123        assert!(said.contains("#16"), "{said}");
7124        assert!(
7125            said.contains("https://github.com/yukimemi/magi/pull/16"),
7126            "{said}"
7127        );
7128        assert!(
7129            said.contains("test (windows-latest)") && said.contains("coverage"),
7130            "{said}"
7131        );
7132
7133        // `failing` can be left over on a green observation; only `checks` counts.
7134        let green = pr(Checks::Green, &["stale"], 0);
7135        assert_eq!(red_merge_summary("yukimemi/magi", &green), None);
7136    }
7137
7138    #[test]
7139    fn red_merge_notices_omit_empty_check_details() {
7140        for checks in [vec![], vec!["", "  "]] {
7141            let red = pr(Checks::Red, &checks, 0);
7142            let summary = red_merge_summary("owner/repo", &red).unwrap();
7143            let notice = crate::notices::merged_red("run-1", &summary);
7144            assert_eq!(
7145                notice.message,
7146                format!("Merged owner/repo PR #16 with red checks ({})", red.url)
7147            );
7148            assert_eq!(notice.severity, crate::notices::Severity::Warn);
7149        }
7150        let red = pr(Checks::Red, &["", " test ", " "], 0);
7151        let summary = red_merge_summary("owner/repo", &red).unwrap();
7152        assert!(summary.contains("with red checks: test ("), "{summary}");
7153    }
7154
7155    #[test]
7156    fn the_repo_label_comes_from_the_pull_request_url() {
7157        let p = Path::new("/tmp/checkout");
7158        assert_eq!(
7159            repo_label(p, "https://github.com/yukimemi/magi/pull/16"),
7160            "yukimemi/magi"
7161        );
7162        assert_eq!(repo_label(p, "not a url"), "checkout");
7163    }
7164
7165    #[test]
7166    fn a_branch_the_base_moved_under_is_rebased_not_fixed() {
7167        // Pull requests 35 and 37 were both rebased by hand: a competition
7168        // that runs for two hours against a repository merging pull requests
7169        // all day conflicts on the way in, and that is arithmetic rather
7170        // than a defect in the change.
7171        let mut conflicted = pr(Checks::Green, &[], 0);
7172        conflicted.blocking = Blocking::Conflict;
7173        assert_eq!(decide(&conflicted, 0, 4, Duration::ZERO), Step::Rebase);
7174
7175        // Decided before the checks, and even with the rounds spent: every
7176        // check on a branch that cannot land is an answer about a state that
7177        // cannot land, and a conflict is not the change's fault.
7178        let mut red = pr(Checks::Red, &["test (ubuntu-latest)"], 2);
7179        red.blocking = Blocking::Conflict;
7180        assert_eq!(decide(&red, 4, 4, Duration::ZERO), Step::Rebase);
7181
7182        // The lifecycle still wins over everything, conflict included.
7183        let mut merged = pr(Checks::Red, &[], 0);
7184        merged.blocking = Blocking::Conflict;
7185        merged.state = PrLifecycle::Merged;
7186        assert_eq!(
7187            decide(&merged, 0, 4, Duration::ZERO),
7188            Step::Done { merged: true }
7189        );
7190    }
7191
7192    #[test]
7193    fn the_forge_verdict_is_read_off_merge_state_status() {
7194        // The spellings that mean "mergeable". `UNSTABLE` is the one that
7195        // matters: mergeable, with a non-required check red or still running.
7196        for ok in ["CLEAN", "UNSTABLE", "unstable", "HAS_HOOKS"] {
7197            assert_eq!(Blocking::of(ok), Blocking::No, "{ok}");
7198            assert!(!Blocking::of(ok).stops_a_merge(), "{ok}");
7199        }
7200        assert_eq!(Blocking::of("DIRTY"), Blocking::Conflict);
7201        assert_eq!(Blocking::of("BLOCKED"), Blocking::Yes);
7202        assert_eq!(Blocking::of("BEHIND"), Blocking::Behind);
7203        // An older `gh`, or a token without the scope, says nothing - and
7204        // refusing to guess is the rule everywhere else in this module.
7205        for quiet in ["", "UNKNOWN"] {
7206            assert_eq!(Blocking::of(quiet), Blocking::Unsaid);
7207            assert!(Blocking::of(quiet).stops_a_merge());
7208        }
7209    }
7210
7211    #[test]
7212    fn a_merge_command_that_failed_after_merging_is_still_a_merge() {
7213        let argv = merge_argv(28, "fix: retry uploads on transient network errors");
7214        // The exact stderr from run ec12, in a jj-colocated repository.
7215        let jj = "could not determine current branch: failed to run git: not on any branch";
7216
7217        let landed = merged_after_all(&argv, jj, Some(PrLifecycle::Merged))
7218            .expect("the forge says merged, so it merged");
7219        assert!(landed.ok);
7220        assert!(
7221            landed.detail.contains("but the pull request is merged"),
7222            "the record must not read as a clean success: {}",
7223            landed.detail
7224        );
7225        assert!(
7226            landed.detail.contains("not on any branch"),
7227            "and it must keep what the command actually said: {}",
7228            landed.detail
7229        );
7230
7231        // A pull request still open means the merge really failed.
7232        assert!(merged_after_all(&argv, jj, Some(PrLifecycle::Open)).is_none());
7233        assert!(merged_after_all(&argv, jj, Some(PrLifecycle::Closed)).is_none());
7234        // And an unreadable answer is not evidence of success.
7235        assert!(merged_after_all(&argv, jj, None).is_none());
7236    }
7237
7238    #[test]
7239    fn a_pull_request_closed_underneath_us_is_done_and_not_merged() {
7240        let mut state = pr(Checks::Red, &["editorconfig"], 3);
7241        state.state = PrLifecycle::Closed;
7242        assert_eq!(
7243            decide(&state, 0, 4, Duration::ZERO),
7244            Step::Done { merged: false },
7245            "a human closing the pull request ends the loop, whatever CI says"
7246        );
7247    }
7248
7249    #[test]
7250    fn the_last_round_gives_up_with_a_reason_naming_what_is_still_failing() {
7251        let red = decide(
7252            &pr(Checks::Red, &["editorconfig", "test (macos)"], 0),
7253            4,
7254            4,
7255            Duration::ZERO,
7256        );
7257        match red {
7258            Step::GiveUp { reason } => {
7259                assert!(reason.contains("editorconfig"), "reason: {reason}");
7260                assert!(reason.contains("test (macos)"), "reason: {reason}");
7261                assert!(reason.contains("4 fix round(s)"), "reason: {reason}");
7262            }
7263            other => panic!("expected a give-up, got {other:?}"),
7264        }
7265
7266        let commented = decide(&pr(Checks::Green, &[], 1), 2, 2, Duration::ZERO);
7267        match commented {
7268            Step::GiveUp { reason } => {
7269                assert!(reason.contains("unresolved"), "reason: {reason}");
7270                assert!(reason.contains("2 fix round(s)"), "reason: {reason}");
7271            }
7272            other => panic!("expected a give-up, got {other:?}"),
7273        }
7274    }
7275
7276    #[test]
7277    fn the_merge_command_squashes_deletes_the_branch_and_sets_its_own_subject() {
7278        let candidate_commit = "magi: candidate A (uncommitted work)";
7279        let subject = merge_subject(candidate_commit, "add retries to the uploader");
7280        let argv = merge_argv(16, &subject);
7281
7282        assert!(argv.contains(&"--squash".to_owned()));
7283        assert!(argv.contains(&"--delete-branch".to_owned()));
7284        assert!(argv.contains(&"--subject".to_owned()));
7285        assert_eq!(
7286            argv.last().map(String::as_str),
7287            Some("add retries to the uploader"),
7288            "the subject must not be the candidate commit message"
7289        );
7290        assert_ne!(subject, candidate_commit);
7291    }
7292
7293    #[test]
7294    fn a_real_pull_request_title_is_used_as_the_squash_subject_verbatim() {
7295        assert_eq!(
7296            merge_subject("feat: a queue, an unattended loop, and a phone UI", "task"),
7297            "feat: a queue, an unattended loop, and a phone UI"
7298        );
7299        assert_eq!(
7300            merge_subject("", "# port the retry logic\n\ndetails"),
7301            "port the retry logic",
7302            "an empty title falls back to the task's first line, heading marks stripped"
7303        );
7304    }
7305
7306    #[test]
7307    fn a_failing_checks_details_url_yields_the_job_to_read_logs_from() {
7308        let url = "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572";
7309        assert_eq!(job_of(url).as_deref(), Some("100114323572"));
7310        assert_eq!(run_of(url).as_deref(), Some("33587406996"));
7311        assert_eq!(job_of("https://coderabbit.ai/status"), None);
7312        assert_eq!(run_of(""), None);
7313    }
7314
7315    #[test]
7316    fn magis_own_stop_comment_is_never_read_back_as_a_finding() {
7317        let mut out = Vec::new();
7318        push_if_outstanding(
7319            &mut out,
7320            ReviewComment {
7321                author: "yukimemi".to_owned(),
7322                path: None,
7323                line: None,
7324                body: format!("{MARKER}\nmagi stopped landing this pull request: 1 check failing"),
7325            },
7326        );
7327        assert!(out.is_empty());
7328    }
7329
7330    /// A run with no tally, so [`RunState::winner`] is `None` and the panel
7331    /// falls back to the repository - which keeps these tests free of a
7332    /// worktree, a `git` invocation and a network.
7333    fn run_state() -> RunState {
7334        let mut state = RunState::new(
7335            std::path::PathBuf::from("/repo/magi"),
7336            "main".to_owned(),
7337            "abcdef1234".to_owned(),
7338            "add retries to the uploader".to_owned(),
7339            crate::config::Config::default(),
7340        );
7341        // These fixtures test execution flow, independent of host disk capacity.
7342        state.config.disk.min_free_bytes = 0;
7343        // Tests run in parallel against one persistent home and the ids
7344        // `RunState::new` draws from the clock can repeat, so two tests would
7345        // share a run's questions. The home also outlives the process, so the
7346        // counter alone would reuse an earlier run's ids.
7347        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
7348        let nanos = std::time::SystemTime::now()
7349            .duration_since(std::time::UNIX_EPOCH)
7350            .map_or(0, |d| d.subsec_nanos() % 1_000_000);
7351        state.id = format!(
7352            "20261004-{nanos:06}-{:04x}",
7353            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
7354        );
7355        state
7356    }
7357
7358    fn green_pr() -> PrState {
7359        PrState {
7360            url: "https://github.com/yukimemi/magi/pull/42".to_owned(),
7361            number: 42,
7362            state: PrLifecycle::Open,
7363            checks: Checks::Green,
7364            // The forge sees nothing in the way unless a test says otherwise.
7365            blocking: Blocking::No,
7366            failing: Vec::new(),
7367            review_comments: vec![ReviewComment {
7368                author: "coderabbitai".to_owned(),
7369                path: Some("src/land.rs".to_owned()),
7370                line: Some(212),
7371                body: "this branch never checks the exit code".to_owned(),
7372            }],
7373        }
7374    }
7375
7376    #[test]
7377    fn land_fixer_defers_review_and_verification_without_a_cache() {
7378        let state = run_state();
7379        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7380        assert!(p.contains(crate::prompt::child_run_ownership()), "{p}");
7381        assert!(p.contains("Commit in this worktree"), "{p}");
7382    }
7383
7384    #[test]
7385    fn github_facing_land_text_is_english_whatever_the_language() {
7386        let mut state = run_state();
7387        state.config.graph.language = "ja".to_owned();
7388        let comment = stop_comment(&state.id, "checks are still red");
7389        assert!(crate::github_text::check("", &comment).is_empty());
7390        assert!(comment.is_ascii(), "{comment}");
7391        assert!(comment.starts_with(MARKER));
7392
7393        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7394        let ja_at = p.find("Write all prose in ja").unwrap();
7395        let rule_at = p.find(crate::prompt::GITHUB_ENGLISH_HEADING).unwrap();
7396        assert!(ja_at < rule_at, "{p}");
7397        assert!(p.contains("stays in Japanese"), "{p}");
7398
7399        state.config.graph.language = "en".to_owned();
7400        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7401        assert!(p.contains(crate::prompt::GITHUB_ENGLISH_HEADING), "{p}");
7402        assert!(!p.contains("does not apply"), "{p}");
7403    }
7404
7405    const NUMSTAT: &str = "12\t3\tsrc/land.rs\n40\t1\tsrc/web.rs\n-\t-\tassets/logo.png";
7406
7407    fn panel() -> String {
7408        approval_panel(
7409            &run_state(),
7410            &green_pr(),
7411            NUMSTAT,
7412            "diff --git a/src/land.rs b/src/land.rs\n@@ -1,2 +1,2 @@\n-old line\n+new line\n context",
7413            &[
7414                "land: ask before merging".to_owned(),
7415                "land: colour the diff".to_owned(),
7416            ],
7417            "feat: merge approval from the phone",
7418        )
7419    }
7420
7421    #[test]
7422    fn the_approval_panel_carries_the_whole_case_for_the_merge() {
7423        let html = panel();
7424        for needle in [
7425            "42",
7426            "main",
7427            "src/land.rs",
7428            "src/web.rs",
7429            "assets/logo.png",
7430            "feat: merge approval from the phone",
7431            "land: ask before merging",
7432            "land: colour the diff",
7433            "coderabbitai",
7434            "this branch never checks the exit code",
7435            "green",
7436        ] {
7437            assert!(html.contains(needle), "the panel must state `{needle}`");
7438        }
7439    }
7440
7441    async fn landing_git_fixture() -> (tempfile::TempDir, RunState, String) {
7442        crate::run::pin_test_home();
7443        let tmp = tempfile::tempdir().unwrap();
7444        let repo = tmp.path().join("repo");
7445        let remote = tmp.path().join("remote.git");
7446        std::fs::create_dir(&repo).unwrap();
7447        git::git(tmp.path(), &["init", "--bare", remote.to_str().unwrap()])
7448            .await
7449            .unwrap();
7450        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
7451        git::git(&repo, &["config", "user.name", "Test"])
7452            .await
7453            .unwrap();
7454        git::git(&repo, &["config", "user.email", "test@example.test"])
7455            .await
7456            .unwrap();
7457        std::fs::write(repo.join("base"), "base").unwrap();
7458        git::git(&repo, &["add", "."]).await.unwrap();
7459        git::git(&repo, &["commit", "-m", "base"]).await.unwrap();
7460        git::git(
7461            &repo,
7462            &["remote", "add", "origin", remote.to_str().unwrap()],
7463        )
7464        .await
7465        .unwrap();
7466        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
7467        git::git(&repo, &["checkout", "-b", "winner"])
7468            .await
7469            .unwrap();
7470        std::fs::write(repo.join("change"), "change").unwrap();
7471        git::git(&repo, &["add", "."]).await.unwrap();
7472        git::git(&repo, &["commit", "-m", "change"]).await.unwrap();
7473        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
7474        git::git(&repo, &["push", "origin", "HEAD:refs/heads/task-head"])
7475            .await
7476            .unwrap();
7477        let mut state = run_state();
7478        state.repo = repo.clone();
7479        state.base_commit = git::rev_parse(&repo, "origin/main").await.unwrap();
7480        state.config.graph.land = true;
7481        state.config.graph.land_approval = true;
7482        state.pr_head = Some("task-head".into());
7483        state.pr_pushed_head = Some(head.clone());
7484        state.candidates = vec![winning_candidate("change")];
7485        state.candidates[0].worktree = repo;
7486        state.candidates[0].branch = "winner".into();
7487        state.tally = Some(uncontested_tally());
7488        state.gate_ran = true;
7489        state.gate_head = Some(head.clone());
7490        state.land_sync_pending = true;
7491        state.save().unwrap();
7492        (tmp, state, head)
7493    }
7494
7495    async fn resume_observed_head(state: &mut RunState, head: &str) -> Result<String> {
7496        let forge = Scripted::new(vec![seen(head, Checks::Green, "CLEAN", false)], vec![]);
7497        resume_landing_head(state, head, &green_pr().url, &forge, None).await
7498    }
7499
7500    async fn advance_landing_base(state: &RunState) {
7501        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7502        std::fs::write(state.repo.join("advance"), "advance").unwrap();
7503        git::git(&state.repo, &["add", "."]).await.unwrap();
7504        git::git(&state.repo, &["commit", "-m", "advance base"])
7505            .await
7506            .unwrap();
7507        git::git(&state.repo, &["push", "origin", "main"])
7508            .await
7509            .unwrap();
7510        git::git(&state.repo, &["checkout", "winner"])
7511            .await
7512            .unwrap();
7513    }
7514
7515    #[tokio::test]
7516    async fn rebase_preparation_failure_preserves_landing_budget_and_resumes() {
7517        let (_tmp, mut state, head) = landing_git_fixture().await;
7518        advance_landing_base(&state).await;
7519        let scratch = state.dir().join("rebase");
7520        std::fs::create_dir_all(&scratch).unwrap();
7521        std::fs::write(scratch.join("obstruction"), "keep").unwrap();
7522        let attempts = state.land_sync_attempts;
7523        let error = rebase_landing_worktree(&mut state, "origin/main")
7524            .await
7525            .unwrap_err();
7526        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
7527        assert_eq!(state.land_sync_attempts, attempts);
7528        assert!(state.land_sync_target.is_none());
7529        assert!(state.rebase_fixes.is_empty());
7530        assert!(
7531            state
7532                .base_sync
7533                .as_ref()
7534                .is_none_or(|sync| sync.conflict.is_none())
7535        );
7536        let block = state.resource_block.as_ref().unwrap();
7537        assert_eq!(block.kind, crate::rebase::SEQUENCER_INFRASTRUCTURE);
7538        assert!(
7539            block.detail.contains("inspect scratch Git backlink"),
7540            "{}",
7541            block.detail
7542        );
7543        assert_eq!(
7544            std::fs::read_to_string(scratch.join("obstruction")).unwrap(),
7545            "keep"
7546        );
7547        assert_eq!(git::rev_parse(&state.repo, "winner").await.unwrap(), head);
7548        std::fs::remove_dir_all(&scratch).unwrap();
7549        state.resource_block = None;
7550        assert_eq!(
7551            rebase_landing_worktree(&mut state, "origin/main")
7552                .await
7553                .unwrap(),
7554            crate::rebase::Rebased::Applied
7555        );
7556        assert_eq!(state.land_sync_attempts, attempts + 1);
7557        assert!(git::is_ancestor(&state.repo, "origin/main", "winner").await);
7558        assert!(git::is_clean(&state.repo).await.unwrap());
7559        assert!(state.rebase_fixes.is_empty());
7560    }
7561
7562    async fn foreign_landing_fixture() -> (tempfile::TempDir, RunState, String, std::path::PathBuf)
7563    {
7564        let (tmp, mut state, old) = landing_git_fixture().await;
7565        let path = tmp.path().join("foreign");
7566        git::worktree_add_branch(&state.repo, &path, "task-head", &old)
7567            .await
7568            .unwrap();
7569        state.foreign_checkout = Some(
7570            crate::foreign_checkout::inspect(&state.repo, "task-head", &path)
7571                .await
7572                .unwrap(),
7573        );
7574        state.config.merge.mode = crate::config::MergeMode::Pr;
7575        state.save().unwrap();
7576        (tmp, state, old, path)
7577    }
7578
7579    #[tokio::test]
7580    async fn foreign_landing_sync_and_interrupted_resumes_preserve_delivery_ancestry() {
7581        for phase in 0..4 {
7582            let (_tmp, mut state, old, path) = foreign_landing_fixture().await;
7583            advance_landing_base(&state).await;
7584            state.config.verify.gate = vec!["test -f advance && test -f change".into()];
7585            if phase == 0 {
7586                // The live Step::Rebase path uses this same synchronization
7587                // and publication pair, without going through resume.
7588                assert_eq!(
7589                    rebase_landing_worktree(&mut state, "origin/main")
7590                        .await
7591                        .unwrap(),
7592                    crate::rebase::Rebased::Applied
7593                );
7594            } else {
7595                interrupt_landing_rebase(&mut state).await;
7596                let repaired_tree = git::tree_of(&state.repo, "HEAD").await.unwrap();
7597                if phase == 2 {
7598                    git::sync_to_head(&state.repo).await.unwrap();
7599                } else if phase == 3 {
7600                    // Crash after joining history, before clearing its saved
7601                    // start. Repeating restoration must not add another merge.
7602                    restore_landing_worktree(&mut state).await.unwrap();
7603                    let joined = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7604                    state.land_rebase_from = Some(old.clone());
7605                    state.save().unwrap();
7606                    restore_landing_worktree(&mut state).await.unwrap();
7607                    assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), joined);
7608                }
7609                state.save().unwrap();
7610                state = RunState::load(&state.id).unwrap();
7611                restore_landing_worktree(&mut state).await.unwrap();
7612                assert_eq!(
7613                    git::tree_of(&state.repo, "HEAD").await.unwrap(),
7614                    repaired_tree
7615                );
7616            }
7617            let head = if phase == 0 {
7618                let forge = Scripted::new(vec![seen(&old, Checks::Green, "CLEAN", false)], vec![]);
7619                publish_landing_head(&mut state, &old, &green_pr().url, &forge)
7620                    .await
7621                    .unwrap()
7622            } else {
7623                resume_observed_head(&mut state, &old).await.unwrap()
7624            };
7625            assert!(git::is_ancestor(&state.repo, &old, &head).await);
7626            assert!(git::is_ancestor(&state.repo, "origin/main", &head).await);
7627            assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
7628            assert_eq!(
7629                git::remote_head(&state.repo, "origin", "task-head")
7630                    .await
7631                    .unwrap(),
7632                Some(head.clone())
7633            );
7634            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7635            assert_eq!(state.foreign_checkout.as_ref().unwrap().synced_head, head);
7636            assert!(state.gate_allows_progress());
7637            assert!(state.land_rebase_from.is_none());
7638            assert!(!state.land_sync_pending);
7639            assert!(git::is_clean(&path).await.unwrap());
7640        }
7641    }
7642
7643    #[tokio::test]
7644    async fn foreign_landing_conflict_repair_can_resume_and_publish_without_losing_ancestry() {
7645        let (_tmp, mut state, old, path) = foreign_landing_fixture().await;
7646        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7647        std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
7648        git::commit_all(&state.repo, "conflicting base")
7649            .await
7650            .unwrap();
7651        git::git(&state.repo, &["push", "origin", "main"])
7652            .await
7653            .unwrap();
7654        git::git(&state.repo, &["checkout", "winner"])
7655            .await
7656            .unwrap();
7657        landing_gate_fixer(
7658            &mut state,
7659            "cat >/dev/null; printf resolved > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"resolved\"}'",
7660        );
7661        state.config.graph.gate_fix_rounds = 0;
7662        state.config.verify.gate = vec!["exit 1".into()];
7663        assert!(resume_observed_head(&mut state, &old).await.is_err());
7664        assert!(state.rebase_fixes.iter().any(|fix| fix.finished));
7665        let repaired = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7666        assert!(git::is_ancestor(&state.repo, &old, &repaired).await);
7667        assert_eq!(
7668            std::fs::read_to_string(state.repo.join("change")).unwrap(),
7669            "resolved"
7670        );
7671        // A red gate must neither deliver nor publish the repaired tree.
7672        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), old);
7673        assert_eq!(
7674            git::remote_head(&state.repo, "origin", "task-head")
7675                .await
7676                .unwrap(),
7677            Some(old.clone())
7678        );
7679        state = RunState::load(&state.id).unwrap();
7680        state.config.verify.gate = vec!["grep -q resolved change".into()];
7681        let head = resume_observed_head(&mut state, &old).await.unwrap();
7682        assert_eq!(head, repaired);
7683        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
7684        assert_eq!(
7685            std::fs::read_to_string(path.join("change")).unwrap(),
7686            "resolved"
7687        );
7688        assert_eq!(
7689            git::remote_head(&state.repo, "origin", "task-head")
7690                .await
7691                .unwrap(),
7692            Some(head.clone())
7693        );
7694        assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7695        assert!(git::is_ancestor(&state.repo, "origin/main", &head).await);
7696        assert!(git::is_clean(&path).await.unwrap());
7697    }
7698
7699    #[tokio::test]
7700    async fn landing_resume_completes_the_last_charged_sync_attempt() {
7701        for (scratch_started, saved_target) in [(false, true), (true, true), (true, false)] {
7702            let (_tmp, mut state, old) = landing_git_fixture().await;
7703            git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7704            std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
7705            git::commit_all(&state.repo, "conflicting base")
7706                .await
7707                .unwrap();
7708            git::git(&state.repo, &["push", "origin", "main"])
7709                .await
7710                .unwrap();
7711            git::git(&state.repo, &["checkout", "winner"])
7712                .await
7713                .unwrap();
7714            let target = git::rev_parse(&state.repo, "origin/main").await.unwrap();
7715            state.config.graph.land_rounds = 1;
7716            state.land_sync_attempts = 1;
7717            state.land_sync_target = saved_target.then(|| target.clone());
7718            state.land_rebase_from = Some(old.clone());
7719            landing_gate_fixer(
7720                &mut state,
7721                "cat >/dev/null; printf resolved > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"resolved\"}'",
7722            );
7723            state.config.verify.gate = vec!["grep -q resolved change".into()];
7724            state.save().unwrap();
7725            // Simulate interruption before the scratch start and at a conflict.
7726            if scratch_started {
7727                assert!(matches!(
7728                    git::rebase_start(&state.repo, &state.dir().join("rebase"), "winner", &target)
7729                        .await
7730                        .unwrap(),
7731                    git::RebaseStart::Conflicted(_)
7732                ));
7733            }
7734            state = RunState::load(&state.id).unwrap();
7735            let head = resume_observed_head(&mut state, &old).await.unwrap();
7736            assert_ne!(head, old);
7737            assert_eq!(state.land_sync_attempts, 1);
7738            assert!(state.land_sync_target.is_none());
7739            assert!(state.land_rebase_from.is_none());
7740            assert!(!state.land_sync_pending);
7741            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7742            assert!(state.gate_allows_progress());
7743            assert_eq!(
7744                git::remote_head(&state.repo, "origin", "task-head")
7745                    .await
7746                    .unwrap(),
7747                Some(head)
7748            );
7749            assert!(
7750                rebase_landing_worktree(&mut state, "origin/main")
7751                    .await
7752                    .unwrap_err()
7753                    .to_string()
7754                    .contains("budget exhausted")
7755            );
7756        }
7757    }
7758
7759    #[tokio::test]
7760    async fn landing_resume_gates_rebased_sha_and_publishes_it_to_the_existing_head() {
7761        let (_tmp, mut state, old) = landing_git_fixture().await;
7762        advance_landing_base(&state).await;
7763        state.config.verify.gate = vec!["test -f advance".into()];
7764        let head = resume_observed_head(&mut state, &old).await.unwrap();
7765        assert_ne!(head, old);
7766        assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7767        assert!(state.gate_allows_progress());
7768        assert_eq!(
7769            git::remote_head(&state.repo, "origin", "task-head")
7770                .await
7771                .unwrap(),
7772            Some(head.clone())
7773        );
7774        assert_eq!(state.pr_pushed_head, Some(head));
7775        assert!(!state.land_sync_pending);
7776        assert!(state.config.graph.land_approval);
7777    }
7778
7779    fn landing_gate_fixer(state: &mut RunState, script: &str) {
7780        state.config.disk.min_free_bytes = 0;
7781        state.config.graph.gate_fix_rounds = 1;
7782        state.config.agents = vec![crate::config::AgentSpec {
7783            id: "mock".into(),
7784            kind: crate::config::AgentKind::Command,
7785            model: None,
7786            command: vec!["sh".into(), "-c".into(), script.into()],
7787            extra_args: Vec::new(),
7788            env: Default::default(),
7789            prompt_delivery: None,
7790            max_turn_secs: None,
7791        }];
7792        state.candidates[0].agent = "mock".into();
7793    }
7794
7795    #[tokio::test]
7796    async fn rebase_fixer_invocation_cap_survives_fallback_and_reload() {
7797        let (tmp, mut state, original) = landing_git_fixture().await;
7798        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7799        std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
7800        git::commit_all(&state.repo, "conflicting base")
7801            .await
7802            .unwrap();
7803        let target = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7804        git::git(&state.repo, &["checkout", "winner"])
7805            .await
7806            .unwrap();
7807        let scratch = state.dir().join("rebase");
7808        let counter = tmp.path().join("calls");
7809        landing_gate_fixer(
7810            &mut state,
7811            "echo \"$REBASE_AGENT\" >> \"$REBASE_COUNTER\"; exit 1",
7812        );
7813        let template = state.config.agents[0].clone();
7814        let ids = ["mock", "fallback1", "fallback2", "fallback3"].map(str::to_owned);
7815        state.config.agents = ids
7816            .iter()
7817            .map(|id| {
7818                let mut spec = template.clone();
7819                spec.id.clone_from(id);
7820                spec.env.insert("REBASE_AGENT".into(), id.clone());
7821                spec.env
7822                    .insert("REBASE_COUNTER".into(), git::path_arg(&counter));
7823                spec
7824            })
7825            .collect();
7826        state.config.roles.fixer = Some(crate::config::AgentChoice::Chain(ids.to_vec()));
7827        state.config.graph.review_rounds = 3;
7828        state.config.verify.build_cache = crate::config::BuildCache::Isolated;
7829        state.config.graph.timeout_resource_wait = 0;
7830        let started = git::rebase_start(&state.repo, &scratch, "winner", &target)
7831            .await
7832            .unwrap();
7833        assert!(matches!(started, git::RebaseStart::Conflicted(_)));
7834        let home = crate::run::home();
7835        let cache = crate::build_target::resolve(&home, &scratch).unwrap();
7836        let owner = crate::cache::Owner::here("other-run", "e2e", "e2e", &scratch, &original);
7837        let crate::cache::AcquireOutcome::Acquired(lease) =
7838            crate::cache::try_acquire(&home, &cache, &owner).unwrap()
7839        else {
7840            panic!("test target was already leased");
7841        };
7842        let error = crate::rebase::rebase_with_fixer(&mut state, &scratch, "winner", &target)
7843            .await
7844            .unwrap_err();
7845        assert!(error.is::<crate::agent::IsolatedSeatWait>(), "{error:#}");
7846        assert!(!counter.exists());
7847        assert_eq!(git::unmerged_paths(&scratch).await.unwrap(), ["change"]);
7848        drop(lease);
7849        state = RunState::load(&state.id).unwrap();
7850        for _ in 0..2 {
7851            let crate::rebase::Rebased::Stopped(why) =
7852                crate::rebase::rebase_with_fixer(&mut state, &scratch, "winner", &target)
7853                    .await
7854                    .unwrap()
7855            else {
7856                panic!("the unresolved conflict must stop");
7857            };
7858            assert!(why.contains("after 3 of 3 fixer round(s)"), "{why}");
7859            assert_eq!(
7860                std::fs::read_to_string(&counter)
7861                    .unwrap()
7862                    .lines()
7863                    .collect::<Vec<_>>(),
7864                ["mock", "fallback1", "fallback2"]
7865            );
7866            assert_eq!(
7867                git::rev_parse(&state.repo, "winner").await.unwrap(),
7868                original
7869            );
7870            state = RunState::load(&state.id).unwrap();
7871        }
7872    }
7873
7874    #[tokio::test]
7875    async fn landing_resume_revalidates_an_operator_published_winner_extension() {
7876        let (_tmp, mut state, old) = landing_git_fixture().await;
7877        std::fs::write(state.repo.join("change"), "operator update").unwrap();
7878        git::commit_all(&state.repo, "extend winner").await.unwrap();
7879        let updated = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7880        git::git(
7881            &state.repo,
7882            &["push", "origin", "HEAD:refs/heads/task-head"],
7883        )
7884        .await
7885        .unwrap();
7886        state.config.verify.gate = vec!["exit 1".into()];
7887        state.config.graph.gate_fix_rounds = 0;
7888        assert!(resume_observed_head(&mut state, &updated).await.is_err());
7889        assert_ne!(old, updated);
7890        assert_eq!(state.gate_head.as_ref(), Some(&updated));
7891        assert!(!state.gate_allows_progress());
7892        assert!(state.land_sync_pending);
7893        state.config.verify.gate = vec!["grep -q 'operator update' change".into()];
7894        let head = resume_observed_head(&mut state, &updated).await.unwrap();
7895        assert_eq!(head, updated);
7896        assert!(state.gate_allows_progress());
7897        assert!(!state.land_sync_pending);
7898        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
7899        land_with(&mut state, &green_pr().url, &forge)
7900            .await
7901            .unwrap();
7902        assert!(state.parked);
7903        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
7904        assert!(forge.argvs().is_empty());
7905    }
7906
7907    #[tokio::test]
7908    async fn landing_resume_refuses_remote_only_and_divergent_operator_updates() {
7909        for divergent in [false, true] {
7910            let (_tmp, mut state, old) = landing_git_fixture().await;
7911            if divergent {
7912                git::git(&state.repo, &["reset", "--hard", "origin/main"])
7913                    .await
7914                    .unwrap();
7915            }
7916            std::fs::write(state.repo.join("external"), "external").unwrap();
7917            git::commit_all(&state.repo, "external update")
7918                .await
7919                .unwrap();
7920            let external = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7921            git::git(
7922                &state.repo,
7923                &["push", "--force", "origin", "HEAD:refs/heads/task-head"],
7924            )
7925            .await
7926            .unwrap();
7927            if !divergent {
7928                git::git(&state.repo, &["reset", "--hard", &old])
7929                    .await
7930                    .unwrap();
7931            }
7932            let error = resume_observed_head(&mut state, &external)
7933                .await
7934                .unwrap_err();
7935            assert!(
7936                error
7937                    .to_string()
7938                    .contains("public head moved outside this run")
7939            );
7940            assert_eq!(state.pr_pushed_head.as_ref(), Some(&old));
7941            assert_eq!(
7942                git::remote_head(&state.repo, "origin", "task-head")
7943                    .await
7944                    .unwrap(),
7945                Some(external)
7946            );
7947        }
7948    }
7949
7950    #[tokio::test]
7951    async fn landing_resume_repairs_a_failed_rebased_gate_before_publication() {
7952        let (_tmp, mut state, old) = landing_git_fixture().await;
7953        advance_landing_base(&state).await;
7954        landing_gate_fixer(
7955            &mut state,
7956            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
7957        );
7958        state.config.verify.gate =
7959            vec!["grep -q fixed change || { echo 'change needs repair'; exit 1; }".into()];
7960        state.config.verify.e2e = vec!["test -f advance".into()];
7961        // First save a red gate without spending a fixer round. Resume must
7962        // still offer the remaining budget for this exact same failed head.
7963        state.config.graph.gate_fix_rounds = 0;
7964        assert!(resume_observed_head(&mut state, &old).await.is_err());
7965        assert_eq!(
7966            git::remote_head(&state.repo, "origin", "task-head")
7967                .await
7968                .unwrap(),
7969            Some(old.clone())
7970        );
7971        state.config.graph.gate_fix_rounds = 1;
7972        let head = resume_observed_head(&mut state, &old).await.unwrap();
7973        assert_eq!(state.gate_fixes.len(), 1);
7974        assert!(state.gate_fixes[0].committed);
7975        assert!(state.gate_allows_progress());
7976        assert_eq!(state.gate_head.as_ref(), Some(&head));
7977        assert_eq!(
7978            git::remote_head(&state.repo, "origin", "task-head")
7979                .await
7980                .unwrap(),
7981            Some(head.clone())
7982        );
7983        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
7984        land_with(&mut state, &green_pr().url, &forge)
7985            .await
7986            .unwrap();
7987        assert!(state.parked);
7988        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
7989        assert!(forge.argvs().is_empty());
7990    }
7991
7992    #[tokio::test]
7993    async fn landing_gate_repairs_stop_at_the_saved_budget_without_publishing() {
7994        let (_tmp, mut state, old) = landing_git_fixture().await;
7995        advance_landing_base(&state).await;
7996        landing_gate_fixer(
7997            &mut state,
7998            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
7999        );
8000        state.config.verify.gate = vec!["echo still red; exit 1".into()];
8001        for _ in 0..2 {
8002            assert!(resume_observed_head(&mut state, &old).await.is_err());
8003            assert_eq!(state.gate_fixes.len(), 1);
8004            assert_eq!(
8005                git::remote_head(&state.repo, "origin", "task-head")
8006                    .await
8007                    .unwrap(),
8008                Some(old.clone())
8009            );
8010        }
8011    }
8012
8013    #[tokio::test]
8014    async fn landing_gate_repair_cannot_publish_failed_e2e_on_repeated_resumes() {
8015        let (_tmp, mut state, old) = landing_git_fixture().await;
8016        advance_landing_base(&state).await;
8017        landing_gate_fixer(
8018            &mut state,
8019            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
8020        );
8021        state.config.verify.gate =
8022            vec!["grep -q fixed change || { echo 'change needs repair'; exit 1; }".into()];
8023        // The repair makes the gate green while breaking an e2e invariant.
8024        state.config.verify.e2e = vec!["grep -q '^change$' change".into()];
8025        let mut saved_comparison = None;
8026        for resume in 0..3 {
8027            assert!(resume_observed_head(&mut state, &old).await.is_err());
8028            state = RunState::load(&state.id).unwrap();
8029            let evidence = state.gate_repair_e2e.as_ref().unwrap();
8030            let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8031            assert_eq!(evidence.head, head);
8032            assert!(!evidence.passed);
8033            assert!(evidence.outcomes.iter().any(|o| !o.ok()));
8034            let comparison = evidence.outcomes[0].rerun_comparison.as_ref().unwrap();
8035            if let Some(saved) = &saved_comparison {
8036                assert_eq!(comparison, saved);
8037            } else {
8038                saved_comparison = Some(comparison.clone());
8039            }
8040            assert_eq!(state.gate_fixes.len(), 1);
8041            assert_eq!(
8042                git::remote_head(&state.repo, "origin", "task-head")
8043                    .await
8044                    .unwrap(),
8045                Some(old.clone())
8046            );
8047            if resume > 0 {
8048                assert!(
8049                    state.gate_allows_progress(),
8050                    "a green gate must not bypass red e2e"
8051                );
8052            }
8053        }
8054        // A changed command is not new evidence about the already checked SHA.
8055        state.config.verify.e2e = vec!["grep -q fixed change".into()];
8056        assert!(resume_observed_head(&mut state, &old).await.is_err());
8057        assert_eq!(
8058            state.gate_repair_e2e.as_ref().unwrap().outcomes[0].rerun_comparison,
8059            saved_comparison
8060        );
8061    }
8062
8063    #[tokio::test]
8064    async fn landing_resumes_recheck_pending_deferred_and_stale_repair_e2e() {
8065        for phase in 0..3 {
8066            let (_tmp, mut state, old) = landing_git_fixture().await;
8067            advance_landing_base(&state).await;
8068            let head = resume_observed_head(&mut state, &old).await.unwrap();
8069            // Persist the shapes left by interruption, resource deferral,
8070            // and a successful check for a different (older) SHA.
8071            state.land_sync_pending = true;
8072            state.config.verify.e2e = vec!["echo e2e is red; exit 1".into()];
8073            state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
8074                if phase == 2 {
8075                    old.clone()
8076                } else {
8077                    head.clone()
8078                },
8079                phase == 2,
8080                if phase == 1 {
8081                    vec![crate::run::CommandOutcome {
8082                        command: state.config.verify.e2e[0].clone(),
8083                        code: None,
8084                        output_tail: "verification resource unavailable".into(),
8085                        duration_ms: 0,
8086                        resource_blocked: true,
8087                        ..Default::default()
8088                    }]
8089                } else {
8090                    Vec::new()
8091                },
8092            ));
8093            state.save().unwrap();
8094            for _ in 0..2 {
8095                state = RunState::load(&state.id).unwrap();
8096                assert!(resume_observed_head(&mut state, &head).await.is_err());
8097                let evidence = state.gate_repair_e2e.as_ref().unwrap();
8098                assert_eq!(evidence.head, head);
8099                assert!(!evidence.passed);
8100                assert!(!evidence.outcomes.is_empty());
8101                assert_eq!(
8102                    git::remote_head(&state.repo, "origin", "task-head")
8103                        .await
8104                        .unwrap(),
8105                    Some(head.clone())
8106                );
8107                assert!(state.land_sync_pending);
8108            }
8109        }
8110    }
8111
8112    #[tokio::test]
8113    async fn landing_resumes_recheck_abnormal_repair_e2e_exit() {
8114        for code in [None, Some(126), Some(127)] {
8115            let (_tmp, mut state, old) = landing_git_fixture().await;
8116            advance_landing_base(&state).await;
8117            let head = resume_observed_head(&mut state, &old).await.unwrap();
8118            state.land_sync_pending = true;
8119            state.config.verify.e2e = vec!["true".into()];
8120            state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
8121                head.clone(),
8122                false,
8123                vec![crate::run::CommandOutcome {
8124                    command: state.config.verify.e2e[0].clone(),
8125                    code,
8126                    output_tail: "verification command did not complete".into(),
8127                    ..Default::default()
8128                }],
8129            ));
8130            state.save().unwrap();
8131            state = RunState::load(&state.id).unwrap();
8132            assert_eq!(resume_observed_head(&mut state, &head).await.unwrap(), head);
8133            let evidence = state.gate_repair_e2e.as_ref().unwrap();
8134            assert_eq!(evidence.head, head);
8135            assert!(evidence.passed);
8136            assert_eq!(evidence.outcomes[0].code, Some(0));
8137        }
8138    }
8139
8140    async fn interrupt_landing_rebase(state: &mut RunState) {
8141        state.land_rebase_from = Some(git::rev_parse(&state.repo, "HEAD").await.unwrap());
8142        state.save().unwrap();
8143        let scratch = state.dir().join("rebase");
8144        assert_eq!(
8145            crate::rebase::rebase_with_fixer(state, &scratch, "winner", "origin/main")
8146                .await
8147                .unwrap(),
8148            crate::rebase::Rebased::Applied
8149        );
8150        assert!(!git::is_clean(&state.repo).await.unwrap());
8151    }
8152
8153    async fn landing_setup(state: &mut RunState) {
8154        git::git(
8155            &state.repo,
8156            &["config", "extensions.worktreeConfig", "true"],
8157        )
8158        .await
8159        .unwrap();
8160        state.config.worktree.setup =
8161            vec![toml::from_str("run = \"printf secret > .env\"").unwrap()];
8162        crate::worktree_setup::prepare(&state.config, &state.repo, &state.repo)
8163            .await
8164            .unwrap();
8165        state.config.verify.gate = vec!["test -f advance && test -f .env".into()];
8166    }
8167
8168    #[tokio::test]
8169    async fn landing_restores_isolated_setup_in_a_linked_checkout() {
8170        let (tmp, mut state, head) = landing_git_fixture().await;
8171        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8172        git::acquire_worktree_config(&state.repo).await.unwrap();
8173        let winner = tmp.path().join("landing");
8174        git::worktree_add_existing(&state.repo, &winner, "winner", false)
8175            .await
8176            .unwrap();
8177        state.candidates[0].worktree = winner.clone();
8178        state.config.verify.build_cache = crate::config::BuildCache::Isolated;
8179        state.config.verify.shell = Some(vec!["sh".into(), "-c".into()]);
8180        state.config.disk.min_free_bytes = 0;
8181        state.config.worktree.setup = vec![crate::config::SetupStep {
8182            run: Some("touch setup-completed".into()),
8183            ..Default::default()
8184        }];
8185        #[cfg(unix)]
8186        {
8187            std::fs::write(state.repo.join(".git/fixture-contract"), "fixture-v1").unwrap();
8188            state.config.coordination = Some(crate::config::Coordination {
8189                contract_file: "fixture-contract".into(),
8190                contract_token: "fixture-v1".into(),
8191                lock_file: "fixture-lock".into(),
8192            });
8193        }
8194        state.land_rebase_from = Some(head);
8195        let restore = restore_landing_worktree(&mut state);
8196        // Only the registered Unix fixture can deadlock by reacquiring its
8197        // own operation lease. Don't time the whole Git/setup path elsewhere.
8198        #[cfg(unix)]
8199        let restore = async {
8200            tokio::time::timeout(Duration::from_secs(15), restore)
8201                .await
8202                .expect("landing setup must not wait for its own repository operation")
8203        };
8204        restore.await.unwrap();
8205        assert!(winner.join("setup-completed").is_file());
8206        assert!(git::is_clean(&winner).await.unwrap());
8207        assert!(state.land_rebase_from.is_none());
8208    }
8209
8210    #[tokio::test]
8211    async fn landing_resume_restores_setup_after_both_fresh_and_interrupted_rebases() {
8212        for phase in 0..3 {
8213            let (_tmp, mut state, old) = landing_git_fixture().await;
8214            advance_landing_base(&state).await;
8215            landing_setup(&mut state).await;
8216            if phase > 0 {
8217                interrupt_landing_rebase(&mut state).await;
8218                if phase == 2 {
8219                    // Crash after clean removed setup products, before setup.
8220                    git::sync_to_head(&state.repo).await.unwrap();
8221                    assert!(!state.repo.join(".env").exists());
8222                }
8223                state = RunState::load(&state.id).unwrap();
8224            }
8225            let head = resume_observed_head(&mut state, &old).await.unwrap();
8226            assert_ne!(head, old);
8227            assert!(state.gate_allows_progress());
8228            assert!(state.land_rebase_from.is_none());
8229            assert_eq!(
8230                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8231                "secret"
8232            );
8233            assert!(git::is_clean(&state.repo).await.unwrap());
8234            assert!(
8235                !git::git(&state.repo, &["ls-tree", "--name-only", "HEAD"])
8236                    .await
8237                    .unwrap()
8238                    .contains(".env")
8239            );
8240        }
8241    }
8242
8243    #[tokio::test]
8244    async fn landing_restoration_protects_ignored_files_outside_setup_products() {
8245        let (_tmp, mut state, _) = landing_git_fixture().await;
8246        advance_landing_base(&state).await;
8247        landing_setup(&mut state).await;
8248        interrupt_landing_rebase(&mut state).await;
8249        // Exercise unusual names without asking Windows to create an invalid
8250        // control-character filename. Unix also covers embedded newlines.
8251        let locals = [
8252            "local notes",
8253            #[cfg(unix)]
8254            "local\nnotes",
8255        ];
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), "local*\n").unwrap();
8260        for local in locals {
8261            std::fs::write(state.repo.join(local), "keep these notes").unwrap();
8262            assert!(
8263                git::git_raw(&state.repo, &["check-ignore", "--quiet", local])
8264                    .await
8265                    .unwrap()
8266                    .ok()
8267            );
8268        }
8269        restore_landing_worktree(&mut state).await.unwrap();
8270        for local in locals {
8271            assert_eq!(
8272                std::fs::read_to_string(state.repo.join(local)).unwrap(),
8273                "keep these notes"
8274            );
8275        }
8276        assert_eq!(
8277            std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8278            "secret"
8279        );
8280        assert!(git::is_clean(&state.repo).await.unwrap());
8281        assert!(state.land_rebase_from.is_none());
8282    }
8283
8284    #[tokio::test]
8285    async fn landing_restoration_rejects_ignored_paths_conflicting_with_the_new_tree() {
8286        for local in ["advance", "advance/notes", "new-directory"] {
8287            let (_tmp, mut state, _) = landing_git_fixture().await;
8288            advance_landing_base(&state).await;
8289            // Also cover a local file blocking a new tracked directory.
8290            git::git(&state.repo, &["checkout", "main"]).await.unwrap();
8291            std::fs::create_dir(state.repo.join("new-directory")).unwrap();
8292            std::fs::write(state.repo.join("new-directory/tracked"), "new").unwrap();
8293            git::git(&state.repo, &["add", "."]).await.unwrap();
8294            git::git(&state.repo, &["commit", "-m", "add directory"])
8295                .await
8296                .unwrap();
8297            git::git(&state.repo, &["push", "origin", "main"])
8298                .await
8299                .unwrap();
8300            git::git(&state.repo, &["checkout", "winner"])
8301                .await
8302                .unwrap();
8303            let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8304                .await
8305                .unwrap();
8306            std::fs::write(state.repo.join(excludes), "advance\nnew-directory\n").unwrap();
8307            let path = state.repo.join(local);
8308            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
8309            std::fs::write(&path, "local notes").unwrap();
8310            interrupt_landing_rebase(&mut state).await;
8311            let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
8312            let checkpoint = state.land_rebase_from.clone();
8313            let error = restore_landing_worktree(&mut state).await.unwrap_err();
8314            assert!(
8315                error.to_string().contains("conflicting with HEAD"),
8316                "{error:#}"
8317            );
8318            assert_eq!(std::fs::read_to_string(&path).unwrap(), "local notes");
8319            assert_eq!(
8320                git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
8321                before
8322            );
8323            assert_eq!(state.land_rebase_from, checkpoint);
8324        }
8325    }
8326
8327    #[tokio::test]
8328    async fn landing_resume_preserves_ignored_gate_artifacts_without_setup() {
8329        for interrupted in [false, true] {
8330            let (_tmp, mut state, old) = landing_git_fixture().await;
8331            assert!(state.config.worktree.setup.is_empty());
8332            // A gate product exists before the base moves, without setup metadata.
8333            let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8334                .await
8335                .unwrap();
8336            std::fs::write(state.repo.join(excludes), "target/\n").unwrap();
8337            state.config.verify.gate =
8338                vec!["mkdir -p target && printf artifact > target/probe".into()];
8339            state.gate_ran = false;
8340            resume_observed_head(&mut state, &old).await.unwrap();
8341            assert_eq!(
8342                std::fs::read_to_string(state.repo.join("target/probe")).unwrap(),
8343                "artifact"
8344            );
8345            advance_landing_base(&state).await;
8346            if interrupted {
8347                interrupt_landing_rebase(&mut state).await;
8348                state = RunState::load(&state.id).unwrap();
8349            }
8350            state.config.verify.gate =
8351                vec!["test -f advance && test \"$(cat target/probe)\" = artifact".into()];
8352            let head = resume_observed_head(&mut state, &old).await.unwrap();
8353            assert_ne!(head, old);
8354            assert!(state.gate_allows_progress());
8355            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
8356            assert_eq!(
8357                std::fs::read_to_string(state.repo.join("target/probe")).unwrap(),
8358                "artifact"
8359            );
8360            assert!(state.land_rebase_from.is_none());
8361            assert_eq!(
8362                git::remote_head(&state.repo, "origin", "task-head")
8363                    .await
8364                    .unwrap(),
8365                Some(head.clone())
8366            );
8367            let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8368            land_with(&mut state, &green_pr().url, &forge)
8369                .await
8370                .unwrap();
8371            assert!(state.parked);
8372            assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8373            assert!(forge.argvs().is_empty());
8374        }
8375    }
8376
8377    #[tokio::test]
8378    #[cfg(unix)]
8379    async fn landing_restoration_waits_for_external_coordination_before_changing_files() {
8380        use std::os::fd::AsRawFd as _;
8381
8382        for interrupted in [false, true] {
8383            let (_tmp, mut state, _) = landing_git_fixture().await;
8384            advance_landing_base(&state).await;
8385            landing_setup(&mut state).await;
8386            if interrupted {
8387                interrupt_landing_rebase(&mut state).await;
8388            }
8389            state.config.worktree.setup =
8390                vec![toml::from_str("run = \"printf restored > .env\"").unwrap()];
8391            let common = crate::repo_lock::common_dir(&state.repo)
8392                .await
8393                .unwrap()
8394                .unwrap();
8395            std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
8396            state.config.coordination = crate::config::test_coordination();
8397            state.config.graph.timeout_resource_wait = 0;
8398            let external = std::fs::OpenOptions::new()
8399                .read(true)
8400                .write(true)
8401                .create(true)
8402                .truncate(false)
8403                .open(common.join("updater.lock"))
8404                .unwrap();
8405            // SAFETY: the descriptor belongs to `external` and remains open.
8406            let locked =
8407                unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
8408            assert_eq!(locked, 0);
8409            let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
8410            let checkpoint = state.land_rebase_from.clone();
8411            let error = restore_landing_worktree(&mut state).await.unwrap_err();
8412            assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8413            assert_eq!(
8414                git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
8415                before
8416            );
8417            assert_eq!(state.land_rebase_from, checkpoint);
8418            assert_eq!(
8419                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8420                "secret"
8421            );
8422
8423            drop(external);
8424            state.config.graph.timeout_resource_wait = 2;
8425            restore_landing_worktree(&mut state).await.unwrap();
8426            assert!(git::is_clean(&state.repo).await.unwrap());
8427            assert!(state.land_rebase_from.is_none());
8428            assert_eq!(
8429                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8430                "restored"
8431            );
8432        }
8433    }
8434
8435    #[tokio::test]
8436    #[cfg(unix)]
8437    async fn landing_restoration_inherits_cancellation_while_waiting_for_a_local_seat() {
8438        use std::sync::atomic::{AtomicBool, Ordering};
8439
8440        let (_tmp, mut state, _) = landing_git_fixture().await;
8441        advance_landing_base(&state).await;
8442        landing_setup(&mut state).await;
8443        interrupt_landing_rebase(&mut state).await;
8444        let common = crate::repo_lock::common_dir(&state.repo)
8445            .await
8446            .unwrap()
8447            .unwrap();
8448        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
8449        state.config.coordination = crate::config::test_coordination();
8450        let holder = crate::repo_lock::SeatLease::for_checkout(
8451            &state.repo,
8452            true,
8453            state.config.coordination.as_ref(),
8454        )
8455        .await
8456        .unwrap();
8457        assert!(holder.is_some());
8458        let cancelled = Arc::new(AtomicBool::new(false));
8459        let signal = cancelled.clone();
8460        let wait = crate::repo_lock::WaitPolicy::new(Duration::from_secs(30), move || {
8461            signal.load(Ordering::SeqCst)
8462        });
8463        let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
8464        let checkpoint = state.land_rebase_from.clone();
8465        let (result, ()) = tokio::join!(
8466            tokio::time::timeout(
8467                Duration::from_secs(2),
8468                wait.scope(restore_landing_worktree(&mut state)),
8469            ),
8470            async {
8471                tokio::time::sleep(Duration::from_millis(100)).await;
8472                cancelled.store(true, Ordering::SeqCst);
8473            }
8474        );
8475        let error = result
8476            .expect("cancellation must release the waiting driver")
8477            .unwrap_err();
8478        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8479        assert_eq!(
8480            git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
8481            before
8482        );
8483        assert_eq!(state.land_rebase_from, checkpoint);
8484        assert_eq!(
8485            std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8486            "secret"
8487        );
8488        drop(holder);
8489        restore_landing_worktree(&mut state).await.unwrap();
8490        assert!(state.land_rebase_from.is_none());
8491        assert!(git::is_clean(&state.repo).await.unwrap());
8492    }
8493
8494    #[tokio::test]
8495    #[cfg(unix)]
8496    async fn landing_verification_inherits_cancellation_while_waiting_for_a_local_seat() {
8497        use std::sync::atomic::{AtomicBool, Ordering};
8498
8499        for e2e in [false, true] {
8500            let (_tmp, mut state, head) = landing_git_fixture().await;
8501            let common = crate::repo_lock::common_dir(&state.repo)
8502                .await
8503                .unwrap()
8504                .unwrap();
8505            std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
8506            state.config.coordination = crate::config::test_coordination();
8507            if e2e {
8508                state.config.verify.e2e = vec!["true".into()];
8509                state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
8510                    head.clone(),
8511                    false,
8512                    Vec::new(),
8513                ));
8514            } else {
8515                state.config.verify.gate = vec!["true".into()];
8516                state.gate_ran = false;
8517            }
8518            let holder = crate::repo_lock::SeatLease::for_checkout(
8519                &state.repo,
8520                true,
8521                state.config.coordination.as_ref(),
8522            )
8523            .await
8524            .unwrap();
8525            assert!(holder.is_some());
8526            let cancelled = Arc::new(AtomicBool::new(false));
8527            let signal = cancelled.clone();
8528            let waiting = Arc::new(tokio::sync::Notify::new());
8529            let observed = waiting.clone();
8530            let wait = crate::repo_lock::WaitPolicy::new(Duration::from_secs(30), move || {
8531                observed.notify_one();
8532                signal.load(Ordering::SeqCst)
8533            });
8534            let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8535            let url = green_pr().url;
8536            let result = {
8537                let mut publishing =
8538                    Box::pin(wait.scope(publish_landing_head(&mut state, &head, &url, &forge)));
8539                // Git and fixture I/O precede local coordination. Start the
8540                // cancellation deadline only once the inherited wait policy
8541                // is polled, rather than timing those unrelated subprocesses.
8542                tokio::time::timeout(Duration::from_secs(30), async {
8543                    tokio::select! {
8544                        result = &mut publishing => panic!(
8545                            "verification must wait behind the held seat: {result:?}"
8546                        ),
8547                        () = waiting.notified() => {}
8548                    }
8549                })
8550                .await
8551                .expect("verification must reach the inherited coordination wait");
8552                cancelled.store(true, Ordering::SeqCst);
8553                tokio::time::timeout(Duration::from_secs(2), publishing).await
8554            };
8555            let error = result
8556                .expect("cancellation must release the verification waiter")
8557                .unwrap_err();
8558            assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8559            assert!(error.to_string().contains("cancelled"), "{error:#}");
8560            assert!(forge.argvs().is_empty());
8561            assert_eq!(
8562                git::remote_head(&state.repo, "origin", "task-head")
8563                    .await
8564                    .unwrap(),
8565                Some(head.clone())
8566            );
8567            drop(holder);
8568            // Cancellation must release its reservation so another attempt can verify.
8569            assert_eq!(
8570                publish_landing_head(&mut state, &head, &url, &forge)
8571                    .await
8572                    .unwrap(),
8573                head
8574            );
8575        }
8576    }
8577
8578    #[tokio::test]
8579    async fn landing_resume_preserves_user_edits_after_an_interrupted_rebase() {
8580        for staged in [false, true] {
8581            let (_tmp, mut state, old) = landing_git_fixture().await;
8582            advance_landing_base(&state).await;
8583            interrupt_landing_rebase(&mut state).await;
8584            std::fs::write(state.repo.join("change"), "user edit").unwrap();
8585            if staged {
8586                git::git(&state.repo, &["add", "change"]).await.unwrap();
8587            }
8588            assert!(resume_observed_head(&mut state, &old).await.is_err());
8589            assert_eq!(
8590                std::fs::read_to_string(state.repo.join("change")).unwrap(),
8591                "user edit"
8592            );
8593            assert_eq!(
8594                git::remote_head(&state.repo, "origin", "task-head")
8595                    .await
8596                    .unwrap(),
8597                Some(old)
8598            );
8599        }
8600    }
8601
8602    #[tokio::test]
8603    async fn landing_resume_returns_to_approval_wait_and_closed_pr_skips_sync() {
8604        let (_tmp, mut state, head) = landing_git_fixture().await;
8605        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8606        let id = state.id.clone();
8607        let pr = land_with(&mut state, &green_pr().url, &forge)
8608            .await
8609            .unwrap();
8610        assert_eq!(pr.state, PrLifecycle::Open);
8611        assert_eq!(state.id, id);
8612        assert!(state.parked);
8613        assert_eq!(state.status, RunStatus::Landing);
8614        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8615        assert!(forge.argvs().is_empty());
8616
8617        state.land_sync_pending = true;
8618        std::fs::write(state.repo.join("dirty"), "do not touch").unwrap();
8619        let mut closed = seen("foreign", Checks::Green, "CLEAN", false);
8620        closed.pr.state = PrLifecycle::Closed;
8621        let forge = Scripted::new(vec![closed], vec![]);
8622        assert_eq!(
8623            land_with(&mut state, &green_pr().url, &forge)
8624                .await
8625                .unwrap()
8626                .state,
8627            PrLifecycle::Closed
8628        );
8629        assert_eq!(
8630            std::fs::read_to_string(state.repo.join("dirty")).unwrap(),
8631            "do not touch"
8632        );
8633        assert!(forge.argvs().is_empty());
8634    }
8635
8636    #[tokio::test]
8637    async fn landing_resume_does_not_publish_a_failed_rebased_gate() {
8638        let (_tmp, mut state, old) = landing_git_fixture().await;
8639        advance_landing_base(&state).await;
8640        state.config.verify.gate = vec!["exit 1".into()];
8641        assert!(resume_observed_head(&mut state, &old).await.is_err());
8642        assert_ne!(state.gate_head.as_deref(), Some(old.as_str()));
8643        assert!(!state.gate_allows_progress());
8644        assert_eq!(
8645            git::remote_head(&state.repo, "origin", "task-head")
8646                .await
8647                .unwrap(),
8648            Some(old)
8649        );
8650        assert!(state.land_sync_pending);
8651    }
8652
8653    #[tokio::test]
8654    async fn landing_publication_recovers_a_push_before_save_and_refuses_a_lease_conflict() {
8655        let (_tmp, mut state, old) = landing_git_fixture().await;
8656        advance_landing_base(&state).await;
8657        let pushed = resume_observed_head(&mut state, &old).await.unwrap();
8658        // Model a crash after the push but before saving its published SHA.
8659        state.pr_pushed_head = Some(old.clone());
8660        state.land_sync_pending = true;
8661        assert_eq!(
8662            resume_observed_head(&mut state, &pushed).await.unwrap(),
8663            pushed
8664        );
8665        // A writer races the observed PR snapshot: the explicit remote lease
8666        // must reject the push even though preflight saw our expected head.
8667        git::git(
8668            &state.repo,
8669            &["push", "--force", "origin", "main:refs/heads/task-head"],
8670        )
8671        .await
8672        .unwrap();
8673        assert!(
8674            publish_landing_head(
8675                &mut state,
8676                &pushed,
8677                &green_pr().url,
8678                &Scripted::new(vec![seen(&pushed, Checks::Green, "CLEAN", false)], vec![])
8679            )
8680            .await
8681            .unwrap_err()
8682            .to_string()
8683            .contains("publishing gated")
8684        );
8685        assert!(
8686            resume_observed_head(&mut state, "foreign-head")
8687                .await
8688                .is_err()
8689        );
8690    }
8691    #[tokio::test]
8692    async fn landing_publication_refuses_a_pr_closed_during_gate() {
8693        let (_tmp, mut state, head) = landing_git_fixture().await;
8694        let mut closed = seen(&head, Checks::Green, "CLEAN", false);
8695        closed.pr.state = PrLifecycle::Closed;
8696        let forge = Scripted::new(vec![closed], vec![]);
8697        assert!(
8698            publish_landing_head(&mut state, &head, &green_pr().url, &forge)
8699                .await
8700                .unwrap_err()
8701                .to_string()
8702                .contains("PR closed or merged")
8703        );
8704    }
8705
8706    /// A candidate selected by the uncontested tally.
8707    fn winning_candidate(summary: &str) -> Candidate {
8708        Candidate {
8709            index: 0,
8710            label: 'A',
8711            agent: "opus".to_owned(),
8712            branch: "magi/x/A".to_owned(),
8713            worktree: PathBuf::from("/wt/A"),
8714            summary: summary.to_owned(),
8715            stat: String::new(),
8716            files: 1,
8717            commits: 1,
8718            empty: false,
8719            failed: None,
8720            verified_noop: None,
8721            duration_ms: 0,
8722            folded: false,
8723        }
8724    }
8725
8726    fn uncontested_tally() -> Tally {
8727        Tally {
8728            first_choice: BTreeMap::from([('A', 1)]),
8729            borda: BTreeMap::new(),
8730            winner: 'A',
8731            rankings: 1,
8732            unanimous_initial: true,
8733            deliberated: false,
8734            changed_votes: 0,
8735            unanimous_final: true,
8736            tie_break: None,
8737            judges: 1,
8738            present: 1,
8739            quorum: 1,
8740            met_quorum: true,
8741            uncontested: None,
8742        }
8743    }
8744
8745    fn review_record(reviewer: usize, agent: &str, summary: &str) -> ReviewRecord {
8746        ReviewRecord {
8747            attempts: 0,
8748            reviewer,
8749            agent: agent.to_owned(),
8750            summary: summary.to_owned(),
8751            findings: Vec::new(),
8752            vote: None,
8753            failed: None,
8754            duration_ms: 0,
8755        }
8756    }
8757
8758    fn review_round(round: usize, reviews: Vec<ReviewRecord>) -> ReviewRound {
8759        let answered = reviews.len();
8760        ReviewRound {
8761            round,
8762            head: "abc1234".to_owned(),
8763            verified_head: None,
8764            verified_at: None,
8765            reviews,
8766            e2e: Vec::new(),
8767            verify_retried: false,
8768            e2e_deferred: false,
8769            e2e_defer_reason: None,
8770            fix: None,
8771            blocking: 0,
8772            answered,
8773            expected: answered,
8774            clean: true,
8775            progressed: false,
8776            vote_split: false,
8777            reconsideration: Vec::new(),
8778            verdict: None,
8779        }
8780    }
8781
8782    #[test]
8783    fn the_approval_panel_states_the_task_verbatim_in_either_language() {
8784        let en = panel();
8785        assert!(en.contains("Task"), "{en}");
8786        assert!(en.contains("add retries to the uploader"), "{en}");
8787
8788        let mut state = run_state();
8789        state.config.graph.language = "ja".to_owned();
8790        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8791        assert!(ja.contains("タスク"), "{ja}");
8792        assert!(
8793            ja.contains("add retries to the uploader"),
8794            "the task itself is not translated: {ja}"
8795        );
8796    }
8797
8798    #[test]
8799    fn the_approval_panel_omits_what_changed_and_review_verdict_with_no_data() {
8800        // `run_state()` has no candidates, no tally and no reviews - exactly
8801        // the shape a run has before anything has judged or reviewed it, and
8802        // the panel must not print an empty box for either.
8803        let html = panel();
8804        assert!(!html.contains("What changed"), "{html}");
8805        assert!(!html.contains("Review verdict"), "{html}");
8806    }
8807
8808    #[test]
8809    fn the_approval_panel_omits_what_changed_when_the_winners_summary_is_empty() {
8810        let mut state = run_state();
8811        state.candidates = vec![winning_candidate("")];
8812        state.tally = Some(uncontested_tally());
8813        let html = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8814        assert!(
8815            !html.contains("What changed"),
8816            "an empty summary must not render an empty box: {html}"
8817        );
8818    }
8819
8820    #[test]
8821    fn the_approval_panel_shows_the_winners_own_account_in_either_language() {
8822        let mut state = run_state();
8823        state.candidates = vec![winning_candidate(
8824            "Added a retry loop around the uploader PUT call.",
8825        )];
8826        state.tally = Some(uncontested_tally());
8827        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8828        assert!(en.contains("What changed"), "{en}");
8829        assert!(
8830            en.contains("Added a retry loop around the uploader PUT call."),
8831            "{en}"
8832        );
8833
8834        state.config.graph.language = "ja".to_owned();
8835        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8836        assert!(ja.contains("変更内容"), "{ja}");
8837        assert!(
8838            ja.contains("Added a retry loop around the uploader PUT call."),
8839            "{ja}"
8840        );
8841    }
8842
8843    #[test]
8844    fn the_approval_panel_shows_only_the_last_review_rounds_verdict() {
8845        let mut state = run_state();
8846        state.reviews = vec![
8847            review_round(
8848                1,
8849                vec![review_record(1, "alpha", "found a race, sent back")],
8850            ),
8851            review_round(2, vec![review_record(1, "alpha", "race is fixed, clean")]),
8852        ];
8853        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8854        assert!(en.contains("Review verdict"), "{en}");
8855        assert!(en.contains("race is fixed, clean"), "{en}");
8856        assert!(
8857            !en.contains("found a race, sent back"),
8858            "only the round that actually cleared the merge should show: {en}"
8859        );
8860
8861        state.config.graph.language = "ja".to_owned();
8862        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8863        assert!(ja.contains("レビューの結論"), "{ja}");
8864        assert!(ja.contains("レビュアー"), "{ja}");
8865        assert!(ja.contains("race is fixed, clean"), "{ja}");
8866    }
8867
8868    /// The `incomplete_review = "warn"` policy (see
8869    /// `graph::Runner::review_loop`) can push a `clean` round to
8870    /// `state.reviews` while one seat's own record still has `failed: Some`
8871    /// and an empty `summary` - a seat that never answered, not one that
8872    /// answered with nothing to say.
8873    fn unanswered_review_record(reviewer: usize, agent: &str, reason: &str) -> ReviewRecord {
8874        ReviewRecord {
8875            attempts: 0,
8876            reviewer,
8877            agent: agent.to_owned(),
8878            summary: String::new(),
8879            findings: Vec::new(),
8880            vote: None,
8881            failed: Some(reason.to_owned()),
8882            duration_ms: 0,
8883        }
8884    }
8885
8886    #[test]
8887    fn the_approval_panel_never_shows_an_unanswered_seat_as_a_blank_verdict() {
8888        let mut state = run_state();
8889        state.reviews = vec![review_round(
8890            1,
8891            vec![
8892                review_record(1, "alpha", "clean, nothing to add"),
8893                unanswered_review_record(2, "beta", "timed out"),
8894            ],
8895        )];
8896        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8897        assert!(en.contains("clean, nothing to add"), "{en}");
8898        assert!(
8899            en.contains("produced no answer: timed out"),
8900            "a seat that never answered must say so, not render a blank box: {en}"
8901        );
8902        assert!(
8903            !en.contains("<div style=\"white-space:pre-wrap;font-size:13px\"></div>"),
8904            "no reviewer box may be left empty: {en}"
8905        );
8906
8907        state.config.graph.language = "ja".to_owned();
8908        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8909        assert!(ja.contains("回答なし: timed out"), "{ja}");
8910    }
8911
8912    #[test]
8913    fn the_approval_panel_contains_nothing_the_frames_policy_would_block() {
8914        let html = panel();
8915        assert!(!html.contains("<script"), "no script survives the csp");
8916        assert!(!html.contains("<form"), "form-action is 'none'");
8917        let pr = green_pr();
8918        assert_eq!(
8919            html.matches("http").count(),
8920            html.matches(pr.url.as_str()).count(),
8921            "the only http url in the panel is the pull request's own link"
8922        );
8923        assert!(
8924            html.contains("target=\"_blank\""),
8925            "the PR link must open in a new tab so it escapes the iframe"
8926        );
8927        assert!(
8928            html.contains("rel=\"noopener noreferrer\""),
8929            "external links opening in new tabs must carry noopener noreferrer"
8930        );
8931    }
8932
8933    #[test]
8934    fn added_and_removed_diff_lines_are_distinguishable_without_colour() {
8935        let html = panel();
8936        assert!(
8937            html.contains(">+</span>"),
8938            "an added line carries a `+` in the gutter, not only a background"
8939        );
8940        assert!(
8941            html.contains(">-</span>"),
8942            "a removed line carries a `-` in the gutter, not only a background"
8943        );
8944        assert!(
8945            html.contains(">new line</span>"),
8946            "the marker is moved to the gutter, so the body is printed once without it"
8947        );
8948    }
8949
8950    #[test]
8951    fn a_diff_past_the_threshold_is_cut_with_an_honest_count() {
8952        let total = DIFF_MAX_LINES + 100;
8953        let diff: String = (0..total).map(|i| format!("+line {i}\n")).collect();
8954        let html = approval_panel(
8955            &run_state(),
8956            &green_pr(),
8957            NUMSTAT,
8958            &diff,
8959            &[],
8960            "feat: something long",
8961        );
8962        assert!(
8963            html.contains(&format!("100 of {total} diff lines omitted")),
8964            "the note must say exactly how much was cut"
8965        );
8966        assert!(html.contains(&format!("line {}", DIFF_MAX_LINES - 1)));
8967        assert!(
8968            !html.contains(&format!("line {DIFF_MAX_LINES}")),
8969            "nothing past the threshold is rendered"
8970        );
8971        assert!(
8972            html.contains("/repo/magi"),
8973            "the note says where the rest is"
8974        );
8975    }
8976
8977    #[test]
8978    fn a_path_with_html_metacharacters_is_escaped_rather_than_rendered() {
8979        let html = approval_panel(
8980            &run_state(),
8981            &green_pr(),
8982            "1\t2\tsrc/<b>&\"x\"'.rs",
8983            "",
8984            &[],
8985            "subject",
8986        );
8987        assert!(html.contains("src/&lt;b&gt;&amp;&quot;x&quot;&#39;.rs"));
8988        assert!(
8989            !html.contains("<b>"),
8990            "an agent-influenced path must never become markup"
8991        );
8992    }
8993
8994    #[tokio::test]
8995    async fn the_merge_lock_serialises_one_repository_but_never_a_different_one() {
8996        let a = std::path::PathBuf::from("/repo/a");
8997        let b = std::path::PathBuf::from("/repo/b");
8998
8999        let held = repo_merge_lock(&a).lock_owned().await;
9000
9001        // A second, concurrent land run against the *same* repository must
9002        // wait - `try_lock` fails while `held` is alive.
9003        assert!(
9004            repo_merge_lock(&a).try_lock().is_err(),
9005            "a second merge into the same repository must not proceed concurrently"
9006        );
9007
9008        // A run against a *different* repository must not be blocked by it -
9009        // this is what keeps a slow rebase or `gh pr merge` in one
9010        // repository from also stalling a land-approval resume in another.
9011        assert!(
9012            repo_merge_lock(&b).try_lock().is_ok(),
9013            "a different repository's merge lock must be independent"
9014        );
9015
9016        drop(held);
9017        assert!(
9018            repo_merge_lock(&a).try_lock().is_ok(),
9019            "the lock is released once the holder is done"
9020        );
9021    }
9022
9023    pub(crate) fn repair_state(major: bool, reject: bool) -> RunState {
9024        let mut state = landing_state();
9025        let mut rec = review_record(1, "alpha", "precise rejection reason");
9026        rec.vote = Some(if reject {
9027            crate::verdict::ReviewVote::Reject
9028        } else {
9029            crate::verdict::ReviewVote::Approve
9030        });
9031        if major {
9032            rec.findings = contested().findings;
9033        }
9034        let mut round = review_round(1, vec![rec]);
9035        round.clean = false;
9036        round.blocking = usize::from(major);
9037        state.reviews.push(round);
9038        state.config.graph.review_rounds = 1;
9039        state
9040    }
9041
9042    #[test]
9043    fn approval_policy_controls_are_independent_and_keep_all_reasons() {
9044        for every in [false, true] {
9045            for contested in [false, true] {
9046                for major in [false, true] {
9047                    for reject in [false, true] {
9048                        let mut state = repair_state(major, reject);
9049                        state.config.graph.land_approval = every;
9050                        state.config.graph.hold_contested_merge = contested;
9051                        let reasons = approval_reasons(&state);
9052                        assert_eq!(reasons.contains(&ApprovalReason::EveryMerge), every);
9053                        assert_eq!(
9054                            reasons.contains(&ApprovalReason::OpenBlockingFindings),
9055                            contested && major
9056                        );
9057                        assert_eq!(
9058                            reasons.contains(&ApprovalReason::FinalReject),
9059                            contested && reject
9060                        );
9061                        assert_eq!(
9062                            reasons.len(),
9063                            usize::from(every)
9064                                + usize::from(contested && major)
9065                                + usize::from(contested && reject)
9066                        );
9067                    }
9068                }
9069            }
9070        }
9071    }
9072
9073    #[test]
9074    fn approval_policy_and_rendering_follow_reconsideration_in_both_directions() {
9075        use crate::verdict::ReviewVote::{Approve, Reject};
9076        for (initial_reject, final_vote) in [(true, Approve), (false, Reject)] {
9077            let mut state = repair_state(false, initial_reject);
9078            state.reviews[0]
9079                .reconsideration
9080                .push(crate::run::ReviewRevoteRecord {
9081                    reviewer: 1,
9082                    agent: "alpha".into(),
9083                    vote: Some(final_vote),
9084                    reason: "changed after reading the panel <evidence>".into(),
9085                    failed: None,
9086                });
9087            assert_eq!(
9088                approval_reasons(&state).contains(&ApprovalReason::FinalReject),
9089                final_vote == Reject
9090            );
9091            for language in ["en", "ja"] {
9092                state.config.graph.language = language.into();
9093                let evidence = approval_evidence(&state);
9094                assert!(evidence.contains(&format!("→ {}", final_vote.label())));
9095                assert!(evidence.contains("changed after reading the panel <evidence>"));
9096                let html = approval_panel(&state, &green_pr(), "", "", &[], "subject");
9097                assert!(html.contains("changed after reading the panel &lt;evidence&gt;"));
9098                assert!(!html.contains("<evidence>"));
9099            }
9100            state.reviews[0].reconsideration[0].vote = None;
9101            state.reviews[0].reconsideration[0].failed = Some("timed out".into());
9102            assert_eq!(
9103                approval_reasons(&state).contains(&ApprovalReason::FinalReject),
9104                initial_reject
9105            );
9106            assert!(approval_evidence(&state).contains("timed out"));
9107        }
9108    }
9109
9110    #[tokio::test]
9111    async fn approval_merge_paths_apply_controls_to_major_and_reject_independently() {
9112        for every in [false, true] {
9113            for contested in [false, true] {
9114                for (major, reject) in [(false, false), (false, true), (true, false), (true, true)]
9115                {
9116                    let mut state = repair_state(major, reject);
9117                    state.config.graph.land_approval = every;
9118                    state.config.graph.hold_contested_merge = contested;
9119                    let forge = Scripted::new(
9120                        vec![seen("abc", Checks::Green, "CLEAN", false)],
9121                        vec![(true, "")],
9122                    );
9123                    land_with(&mut state, URL, &forge).await.unwrap();
9124                    let expected = every || (contested && (major || reject));
9125                    assert_eq!(state.land_approval.is_some(), expected);
9126                    assert_eq!(forge.calls().contains(&"merge"), !expected);
9127                    if expected {
9128                        assert!(state.parked);
9129                    }
9130                }
9131            }
9132        }
9133    }
9134
9135    #[tokio::test]
9136    async fn reviewed_branch_hold_is_read_before_landing_decision() {
9137        for (base, control) in [
9138            (false, "land_approval"),
9139            (true, "land_approval"),
9140            (false, "hold_contested_merge"),
9141        ] {
9142            let (_tmp, mut state, _) = landing_git_fixture().await;
9143            state.config.graph.land_approval = base;
9144            state.config.graph.hold_contested_merge = false;
9145            state.reviewed_commits = Some(Vec::new());
9146            if control == "hold_contested_merge" {
9147                state.reviews = repair_state(false, true).reviews;
9148            }
9149            std::fs::write(
9150                state.repo.join("magi.toml"),
9151                format!("[graph]\n{control} = {}\n", !base),
9152            )
9153            .unwrap();
9154            git::git(&state.repo, &["add", "magi.toml"]).await.unwrap();
9155            git::git(&state.repo, &["commit", "-m", "approval policy"])
9156                .await
9157                .unwrap();
9158            let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
9159            state.land_sync_pending = false;
9160            state.pr_pushed_head = Some(head.clone());
9161            state.gate_head = Some(head.clone());
9162            let forge = Scripted::new(
9163                vec![seen(&head, Checks::Green, "CLEAN", false)],
9164                vec![(true, "")],
9165            );
9166            land_with(&mut state, URL, &forge).await.unwrap();
9167            assert!(
9168                state.land_approval.is_some(),
9169                "base={base}, control={control}"
9170            );
9171            assert!(!forge.calls().contains(&"merge"));
9172            if !base {
9173                let question = ask::Questions::open()
9174                    .get(&state.land_approval.as_ref().unwrap().question)
9175                    .unwrap();
9176                assert!(question.detail.contains(&format!(
9177                    "{control}=true from the reviewed branch's magi.toml"
9178                )));
9179            }
9180        }
9181    }
9182
9183    #[tokio::test]
9184    async fn reviewed_branch_hold_asks_and_survives_removal_and_resume() {
9185        for file in ["magi.toml", ".magi/config.toml"] {
9186            for control in crate::config::OwnerHold::ALL {
9187                let (_tmp, mut state, _) = landing_git_fixture().await;
9188                state.config.graph.land_approval = false;
9189                state.config.graph.hold_contested_merge = false;
9190                state.reviewed_commits = Some(Vec::new());
9191                if control == crate::config::OwnerHold::HoldContestedMerge {
9192                    state.reviews = repair_state(false, true).reviews;
9193                }
9194                let config = state.repo.join(file);
9195                std::fs::create_dir_all(config.parent().unwrap()).unwrap();
9196                std::fs::write(
9197                    &config,
9198                    format!(
9199                        "[graph]\n{} = true\n[verify]\ngate = ['untrusted']\n",
9200                        control.key()
9201                    ),
9202                )
9203                .unwrap();
9204                git::git(&state.repo, &["add", file]).await.unwrap();
9205                git::git(&state.repo, &["commit", "-m", "require approval"])
9206                    .await
9207                    .unwrap();
9208                let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
9209                let gate = state.config.verify.gate.clone();
9210                state.observe_branch_owner_holds(&head).await;
9211                assert_eq!(state.config.verify.gate, gate);
9212                assert!(state.owner_hold(control));
9213                let holds = state.branch_owner_holds.clone();
9214                git::git(&state.repo, &["rm", file]).await.unwrap();
9215                git::git(&state.repo, &["commit", "-m", "remove config"])
9216                    .await
9217                    .unwrap();
9218                let later = git::rev_parse(&state.repo, "HEAD").await.unwrap();
9219                state.save().unwrap();
9220                state = RunState::load(&state.id).unwrap();
9221                state.observe_branch_owner_holds(&later).await;
9222                assert_eq!(state.branch_owner_holds, holds);
9223                assert_eq!(state.branch_owner_holds[0].head, head);
9224                state.land_sync_pending = false;
9225                state.pr_pushed_head = Some(later.clone());
9226                state.gate_head = Some(later.clone());
9227                let forge = Scripted::new(
9228                    vec![seen(&later, Checks::Green, "CLEAN", false)],
9229                    vec![(true, "")],
9230                );
9231                land_with(&mut state, URL, &forge).await.unwrap();
9232                assert!(!forge.calls().contains(&"merge"));
9233                assert!(state.parked);
9234                let question = ask::Questions::open()
9235                    .get(&state.land_approval.as_ref().unwrap().question)
9236                    .unwrap();
9237                assert!(question.detail.contains("Approval required because:"));
9238                assert!(question.detail.contains(&format!(
9239                    "{}=true from the reviewed branch's {file}",
9240                    control.key()
9241                )));
9242                assert_eq!(state.branch_owner_holds, holds);
9243                state.save().unwrap();
9244                let resumed = RunState::load(&state.id).unwrap();
9245                assert!(resumed.owner_hold(control));
9246                assert_eq!(resumed.branch_owner_holds, holds);
9247                assert_eq!(
9248                    resumed.land_approval.unwrap().question,
9249                    state.land_approval.unwrap().question
9250                );
9251            }
9252        }
9253    }
9254
9255    #[tokio::test]
9256    async fn approval_snapshot_exposes_minor_findings_and_survives_disabled_controls() {
9257        let mut state = repair_state(false, true);
9258        state.reviews[0].clean = true;
9259        let mut finding = contested().findings.remove(0);
9260        finding.severity = crate::verdict::Severity::Minor;
9261        state.reviews[0].reviews[0].findings.push(finding);
9262        assert!(state.open_findings().is_empty());
9263        let mut pr = green_pr();
9264        pr.review_comments.clear();
9265        for language in ["en", "ja"] {
9266            state.config.graph.language = language.into();
9267            let html = approval_panel(&state, &pr, "", "", &[], "subject");
9268            assert!(html.contains("[R3-1-1] minor"));
9269            assert!(html.contains(if language == "ja" {
9270                "内部指摘の解決を意味するものではありません"
9271            } else {
9272                "This does not mean internal findings are resolved"
9273            }));
9274            assert!(
9275                html.find(if language == "ja" {
9276                    "承認が必要な理由:"
9277                } else {
9278                    "Approval required because:"
9279                })
9280                .unwrap()
9281                    < html.find("[R3-1-1]").unwrap()
9282            );
9283        }
9284        state.config.graph.language = "en".into();
9285        let observed = seen("abc", Checks::Green, "CLEAN", false);
9286        assert_eq!(
9287            approval_gate(&mut state, &observed.pr, "subject", None, "abc")
9288                .await
9289                .unwrap(),
9290            ApprovalGate::Pending
9291        );
9292        let id = state.land_approval.as_ref().unwrap().question.clone();
9293        let q = ask::Questions::open().get(&id).unwrap();
9294        assert!(q.detail.starts_with("Approval required because:"));
9295        assert!(q.detail.contains("final reviewer reject"));
9296        assert!(q.detail.contains("[R3-1-1] minor"));
9297        assert!(
9298            q.detail
9299                .contains("No adoption or resolution evidence recorded")
9300        );
9301        state.config.graph.land_approval = false;
9302        state.config.graph.hold_contested_merge = false;
9303        state.reviews.clear();
9304        assert_eq!(approval_reasons(&state), [ApprovalReason::ExistingDecision]);
9305        assert!(deputy_brief(&q, Some(&state)).contains("final reviewer reject"));
9306        assert!(deputy_brief(&q, None).contains("[R3-1-1] minor"));
9307        let forge = Scripted::new(vec![observed], vec![]);
9308        land_with(&mut state, URL, &forge).await.unwrap();
9309        assert!(!forge.calls().contains(&"merge"));
9310        assert_eq!(state.land_approval.as_ref().unwrap().question, id);
9311        assert_eq!(ask::Questions::open().get(&id).unwrap().detail, q.detail);
9312    }
9313
9314    #[tokio::test]
9315    async fn approval_evidence_keeps_all_findings_and_bounds_unicode_prose() {
9316        let mut state = repair_state(false, true);
9317        state.config.graph.land_approval = false;
9318        let long_reason = format!("{}REASON_TAIL", "拒否🦀".repeat(200));
9319        let long_detail = format!("{}DETAIL_TAIL", "詳細🦀".repeat(200));
9320        let long_title = format!("{}TITLE_TAIL", "題🦀".repeat(100));
9321        state.reviews[0].reviews[0].summary = long_reason.clone();
9322        for i in 1..=10 {
9323            let mut finding = contested().findings.remove(0);
9324            finding.id = format!("R1-1-{i}");
9325            finding.severity = if i == 9 {
9326                crate::verdict::Severity::Major
9327            } else {
9328                crate::verdict::Severity::Minor
9329            };
9330            finding.title = long_title.clone();
9331            finding.detail = long_detail.clone();
9332            state.reviews[0].reviews[0].findings.push(finding);
9333        }
9334        state.reviews[0].fix = Some(crate::run::FixRecord {
9335            agent: "fixer".into(),
9336            addressed: vec!["R1-1-9".into()],
9337            rejected: vec![crate::verdict::Rejection {
9338                id: "R1-1-10".into(),
9339                why: long_reason.clone(),
9340            }],
9341            notes: long_detail.clone(),
9342            committed: false,
9343            failed: None,
9344            duration_ms: 0,
9345            continuation: None,
9346        });
9347        assert_eq!(
9348            approval_reasons(&state),
9349            [
9350                ApprovalReason::OpenBlockingFindings,
9351                ApprovalReason::FinalReject
9352            ]
9353        );
9354        let excerpt = approval_excerpt(&long_reason, 300);
9355        assert_eq!(excerpt.chars().count(), 300);
9356        assert!(excerpt.ends_with('…'));
9357        let boundary = "拒".repeat(300);
9358        assert_eq!(approval_excerpt(&boundary, 300), boundary);
9359        for language in ["en", "ja"] {
9360            state.config.graph.language = language.into();
9361            for revote in [
9362                None,
9363                Some(crate::verdict::ReviewVote::Reject),
9364                Some(crate::verdict::ReviewVote::Approve),
9365            ] {
9366                state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Reject);
9367                state.reviews[0].reconsideration.clear();
9368                if let Some(vote) = revote {
9369                    state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Approve);
9370                    state.reviews[0]
9371                        .reconsideration
9372                        .push(crate::run::ReviewRevoteRecord {
9373                            reviewer: 1,
9374                            agent: "alpha".into(),
9375                            vote: Some(vote),
9376                            reason: long_reason.clone(),
9377                            failed: None,
9378                        });
9379                }
9380                let evidence = approval_evidence(&state);
9381                let final_vote = revote.unwrap_or(crate::verdict::ReviewVote::Reject);
9382                assert!(evidence.contains(&format!("#1 (alpha): {}", final_vote.label())));
9383                assert!(approval_reasons(&state).contains(&ApprovalReason::OpenBlockingFindings));
9384                assert_eq!(
9385                    approval_reasons(&state).contains(&ApprovalReason::FinalReject),
9386                    final_vote == crate::verdict::ReviewVote::Reject
9387                );
9388                assert!(evidence.contains(&excerpt));
9389                assert!(evidence.contains("[R1-1-8] minor"));
9390                assert!(evidence.contains("[R1-1-9] major"));
9391                assert!(evidence.contains("[R1-1-10] minor"));
9392                for tail in ["REASON_TAIL", "DETAIL_TAIL", "TITLE_TAIL"] {
9393                    assert!(!evidence.contains(tail));
9394                }
9395                assert!(evidence.contains(if language == "ja" {
9396                    "採用申告(解決未確認)"
9397                } else {
9398                    "claimed addressed (resolution unconfirmed)"
9399                }));
9400                assert!(evidence.contains(if language == "ja" {
9401                    "不採用理由"
9402                } else {
9403                    "declined"
9404                }));
9405                let major_evidence = evidence
9406                    .split("[R1-1-9] major")
9407                    .nth(1)
9408                    .unwrap()
9409                    .split("[R1-1-10]")
9410                    .next()
9411                    .unwrap();
9412                assert!(major_evidence.contains(if language == "ja" {
9413                    "採用申告(解決未確認)"
9414                } else {
9415                    "claimed addressed (resolution unconfirmed)"
9416                }));
9417                let last_evidence = evidence.split("[R1-1-10] minor").nth(1).unwrap();
9418                assert!(last_evidence.contains(if language == "ja" {
9419                    "不採用理由"
9420                } else {
9421                    "declined"
9422                }));
9423                let html = approval_panel(&state, &green_pr(), "", "", &[], "subject");
9424                assert!(html.contains(&esc(&evidence)));
9425                assert_eq!(
9426                    approval_gate(&mut state, &green_pr(), "subject", None, "abc")
9427                        .await
9428                        .unwrap(),
9429                    ApprovalGate::Pending
9430                );
9431                let id = &state.land_approval.take().unwrap().question;
9432                let q = ask::Questions::open().get(id).unwrap();
9433                assert!(q.detail.starts_with(&evidence));
9434            }
9435            state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Reject);
9436        }
9437    }
9438
9439    #[test]
9440    fn merge_repair_choice_covers_major_only_and_reject_only_without_contested_and() {
9441        for (major, reject) in [(true, false), (false, true), (true, true)] {
9442            let state = repair_state(major, reject);
9443            assert!(repair_available(&state));
9444            assert_eq!(&approval_choices(&state)[..3], [APPROVE, HOLD, REPAIR]);
9445        }
9446        assert!(!repair_available(&repair_state(false, false)));
9447        let mut clean = repair_state(true, false);
9448        clean.reviews[0].clean = true;
9449        assert_eq!(&approval_choices(&clean)[..3], [APPROVE, HOLD, REPAIR]);
9450        assert_eq!(approval(Some(REPAIR)), Approval::Repair);
9451    }
9452
9453    #[tokio::test]
9454    async fn merge_repair_upgrades_legacy_questions_and_snapshots_exact_evidence_once() {
9455        let mut state = repair_state(true, false);
9456        let pr = green_pr();
9457        approval_gate(&mut state, &pr, "feat: x", None, "abc")
9458            .await
9459            .unwrap();
9460        let store = ask::Questions::open();
9461        let id = state.land_approval.as_ref().unwrap().question.clone();
9462        // Simulate an unanswered two-choice question created by an older build.
9463        store
9464            .update(&id, |q| {
9465                q.choices = vec![APPROVE.into(), HOLD.into()];
9466                Ok(())
9467            })
9468            .unwrap();
9469        let upgraded = store.get(&id).unwrap();
9470        assert_eq!(upgraded.choices, approval_choices(&state));
9471        assert!(!upgraded.actions.contains_key(HOLD));
9472        assert_eq!(store.get(&id).unwrap().choices, upgraded.choices);
9473        assert!(
9474            store
9475                .list()
9476                .iter()
9477                .any(|q| q.id == id && q.choices == upgraded.choices)
9478        );
9479        assert!(
9480            crate::prompt::chat_consult(&upgraded).contains("--reply 'fix findings and re-review'")
9481        );
9482        assert!(deputy_brief(&upgraded, Some(&state)).contains("never approves a merge"));
9483        store
9484            .update(&id, |q| q.answer(ask::Answer::Choice(REPAIR.into())))
9485            .unwrap();
9486        // An earlier build may have recorded the repair answer and stopped
9487        // before any driver consumed it. Reconcile that durable decision too.
9488        store
9489            .update(&id, |q| {
9490                q.actions.clear();
9491                Ok(())
9492            })
9493            .unwrap();
9494        assert_eq!(
9495            store.get(&id).unwrap().chosen_action(),
9496            Some(&ask::ChoiceAction::Resume {
9497                run: state.id.clone()
9498            })
9499        );
9500        let binding = state.land_approval.clone();
9501        assert_eq!(
9502            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9503                .await
9504                .unwrap(),
9505            ApprovalGate::Repair
9506        );
9507        assert!(state.land_approval.is_none());
9508        assert_eq!(state.merge_repairs.len(), 1);
9509        let request = &state.merge_repairs[0];
9510        assert_eq!(request.question, id);
9511        assert_eq!(request.head, "abc");
9512        assert_eq!(request.pr, pr.url);
9513        assert_eq!(
9514            request.reviews[0].reviews[0].summary,
9515            "precise rejection reason"
9516        );
9517        assert_eq!(request.reviews[0].reviews[0].findings[0].id, "R3-1-1");
9518        assert_eq!(
9519            request.reviews[0].reviews[0].findings[0].detail,
9520            state.reviews[0].reviews[0].findings[0].detail
9521        );
9522        // A repeated consumption of the same answer never dispatches another repair.
9523        state.land_approval = binding;
9524        assert_eq!(
9525            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9526                .await
9527                .unwrap(),
9528            ApprovalGate::Repair
9529        );
9530        assert_eq!(state.merge_repairs.len(), 1);
9531        state.land_approval = None;
9532        state.config.graph.land_approval = false;
9533        state.config.graph.hold_contested_merge = false;
9534        state.reviews.clear();
9535        assert_eq!(approval_reasons(&state), [ApprovalReason::AfterRepair]);
9536        assert_eq!(
9537            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9538                .await
9539                .unwrap(),
9540            ApprovalGate::Pending
9541        );
9542        let fresh_id = &state.land_approval.as_ref().unwrap().question;
9543        assert_ne!(fresh_id, &id);
9544        let fresh = store.get(fresh_id).unwrap();
9545        assert!(
9546            fresh
9547                .detail
9548                .contains("fresh owner approval after merge repair")
9549        );
9550        assert!(fresh.detail.contains("No review recorded"));
9551        assert!(!fresh.detail.contains("precise rejection reason"));
9552    }
9553
9554    #[tokio::test]
9555    async fn merge_repair_answer_never_merges_and_hold_never_requests_repair() {
9556        for choice in [REPAIR, HOLD] {
9557            let mut state = repair_state(false, true);
9558            let observed = seen("abc", Checks::Green, "CLEAN", false);
9559            approval_gate(&mut state, &observed.pr, "feat: x", None, "abc")
9560                .await
9561                .unwrap();
9562            let id = state.land_approval.as_ref().unwrap().question.clone();
9563            ask::Questions::open()
9564                .update(&id, |q| q.answer(ask::Answer::Choice(choice.into())))
9565                .unwrap();
9566            let forge = Scripted::new(vec![observed], vec![(true, "")]);
9567            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
9568                .await
9569                .unwrap();
9570            assert!(
9571                forge
9572                    .argvs()
9573                    .iter()
9574                    .all(|a| a.iter().any(|s| s == "--disable-auto"))
9575            );
9576            assert!(!forge.calls().contains(&"fix"));
9577            assert_eq!(state.merge_repairs.len(), usize::from(choice == REPAIR));
9578            assert_ne!(state.status, RunStatus::Merged);
9579        }
9580    }
9581
9582    #[test]
9583    fn only_the_merge_choice_merges_and_silence_holds() {
9584        let table = [
9585            (None, Approval::Hold),
9586            (Some("merge"), Approval::Merge),
9587            (Some(" merge\n"), Approval::Merge),
9588            (Some("hold"), Approval::Hold),
9589            (Some(""), Approval::Hold),
9590            (Some("yes"), Approval::Hold),
9591        ];
9592        for (answer, want) in table {
9593            assert_eq!(
9594                approval(answer),
9595                want,
9596                "answer {answer:?} must resolve to {want:?}"
9597            );
9598        }
9599    }
9600
9601    #[tokio::test]
9602    async fn a_first_visit_to_the_merge_gate_files_a_question_and_returns_pending_at_once() {
9603        let mut state = landing_state();
9604        state.config.graph.land_approval = true;
9605        let pr = green_pr();
9606
9607        let gate = approval_gate(&mut state, &pr, "feat: x", None, "abc")
9608            .await
9609            .unwrap();
9610        assert_eq!(gate, ApprovalGate::Pending, "nobody has answered yet");
9611        assert!(
9612            !state.parked,
9613            "approval_gate itself never sets `parked`; only its caller does"
9614        );
9615
9616        let store = ask::Questions::open();
9617        let filed: Vec<_> = store
9618            .list()
9619            .into_iter()
9620            .filter(|q| q.run == state.id)
9621            .collect();
9622        assert_eq!(filed.len(), 1, "exactly one question is filed");
9623        assert_eq!(filed[0].node, APPROVAL_NODE);
9624        assert_eq!(filed[0].choices, approval_choices(&state));
9625        assert!(filed[0].status.open());
9626
9627        // A second visit - standing in for a resumed run whose slot the
9628        // daemon handed to something else while nobody had answered - must
9629        // find the same question rather than filing a second one.
9630        let again = approval_gate(&mut state, &pr, "feat: x", None, "abc")
9631            .await
9632            .unwrap();
9633        assert_eq!(again, ApprovalGate::Pending);
9634        let still_one = store
9635            .list()
9636            .into_iter()
9637            .filter(|q| q.run == state.id)
9638            .count();
9639        assert_eq!(
9640            still_one, 1,
9641            "asking twice must not double-file the question"
9642        );
9643    }
9644
9645    #[tokio::test]
9646    async fn approving_the_existing_question_is_read_back_as_approved() {
9647        crate::run::pin_test_home();
9648        let mut state = run_state();
9649        state.config.graph.land_approval = true;
9650        let pr = green_pr();
9651        assert_eq!(
9652            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9653                .await
9654                .unwrap(),
9655            ApprovalGate::Pending
9656        );
9657
9658        let store = ask::Questions::open();
9659        let mut q = store
9660            .list()
9661            .into_iter()
9662            .find(|q| q.run == state.id)
9663            .expect("filed above");
9664        let talks = crate::talk::Talks::open();
9665        let cfg = crate::config::Config {
9666            agents: vec![crate::config::AgentSpec {
9667                id: "mock".into(),
9668                kind: crate::config::AgentKind::Command,
9669                model: None,
9670                command: vec!["true".into()],
9671                extra_args: Vec::new(),
9672                env: Default::default(),
9673                prompt_delivery: None,
9674                max_turn_secs: None,
9675            }],
9676            ..crate::config::Config::default()
9677        };
9678        let mut talk = crate::talk::begin(&talks, &cfg, state.repo.clone(), Some("mock")).unwrap();
9679        crate::consult::begin(&store, &talks, &q, &talk).unwrap();
9680        crate::talk::drain(&mut talk, &talks).unwrap();
9681        assert_eq!(
9682            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9683                .await
9684                .unwrap(),
9685            ApprovalGate::Pending,
9686            "consultation cannot approve or hold the merge"
9687        );
9688        q = store.get(&q.id).unwrap();
9689        assert!(q.answer.is_none());
9690        // The owner's merge answer (from the chat or the card) is the approval.
9691        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
9692        store.put(&mut q).unwrap();
9693
9694        assert_eq!(
9695            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9696                .await
9697                .unwrap(),
9698            ApprovalGate::Approved
9699        );
9700    }
9701
9702    #[tokio::test]
9703    async fn legacy_hold_actions_are_removed_on_get_and_list_before_answering() {
9704        crate::run::pin_test_home();
9705        let store = ask::Questions::open();
9706        for via_list in [false, true] {
9707            let mut state = repair_state(false, true);
9708            let pr = green_pr();
9709            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9710                .await
9711                .unwrap();
9712            let id = state.land_approval.as_ref().unwrap().question.clone();
9713            store
9714                .update(&id, |q| {
9715                    q.actions.insert(
9716                        HOLD.to_owned(),
9717                        ask::ChoiceAction::Resume {
9718                            run: state.id.clone(),
9719                        },
9720                    );
9721                    Ok(())
9722                })
9723                .unwrap();
9724            let q = if via_list {
9725                store.list().into_iter().find(|q| q.id == id).unwrap()
9726            } else {
9727                store.get(&id).unwrap()
9728            };
9729            assert!(!q.actions.contains_key(HOLD));
9730            store
9731                .update(&id, |q| {
9732                    // Check the persisted migration, without another read upgrade.
9733                    assert!(!q.actions.contains_key(HOLD));
9734                    assert!(!upgrade_repair_choice(q, &state));
9735                    q.answer(ask::Answer::Choice(HOLD.to_owned()))
9736                })
9737                .unwrap();
9738            assert!(store.get(&id).unwrap().chosen_action().is_none());
9739            assert_eq!(
9740                approval_gate(&mut state, &pr, "feat: x", None, "abc")
9741                    .await
9742                    .unwrap(),
9743                ApprovalGate::Held
9744            );
9745        }
9746    }
9747
9748    #[tokio::test]
9749    async fn explicit_hold_stays_held_but_expired_approval_is_reasked() {
9750        crate::run::pin_test_home();
9751        let store = ask::Questions::open();
9752
9753        let mut held_state = run_state();
9754        held_state.config.graph.land_approval = true;
9755        let pr = green_pr();
9756        approval_gate(&mut held_state, &pr, "feat: x", None, "abc")
9757            .await
9758            .unwrap();
9759        let mut q = store
9760            .list()
9761            .into_iter()
9762            .find(|q| q.run == held_state.id)
9763            .expect("filed above");
9764        q.answer(ask::Answer::Choice(HOLD.to_owned())).unwrap();
9765        store.put(&mut q).unwrap();
9766        assert_eq!(
9767            approval_gate(&mut held_state, &pr, "feat: x", None, "abc")
9768                .await
9769                .unwrap(),
9770            ApprovalGate::Held
9771        );
9772
9773        let mut abandoned_state = run_state();
9774        abandoned_state.config.graph.land_approval = true;
9775        approval_gate(&mut abandoned_state, &pr, "feat: x", None, "abc")
9776            .await
9777            .unwrap();
9778        let mut q = store
9779            .list()
9780            .into_iter()
9781            .find(|q| q.run == abandoned_state.id)
9782            .expect("filed above");
9783        q.abandon("no answer within the timeout");
9784        store.put(&mut q).unwrap();
9785        assert_eq!(
9786            approval_gate(&mut abandoned_state, &pr, "feat: x", None, "abc")
9787                .await
9788                .unwrap(),
9789            ApprovalGate::Pending,
9790            "an expired approval must ask again without merging"
9791        );
9792        assert_eq!(
9793            store.get(&q.id).unwrap().status,
9794            ask::QuestionStatus::Abandoned
9795        );
9796        assert_ne!(
9797            abandoned_state.land_approval.as_ref().unwrap().question,
9798            q.id
9799        );
9800    }
9801
9802    fn contested() -> ContestedHandoff {
9803        let finding = |id: &str, n: u32| crate::verdict::Finding {
9804            id: id.to_owned(),
9805            severity: crate::verdict::Severity::Major,
9806            file: Some("src/a.rs".to_owned()),
9807            line: Some(n),
9808            title: format!("problem {id}"),
9809            detail: String::new(),
9810        };
9811        ContestedHandoff {
9812            findings: (1..=7).map(|n| finding(&format!("R3-1-{n}"), n)).collect(),
9813            rejecters: vec![(1, "alpha".to_owned())],
9814        }
9815    }
9816
9817    #[test]
9818    fn the_contested_record_is_asked_about_unless_the_switch_is_off() {
9819        let mut state = run_state();
9820        assert!(contested_to_ask(&state).is_none(), "nothing recorded");
9821        state.contested_handoff = Some(contested());
9822        assert!(contested_to_ask(&state).is_some());
9823        state.config.graph.hold_contested_merge = false;
9824        assert!(
9825            contested_to_ask(&state).is_none(),
9826            "the switch restores today"
9827        );
9828    }
9829
9830    #[test]
9831    fn the_deputy_brief_carries_the_pr_the_findings_and_names_what_is_missing() {
9832        let q = ask::Question::new(
9833            "run-1".to_owned(),
9834            APPROVAL_NODE.to_owned(),
9835            "land".to_owned(),
9836            "Merge?".to_owned(),
9837            String::new(),
9838            vec![APPROVE.to_owned(), HOLD.to_owned()],
9839        );
9840        let none = deputy_brief(&q, None);
9841        assert!(none.contains("could not be read"), "{none}");
9842        assert!(none.contains("Silence is a hold"), "{none}");
9843
9844        let mut state = run_state();
9845        state.pr = Some(crate::run::PrRecord {
9846            url: "https://example.test/pull/7".to_owned(),
9847            number: 7,
9848            state: "open".to_owned(),
9849            checks: "green".to_owned(),
9850            round: 0,
9851            rounds: 3,
9852            red_at_merge: Vec::new(),
9853        });
9854        state.contested_handoff = Some(contested());
9855        let b = deputy_brief(&q, Some(&state));
9856        assert!(b.contains("https://example.test/pull/7"), "{b}");
9857        assert!(b.contains("not recorded in this legacy question"), "{b}");
9858        assert!(!b.contains("This question was filed although"));
9859        state.contested_handoff = None;
9860        assert!(deputy_brief(&q, Some(&state)).contains("not recorded in this legacy question"));
9861    }
9862
9863    #[test]
9864    fn the_contested_question_names_the_pr_the_findings_and_the_rejecter() {
9865        for lang in ["en", "ja"] {
9866            let mut cfg = crate::config::Config::default();
9867            cfg.graph.language = lang.to_owned();
9868            let w = words(&cfg.graph.language);
9869            let text = w.approval_detail(
9870                "https://github.com/yukimemi/magi/pull/42",
9871                "main",
9872                "feat: x",
9873                Some(&contested()),
9874            );
9875            assert!(text.contains("pull/42"), "{text}");
9876            assert!(
9877                text.contains("R3-1-1 major src/a.rs:1: problem R3-1-1"),
9878                "{text}"
9879            );
9880            assert!(text.contains("R3-1-5"), "{text}");
9881            assert!(!text.contains("R3-1-6"), "the list is capped: {text}");
9882            assert!(text.contains("2"), "the rest are counted: {text}");
9883            assert!(text.contains("#1 (alpha)"), "{text}");
9884        }
9885        let plain = words("en").approval_detail("u", "main", "s", None);
9886        assert!(!plain.contains("reject"), "{plain}");
9887    }
9888
9889    #[tokio::test]
9890    async fn a_contested_question_is_filed_once_and_a_resume_finds_the_same_one() {
9891        crate::run::pin_test_home();
9892        let mut state = run_state();
9893        state.config.graph.land_approval = false;
9894        state.contested_handoff = Some(contested());
9895        let pr = green_pr();
9896        let c = contested_to_ask(&state);
9897        assert_eq!(
9898            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
9899                .await
9900                .unwrap(),
9901            ApprovalGate::Pending,
9902            "silence is a hold"
9903        );
9904        let store = ask::Questions::open();
9905        let filed: Vec<_> = store
9906            .list()
9907            .into_iter()
9908            .filter(|q| q.run == state.id)
9909            .collect();
9910        assert_eq!(filed.len(), 1);
9911        assert!(filed[0].detail.contains("R3-1-1"), "{}", filed[0].detail);
9912
9913        assert_eq!(
9914            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
9915                .await
9916                .unwrap(),
9917            ApprovalGate::Pending
9918        );
9919        let mut q = store
9920            .list()
9921            .into_iter()
9922            .find(|q| q.run == state.id)
9923            .unwrap();
9924        assert_eq!(q.id, filed[0].id, "the same question after a resume");
9925        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
9926        store.put(&mut q).unwrap();
9927        assert_eq!(
9928            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
9929                .await
9930                .unwrap(),
9931            ApprovalGate::Approved
9932        );
9933    }
9934
9935    #[test]
9936    fn the_diffstat_table_is_ordered_by_churn_with_binaries_last() {
9937        let rows = parse_numstat(NUMSTAT);
9938        assert_eq!(
9939            rows.iter().map(|r| r.path.as_str()).collect::<Vec<_>>(),
9940            ["src/web.rs", "src/land.rs", "assets/logo.png"]
9941        );
9942        assert_eq!(rows[2].added, None, "a binary file has no line counts");
9943    }
9944    #[test]
9945    fn the_approval_speaks_the_language_the_repository_is_configured_for() {
9946        // Reported from a real run: the merge question arrived in English on a
9947        // repository with `language = "ja"`. magi's own strings have to follow
9948        // that setting too - "it is a literal in Rust" is not an answer.
9949        let mut state = run_state();
9950        state.config.graph.language = "ja".to_owned();
9951        let pr = green_pr();
9952        let commits = ["c1".to_owned()];
9953
9954        let ja = approval_panel(&state, &pr, "3\t1\tsrc/a.rs", "+ x", &commits, "feat: x");
9955        assert!(ja.contains("lang=\"ja\""), "the document must declare it");
9956        assert!(ja.contains("squash されるコミット"), "{ja}");
9957        assert!(ja.contains("レビューコメント"), "{ja}");
9958        assert!(ja.contains("差分"), "{ja}");
9959        assert!(
9960            !ja.contains("Commits being squashed"),
9961            "no English left over"
9962        );
9963
9964        let w = words("ja");
9965        assert!(w.approval_summary(17, "feat: x").contains("マージ"));
9966        assert!(
9967            w.approval_detail("http://x/1", "main", "feat: x", None)
9968                .contains("パネル")
9969        );
9970
9971        // The evidence itself is language-neutral and must survive either way.
9972        assert!(ja.contains("src/a.rs"), "the diffstat is not prose");
9973        assert!(ja.contains("feat: x"), "nor is the merge subject");
9974
9975        // English stays the default, and a language magi cannot check falls
9976        // back to it rather than shipping a guess.
9977        state.config.graph.language = "en".to_owned();
9978        let en = approval_panel(&state, &pr, "3\t1\tsrc/a.rs", "+ x", &commits, "feat: x");
9979        assert!(en.contains("Commits being squashed"), "{en}");
9980        assert_eq!(words("Klingon").html_lang, "en");
9981    }
9982
9983    /// A `gh pr list` result naming exactly one pull request whose base and
9984    /// merge time both fit the run is exactly the case
9985    /// [`find_external_merge`] exists to act on.
9986    #[test]
9987    fn pick_open_pr_classifies_by_count_and_base() {
9988        let one = r#"[{"number":58,"url":"https://x/pull/58","title":"t","baseRefName":"main"}]"#;
9989        assert_eq!(
9990            pick_open_pr(one, "main").unwrap(),
9991            OpenPr::One {
9992                url: "https://x/pull/58".into(),
9993                title: "t".into()
9994            }
9995        );
9996        assert_eq!(pick_open_pr("[]", "main").unwrap(), OpenPr::None);
9997        assert_eq!(pick_open_pr(one, "dev").unwrap(), OpenPr::None);
9998        let two = r#"[{"number":1,"url":"u1","title":"","baseRefName":"main"},
9999                     {"number":2,"url":"u2","title":"","baseRefName":"main"}]"#;
10000        assert_eq!(
10001            pick_open_pr(two, "main").unwrap(),
10002            OpenPr::Many(vec!["u1".into(), "u2".into()])
10003        );
10004        // A fork's same-named branch is not a pull request for this head.
10005        let fork = r#"[{"url":"f","baseRefName":"main","isCrossRepository":true}]"#;
10006        assert_eq!(pick_open_pr(fork, "main").unwrap(), OpenPr::None);
10007        assert!(pick_open_pr("not json", "main").is_err());
10008        // An incomplete record is an error, never "nothing open".
10009        assert!(pick_open_pr(r#"[{"url":"u","title":"t"}]"#, "main").is_err());
10010        assert!(pick_open_pr(r#"[{"title":"t","baseRefName":"main"}]"#, "main").is_err());
10011    }
10012
10013    #[test]
10014    fn pick_merged_pr_picks_the_unique_match() {
10015        let json = r#"[
10016            {"url": "https://github.com/o/r/pull/42", "number": 42,
10017             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "main"}
10018        ]"#;
10019        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10020        let found = pick_merged_pr(json, "main", created_at)
10021            .expect("valid json")
10022            .expect("one unambiguous match");
10023        assert_eq!(found.url, "https://github.com/o/r/pull/42");
10024        assert_eq!(found.number, 42);
10025    }
10026
10027    /// Two candidates surviving the filter is exactly as uninformative as
10028    /// zero — a branch name can be reused across runs — so neither is
10029    /// preferred over the other and nothing is recorded automatically.
10030    #[test]
10031    fn pick_merged_pr_refuses_when_more_than_one_candidate_survives() {
10032        let json = r#"[
10033            {"url": "https://github.com/o/r/pull/42", "number": 42,
10034             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "main"},
10035            {"url": "https://github.com/o/r/pull/43", "number": 43,
10036             "mergedAt": "2026-09-21T10:00:00Z", "baseRefName": "main"}
10037        ]"#;
10038        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10039        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
10040        let error = pick_merged_pr_with(json, "main", created_at, true).unwrap_err();
10041        assert!(error.to_string().contains("ambiguous"), "{error:#}");
10042    }
10043
10044    /// A pull request that targets a different base branch cannot be this
10045    /// run's, whatever its head branch is named — a reused branch name from
10046    /// an unrelated task must not be recorded as this run's merge.
10047    #[test]
10048    fn pick_merged_pr_ignores_a_different_base_branch() {
10049        let json = r#"[
10050            {"url": "https://github.com/o/r/pull/42", "number": 42,
10051             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "release"}
10052        ]"#;
10053        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10054        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
10055    }
10056
10057    /// A pull request merged before this run was even created cannot be this
10058    /// run's winner, no matter how its head branch is spelled.
10059    #[test]
10060    fn pick_merged_pr_ignores_a_merge_that_predates_the_run() {
10061        let json = r#"[
10062            {"url": "https://github.com/o/r/pull/42", "number": 42,
10063             "mergedAt": "2026-09-18T10:00:00Z", "baseRefName": "main"}
10064        ]"#;
10065        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
10066        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
10067    }
10068
10069    #[test]
10070    fn slug_of_pr_url_reads_host_owner_and_repo() {
10071        assert_eq!(
10072            slug_of_pr_url("https://github.com/yukimemi/shun/pull/272").as_deref(),
10073            Some("github.com/yukimemi/shun")
10074        );
10075    }
10076
10077    #[test]
10078    fn slug_of_pr_url_refuses_a_url_with_no_pull_segment() {
10079        assert_eq!(slug_of_pr_url("https://github.com/yukimemi/shun"), None);
10080        assert_eq!(slug_of_pr_url("not a url at all"), None);
10081        assert_eq!(slug_of_pr_url("https://github.com"), None);
10082    }
10083
10084    #[test]
10085    fn slug_of_repo_url_reads_host_owner_and_repo() {
10086        assert_eq!(
10087            slug_of_repo_url("https://github.com/yukimemi/magi").as_deref(),
10088            Some("github.com/yukimemi/magi")
10089        );
10090        assert_eq!(slug_of_repo_url("https://github.com"), None);
10091    }
10092
10093    #[test]
10094    fn ensure_same_repo_accepts_a_matching_slug_regardless_of_case() {
10095        ensure_same_repo("github.com/yukimemi/magi", "GitHub.Com/YukiMemi/Magi")
10096            .expect("same repo, different case");
10097    }
10098
10099    /// The shun/8c75 incident: an id-less `--merged` picked this repository's
10100    /// own in-progress run and rewrote its status from a pull request in a
10101    /// completely different repository. This is the guard that must catch
10102    /// that even when an explicit (but wrong) id is given.
10103    #[test]
10104    fn ensure_same_repo_refuses_a_different_repo() {
10105        let err =
10106            ensure_same_repo("github.com/yukimemi/magi", "github.com/yukimemi/shun").unwrap_err();
10107        let msg = format!("{err:#}");
10108        assert!(msg.contains("github.com/yukimemi/magi"), "{msg}");
10109        assert!(msg.contains("github.com/yukimemi/shun"), "{msg}");
10110    }
10111
10112    /// Same owner/repo on two different forge hosts (a GitHub Enterprise
10113    /// instance mirroring a `github.com` repository's name, say) must not be
10114    /// treated as the same repository just because the trailing path
10115    /// matches.
10116    #[test]
10117    fn ensure_same_repo_refuses_the_same_slug_on_a_different_host() {
10118        let err = ensure_same_repo(
10119            "github.com/yukimemi/magi",
10120            "github.example.com/yukimemi/magi",
10121        )
10122        .unwrap_err();
10123        let msg = format!("{err:#}");
10124        assert!(msg.contains("github.com/yukimemi/magi"), "{msg}");
10125        assert!(msg.contains("github.example.com/yukimemi/magi"), "{msg}");
10126    }
10127
10128    /// No winner decided yet means there is no branch to ask GitHub about at
10129    /// all — `find_external_merge` must return `None` without ever spawning
10130    /// `gh`, which this proves by never providing a real repository to spawn
10131    /// it in.
10132    #[tokio::test]
10133    async fn find_external_merge_returns_none_without_a_winner() {
10134        let state = RunState::new(
10135            PathBuf::from("/no/such/repo"),
10136            "main".to_owned(),
10137            "0000000000000000000000000000000000000000".to_owned(),
10138            "irrelevant".to_owned(),
10139            crate::config::Config::default(),
10140        );
10141        assert_eq!(find_external_merge(&state).await.unwrap(), None);
10142    }
10143
10144    fn pr_run(home: &Path, id: &str, repo: &str, status: RunStatus, url: &str, state: &str) {
10145        let mut run = RunState::new(
10146            PathBuf::from(repo),
10147            "main".to_owned(),
10148            "abcdef1234".to_owned(),
10149            "x".to_owned(),
10150            crate::config::Config::default(),
10151        );
10152        run.id = id.to_owned();
10153        run.status = status;
10154        run.driver_exited = true;
10155        run.pr = Some(crate::run::PrRecord {
10156            number: url.rsplit('/').next().unwrap().parse().unwrap(),
10157            url: url.to_owned(),
10158            state: state.to_owned(),
10159            checks: "red".to_owned(),
10160            round: 0,
10161            rounds: 2,
10162            red_at_merge: Vec::new(),
10163        });
10164        run.save_under(home).unwrap();
10165    }
10166
10167    fn recorded(home: &Path, id: &str) -> String {
10168        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
10169        serde_json::from_str::<RunState>(&body)
10170            .unwrap()
10171            .pr
10172            .unwrap()
10173            .state
10174    }
10175
10176    const PR: &str = "https://github.com/o/r/pull/7";
10177
10178    #[test]
10179    fn write_through_updates_predecessors_and_siblings_only() {
10180        let tmp = tempfile::tempdir().unwrap();
10181        let h = tmp.path();
10182        pr_run(
10183            h,
10184            "20261004-100000-aaaa",
10185            "/repo/r",
10186            RunStatus::Superseded,
10187            PR,
10188            "open",
10189        );
10190        pr_run(
10191            h,
10192            "20261004-100100-bbbb",
10193            "/repo/r",
10194            RunStatus::Blocked,
10195            PR,
10196            "open",
10197        );
10198        // Not terminal: a driver may be writing it.
10199        pr_run(
10200            h,
10201            "20261004-100200-cccc",
10202            "/repo/r",
10203            RunStatus::Landing,
10204            PR,
10205            "open",
10206        );
10207        // Another repository's pull request with the same number.
10208        pr_run(
10209            h,
10210            "20261004-100300-dddd",
10211            "/repo/other",
10212            RunStatus::Blocked,
10213            "https://github.com/o/other/pull/7",
10214            "open",
10215        );
10216        // A different pull request of the same repository.
10217        pr_run(
10218            h,
10219            "20261004-100400-eeee",
10220            "/repo/r",
10221            RunStatus::Blocked,
10222            "https://github.com/o/r/pull/8",
10223            "open",
10224        );
10225        pr_run(
10226            h,
10227            "20261004-100500-ffff",
10228            "/repo/r",
10229            RunStatus::Merged,
10230            PR,
10231            "open",
10232        );
10233        let source = RunState::load_under("20261004-100500-ffff", h).unwrap();
10234
10235        assert_eq!(
10236            write_pr_state_through_in(h, &source, PrLifecycle::Merged),
10237            2
10238        );
10239        assert_eq!(recorded(h, "20261004-100000-aaaa"), "merged");
10240        assert_eq!(recorded(h, "20261004-100100-bbbb"), "merged");
10241        assert_eq!(recorded(h, "20261004-100200-cccc"), "open");
10242        assert_eq!(recorded(h, "20261004-100300-dddd"), "open");
10243        assert_eq!(recorded(h, "20261004-100400-eeee"), "open");
10244        // The source's own record is the caller's to write.
10245        assert_eq!(recorded(h, "20261004-100500-ffff"), "open");
10246        // Idempotent.
10247        assert_eq!(
10248            write_pr_state_through_in(h, &source, PrLifecycle::Merged),
10249            0
10250        );
10251        let hit = RunState::load_under("20261004-100000-aaaa", h).unwrap();
10252        assert!(hit.events.iter().any(|e| e.message.contains("merged")));
10253    }
10254
10255    #[test]
10256    fn lifecycle_updates_preserve_live_and_unknown_terminal_drivers() {
10257        let home = tempfile::tempdir().unwrap();
10258        let live_id = "20261004-100000-aaaa";
10259        let unknown_id = "20261004-100100-bbbb";
10260        for id in [live_id, unknown_id] {
10261            pr_run(home.path(), id, "repo", RunStatus::Ready, PR, "open");
10262            let mut s = RunState::load_under(id, home.path()).unwrap();
10263            s.driver_exited = false;
10264            // Model legacy driver evidence, not a newly reserved unstarted run.
10265            s.driver_claimed = None;
10266            if id == live_id {
10267                s.driver_pid = Some(std::process::id());
10268                s.driver_started_at = crate::proc::process_started_at(std::process::id());
10269            }
10270            s.save_under(home.path()).unwrap();
10271            if id == unknown_id {
10272                assert_eq!(
10273                    s.liveness_under(home.path(), false),
10274                    crate::run::Liveness::Unknown
10275                );
10276            }
10277        }
10278        let known = BTreeMap::from([(PR.to_owned(), PrLifecycle::Merged)]);
10279        assert_eq!(apply_pr_states(home.path(), &known), 0);
10280        for id in [live_id, unknown_id] {
10281            assert_eq!(recorded(home.path(), id), "open");
10282        }
10283    }
10284
10285    #[test]
10286    fn repair_rewrites_merged_and_closed_and_leaves_open_and_unknown() {
10287        let tmp = tempfile::tempdir().unwrap();
10288        let h = tmp.path();
10289        let url = |n: u32| format!("https://github.com/o/r/pull/{n}");
10290        pr_run(
10291            h,
10292            "20261004-100000-aaaa",
10293            "/repo/r",
10294            RunStatus::Superseded,
10295            &url(1),
10296            "open",
10297        );
10298        pr_run(
10299            h,
10300            "20261004-100100-bbbb",
10301            "/repo/r",
10302            RunStatus::Blocked,
10303            &url(2),
10304            "open",
10305        );
10306        pr_run(
10307            h,
10308            "20261004-100200-cccc",
10309            "/repo/r",
10310            RunStatus::Ready,
10311            &url(3),
10312            "open",
10313        );
10314        pr_run(
10315            h,
10316            "20261004-100300-dddd",
10317            "/repo/r",
10318            RunStatus::Ready,
10319            &url(4),
10320            "open",
10321        );
10322        pr_run(
10323            h,
10324            "20261004-100400-eeee",
10325            "/repo/r",
10326            RunStatus::Implementing,
10327            &url(1),
10328            "open",
10329        );
10330        assert_eq!(stale_open_prs(h).len(), 4);
10331
10332        let mut known = BTreeMap::new();
10333        known.insert(url(1), PrLifecycle::Merged);
10334        known.insert(url(2), PrLifecycle::Closed);
10335        known.insert(url(3), PrLifecycle::Open);
10336        // #4: the forge could not be read, so it has no answer.
10337        assert_eq!(apply_pr_states(h, &known), 2);
10338        assert_eq!(recorded(h, "20261004-100000-aaaa"), "merged");
10339        assert_eq!(recorded(h, "20261004-100100-bbbb"), "closed");
10340        assert_eq!(recorded(h, "20261004-100200-cccc"), "open");
10341        assert_eq!(recorded(h, "20261004-100300-dddd"), "open");
10342        assert_eq!(recorded(h, "20261004-100400-eeee"), "open");
10343        assert_eq!(apply_pr_states(h, &known), 0);
10344    }
10345
10346    // --- the land loop against a scripted forge -------------------------
10347
10348    use std::collections::VecDeque;
10349    use std::sync::Mutex;
10350
10351    /// Answers views from a script (the last one repeats), merges from a
10352    /// queue, and records every call so a test can assert the order.
10353    struct Scripted {
10354        public_repo: Option<PathBuf>,
10355        evidence: Mutex<Option<CiEvidence>>,
10356        views: Mutex<VecDeque<Seen>>,
10357        merges: Mutex<VecDeque<(bool, String)>>,
10358        fix: Mutex<Option<Fixed>>,
10359        log: Mutex<Vec<&'static str>>,
10360        argvs: Mutex<Vec<Vec<String>>>,
10361        required: Mutex<Option<BTreeSet<String>>>,
10362        /// Set once a merge answered ok: the forge then reports `merged`,
10363        /// unless `queued` says the merge only entered a queue.
10364        merged: Mutex<bool>,
10365        queued: Mutex<bool>,
10366        /// Views fail once a merge answered ok.
10367        unreadable_after_merge: Mutex<bool>,
10368        /// Workflow runs asked to rerun, and whether that call fails.
10369        reruns: Mutex<Vec<String>>,
10370        rerun_fails: Mutex<bool>,
10371        /// Unix seconds; every poll moves it on by `POLL`.
10372        clock: Mutex<i64>,
10373    }
10374
10375    impl Scripted {
10376        fn new(views: Vec<Seen>, merges: Vec<(bool, &str)>) -> Self {
10377            Self {
10378                public_repo: None,
10379                evidence: Mutex::new(None),
10380                views: Mutex::new(views.into()),
10381                merges: Mutex::new(
10382                    merges
10383                        .into_iter()
10384                        .map(|(ok, m)| (ok, m.to_owned()))
10385                        .collect(),
10386                ),
10387                fix: Mutex::new(None),
10388                log: Mutex::new(Vec::new()),
10389                argvs: Mutex::new(Vec::new()),
10390                required: Mutex::new(None),
10391                merged: Mutex::new(false),
10392                queued: Mutex::new(false),
10393                unreadable_after_merge: Mutex::new(false),
10394                reruns: Mutex::new(Vec::new()),
10395                rerun_fails: Mutex::new(false),
10396                clock: Mutex::new(1_000),
10397            }
10398        }
10399        fn argvs(&self) -> Vec<Vec<String>> {
10400            self.argvs.lock().unwrap().clone()
10401        }
10402        fn calls(&self) -> Vec<&'static str> {
10403            self.log.lock().unwrap().clone()
10404        }
10405    }
10406
10407    impl Forge for Scripted {
10408        async fn attribution(&self, _state: &RunState, _seen: &Seen) -> Option<CiEvidence> {
10409            self.evidence.lock().unwrap().clone()
10410        }
10411        async fn view(&self, _repo: &Path, _url: &str) -> Result<Seen> {
10412            self.log.lock().unwrap().push("view");
10413            if *self.unreadable_after_merge.lock().unwrap()
10414                && !self.argvs.lock().unwrap().is_empty()
10415            {
10416                anyhow::bail!("forge unreachable");
10417            }
10418            let mut seen = {
10419                let mut v = self.views.lock().unwrap();
10420                if v.len() > 1 {
10421                    v.pop_front().unwrap()
10422                } else {
10423                    v[0].clone()
10424                }
10425            };
10426            if seen.head == "@published" {
10427                let head =
10428                    git::remote_head(self.public_repo.as_ref().unwrap(), "origin", "task-head")
10429                        .await?
10430                        .context("missing published head")?;
10431                seen.head.clone_from(&head);
10432                seen.rollup_head = head;
10433            }
10434            if *self.merged.lock().unwrap() {
10435                seen.pr.state = PrLifecycle::Merged;
10436            }
10437            Ok(seen)
10438        }
10439        async fn merge(&self, _repo: &Path, argv: &[String]) -> Result<(bool, String)> {
10440            self.log.lock().unwrap().push("merge");
10441            self.argvs.lock().unwrap().push(argv.to_vec());
10442            let out = self
10443                .merges
10444                .lock()
10445                .unwrap()
10446                .pop_front()
10447                .expect("unscripted merge");
10448            if out.0 && !*self.queued.lock().unwrap() && !argv.iter().any(|a| a == "--disable-auto")
10449            {
10450                *self.merged.lock().unwrap() = true;
10451            }
10452            Ok(out)
10453        }
10454        async fn poll(&self) {
10455            self.log.lock().unwrap().push("poll");
10456            *self.clock.lock().unwrap() += POLL.as_secs() as i64;
10457        }
10458        async fn rerun(&self, _repo: &Path, run: &str) -> Result<()> {
10459            self.log.lock().unwrap().push("rerun");
10460            self.reruns.lock().unwrap().push(run.to_owned());
10461            if *self.rerun_fails.lock().unwrap() {
10462                anyhow::bail!("gh run rerun: no");
10463            }
10464            Ok(())
10465        }
10466        fn now(&self) -> i64 {
10467            *self.clock.lock().unwrap()
10468        }
10469        async fn required_contexts(&self, _repo: &Path, _base: &str) -> Option<BTreeSet<String>> {
10470            self.required.lock().unwrap().clone()
10471        }
10472        async fn fix(
10473            &self,
10474            _state: &mut RunState,
10475            _pr: &PrState,
10476            _round: usize,
10477            _budget: usize,
10478            _reason: &str,
10479            _logs: &str,
10480        ) -> Result<Fixed> {
10481            self.log.lock().unwrap().push("fix");
10482            Ok(self.fix.lock().unwrap().take().expect("unscripted fix"))
10483        }
10484    }
10485
10486    const REFUSED: &str =
10487        "X Pull request #42 is not mergeable: the base branch policy prohibits the merge.";
10488
10489    fn seen(head: &str, checks: Checks, merge_state: &str, comments: bool) -> Seen {
10490        let mut pr = green_pr();
10491        pr.checks = checks;
10492        pr.blocking = Blocking::of(merge_state);
10493        if !comments {
10494            pr.review_comments.clear();
10495        }
10496        Seen {
10497            pr,
10498            title: "feat: x".to_owned(),
10499            failing_urls: Vec::new(),
10500            head: head.to_owned(),
10501            rollup_head: head.to_owned(),
10502            merge_state: merge_state.to_owned(),
10503            contexts: Vec::new(),
10504            base: "main".to_owned(),
10505        }
10506    }
10507
10508    fn landing_state() -> RunState {
10509        crate::run::pin_test_home();
10510        let mut state = run_state();
10511        state.config.graph.land_approval = false;
10512        state
10513    }
10514
10515    #[test]
10516    fn a_pushed_head_is_awaited_case_insensitively_and_an_unreadable_one_is_not_a_match() {
10517        assert!(!awaiting_new_head(None, "aaa"));
10518        assert!(!awaiting_new_head(Some("abc123"), "ABC123"));
10519        assert!(awaiting_new_head(Some("abc123"), "def456"));
10520        assert!(awaiting_new_head(Some("abc123"), ""));
10521    }
10522
10523    #[test]
10524    fn a_refusal_is_judged_by_the_pull_requests_state_not_by_its_wording() {
10525        let open = |c, m: &str| seen("a", c, m, false);
10526        let table = [
10527            (None, false, Refused::Pending),
10528            (
10529                Some(open(Checks::Pending, "BLOCKED")),
10530                false,
10531                Refused::Pending,
10532            ),
10533            (
10534                Some(open(Checks::Unknown, "BLOCKED")),
10535                false,
10536                Refused::Pending,
10537            ),
10538            (
10539                Some(open(Checks::Green, "UNKNOWN")),
10540                false,
10541                Refused::Pending,
10542            ),
10543            (Some(open(Checks::Green, "")), false, Refused::Pending),
10544            (
10545                Some(open(Checks::Green, "BLOCKED")),
10546                false,
10547                Refused::Recheck,
10548            ),
10549            (Some(open(Checks::Green, "BLOCKED")), true, Refused::Final),
10550        ];
10551        for (after, rechecked, want) in table {
10552            assert_eq!(
10553                classify_refusal(after.as_ref(), rechecked, "a", CiExpectation::Expected),
10554                want
10555            );
10556        }
10557        let mut closed = open(Checks::Green, "CLEAN");
10558        closed.pr.state = PrLifecycle::Closed;
10559        assert_eq!(
10560            classify_refusal(Some(&closed), false, "a", CiExpectation::Expected),
10561            Refused::Final
10562        );
10563    }
10564
10565    #[test]
10566    fn behind_precedes_old_ci_and_other_blocking_policies_stay_distinct() {
10567        for checks in [Checks::Pending, Checks::Unknown, Checks::Red, Checks::Green] {
10568            let pr = seen("a", checks, "BEHIND", false).pr;
10569            assert_eq!(
10570                decide_with(&pr, 0, 4, Duration::ZERO, CiExpectation::Expected),
10571                Step::Rebase
10572            );
10573        }
10574        for status in ["DRAFT", "BLOCKED", "UNKNOWN"] {
10575            let current = seen("a", Checks::Green, status, false);
10576            assert_ne!(
10577                decide_with(&current.pr, 0, 4, Duration::ZERO, CiExpectation::Expected),
10578                Step::Rebase
10579            );
10580            assert_ne!(
10581                classify_refusal(Some(&current), false, "a", CiExpectation::Expected),
10582                Refused::Behind
10583            );
10584        }
10585        let mut current = seen("a", Checks::Pending, "BEHIND", false);
10586        current.rollup_head = "old".into();
10587        assert_eq!(
10588            classify_refusal(Some(&current), true, "a", CiExpectation::Expected),
10589            Refused::Behind
10590        );
10591        assert_eq!(
10592            classify_refusal(Some(&current), true, "other", CiExpectation::Expected),
10593            Refused::Pending
10594        );
10595        current.pr.state = PrLifecycle::Closed;
10596        assert_eq!(
10597            classify_refusal(Some(&current), true, "a", CiExpectation::Expected),
10598            Refused::Final
10599        );
10600    }
10601
10602    #[tokio::test]
10603    async fn behind_at_each_landing_boundary_syncs_and_requires_new_head_approval() {
10604        for boundary in ["initial", "premerge", "refusal"] {
10605            let (_tmp, mut state, old) = landing_git_fixture().await;
10606            state.land_sync_pending = false;
10607            advance_landing_base(&state).await;
10608            state.config.verify.gate = vec!["test -f advance".into()];
10609            state.config.verify.e2e = vec!["test -f advance".into()];
10610            approval_gate(&mut state, &green_pr(), "feat: x", None, &old)
10611                .await
10612                .unwrap();
10613            let old_binding = state.land_approval.clone().unwrap();
10614            let store = ask::Questions::open();
10615            let mut question = store.get(&old_binding.question).unwrap();
10616            question
10617                .answer(ask::Answer::Choice(APPROVE.to_owned()))
10618                .unwrap();
10619            store.put(&mut question).unwrap();
10620            let mut views = Vec::new();
10621            if boundary != "initial" {
10622                views.push(seen(&old, Checks::Green, "CLEAN", false));
10623            }
10624            if boundary == "refusal" {
10625                views.push(seen(&old, Checks::Green, "CLEAN", false));
10626            }
10627            let mut behind = seen(&old, Checks::Pending, "BEHIND", false);
10628            behind.rollup_head = "old-ci-head".into();
10629            views.push(behind);
10630            // Publication checks the PR lease while verification has completed.
10631            views.push(seen(&old, Checks::Green, "CLEAN", false));
10632            views.push(seen("@published", Checks::Pending, "CLEAN", false));
10633            views.push(seen("@published", Checks::Green, "CLEAN", false));
10634            let merges = if boundary == "refusal" {
10635                vec![(false, REFUSED)]
10636            } else {
10637                vec![]
10638            };
10639            let mut forge = Scripted::new(views, merges);
10640            forge.public_repo = Some(state.repo.clone());
10641            let run = state.id.clone();
10642            land_with(&mut state, URL, &forge).await.unwrap();
10643            let head = state.pr_pushed_head.clone().unwrap();
10644            assert_ne!(head, old, "{boundary}");
10645            assert_eq!(state.id, run);
10646            assert_eq!(state.pr_branch(), Some("task-head"));
10647            assert_eq!(state.winner().unwrap().branch, "winner");
10648            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
10649            assert!(state.gate_allows_progress());
10650            let e2e = state.head_e2e.as_ref().unwrap();
10651            assert_eq!(e2e.head, head);
10652            assert!(e2e.passed);
10653            assert_eq!(state.land_sync_attempts, 1);
10654            assert!(!state.land_sync_pending);
10655            assert!(state.parked);
10656            let binding = state.land_approval.as_ref().unwrap();
10657            assert_eq!(binding.head, head);
10658            assert_ne!(binding.question, old_binding.question);
10659            assert_eq!(forge.argvs().len(), usize::from(boundary == "refusal"));
10660            // The new question authorizes only the synchronized head on resume.
10661            let mut question = store.get(&binding.question).unwrap();
10662            question
10663                .answer(ask::Answer::Choice(APPROVE.to_owned()))
10664                .unwrap();
10665            store.put(&mut question).unwrap();
10666            let forge = Scripted::new(
10667                vec![seen(&head, Checks::Green, "CLEAN", false)],
10668                vec![(true, "")],
10669            );
10670            land_with(&mut state, URL, &forge).await.unwrap();
10671            assert_eq!(state.status, RunStatus::Merged);
10672            assert_eq!(
10673                value_of(&forge.argvs()[0], "--match-head-commit"),
10674                Some(head.as_str())
10675            );
10676        }
10677    }
10678
10679    #[tokio::test]
10680    async fn behind_refusal_remains_actionable_when_the_next_view_is_clean() {
10681        let (_tmp, mut state, old) = landing_git_fixture().await;
10682        state.land_sync_pending = false;
10683        state.config.graph.land_approval = false;
10684        state.config.verify.gate = vec!["test -f advance && test -f change".into()];
10685        advance_landing_base(&state).await;
10686        let mut forge = Scripted::new(
10687            vec![
10688                seen(&old, Checks::Green, "CLEAN", false),
10689                seen(&old, Checks::Green, "CLEAN", false),
10690                seen(&old, Checks::Green, "BEHIND", false),
10691                // The next observation is the publication lease check. The
10692                // refusal's evidence still applies to exactly this old head.
10693                seen(&old, Checks::Green, "CLEAN", false),
10694                seen("@published", Checks::Green, "CLEAN", false),
10695            ],
10696            vec![(false, REFUSED), (true, "")],
10697        );
10698        forge.public_repo = Some(state.repo.clone());
10699        land_with(&mut state, URL, &forge).await.unwrap();
10700        let head = state.pr_pushed_head.as_deref().unwrap();
10701        assert_ne!(head, old);
10702        assert_eq!(state.land_sync_attempts, 1);
10703        assert_eq!(state.gate_head.as_deref(), Some(head));
10704        assert_eq!(state.status, RunStatus::Merged);
10705        let requests = forge.argvs();
10706        assert_eq!(requests.len(), 2);
10707        assert_eq!(
10708            value_of(&requests[0], "--match-head-commit"),
10709            Some(old.as_str())
10710        );
10711        assert_eq!(value_of(&requests[1], "--match-head-commit"), Some(head));
10712    }
10713
10714    #[tokio::test]
10715    async fn behind_ancestry_failure_stops_without_rebasing_or_publishing() {
10716        let (tmp, mut state, old) = landing_git_fixture().await;
10717        state.land_sync_pending = false;
10718        // A damaged history must not be interpreted as a missing base. Keep
10719        // the head's tree intact so worktree restoration itself can succeed.
10720        let tree = git::rev_parse(&state.repo, "HEAD^{tree}").await.unwrap();
10721        let commit = tmp.path().join("broken-commit");
10722        std::fs::write(
10723            &commit,
10724            format!(
10725                "tree {tree}\nparent {}\nauthor Test <test@example.test> 1 +0000\ncommitter Test <test@example.test> 1 +0000\n\nbroken history\n",
10726                "f".repeat(40)
10727            ),
10728        )
10729        .unwrap();
10730        let replacement = git::git(
10731            &state.repo,
10732            &[
10733                "hash-object",
10734                "-t",
10735                "commit",
10736                "-w",
10737                commit.to_str().unwrap(),
10738            ],
10739        )
10740        .await
10741        .unwrap();
10742        git::git(&state.repo, &["replace", &old, replacement.trim()])
10743            .await
10744            .unwrap();
10745        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
10746        land_with(&mut state, URL, &forge).await.unwrap();
10747        assert_eq!(state.land_sync_attempts, 0);
10748        assert_eq!(state.pr_pushed_head.as_deref(), Some(old.as_str()));
10749        assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
10750        assert!(forge.argvs().is_empty());
10751        assert!(
10752            state.events.iter().any(|e| e.message.contains(
10753                "could not determine whether the landing head contains the fetched base"
10754            ))
10755        );
10756    }
10757
10758    #[tokio::test]
10759    async fn behind_fetch_failure_stops_without_rebasing_or_publishing() {
10760        let (_tmp, mut state, old) = landing_git_fixture().await;
10761        state.land_sync_pending = false;
10762        git::git(
10763            &state.repo,
10764            &["remote", "set-url", "origin", "missing-remote"],
10765        )
10766        .await
10767        .unwrap();
10768        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
10769        land_with(&mut state, URL, &forge).await.unwrap();
10770        assert_eq!(state.land_sync_attempts, 0);
10771        assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
10772        assert!(
10773            state
10774                .events
10775                .iter()
10776                .any(|e| e.message.contains("cannot fetch landing base"))
10777        );
10778        assert!(forge.argvs().is_empty());
10779    }
10780
10781    #[tokio::test]
10782    async fn behind_without_base_progress_and_exhausted_resume_budget_never_publish() {
10783        let (_tmp, mut state, old) = landing_git_fixture().await;
10784        state.land_sync_pending = false;
10785        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
10786        land_with(&mut state, URL, &forge).await.unwrap();
10787        assert_eq!(state.pr_pushed_head.as_deref(), Some(old.as_str()));
10788        assert_eq!(state.land_sync_attempts, 0);
10789        assert!(
10790            state
10791                .events
10792                .iter()
10793                .any(|e| e.message.contains("already included"))
10794        );
10795        advance_landing_base(&state).await;
10796        state.land_sync_attempts = state.config.graph.land_rounds;
10797        state.land_sync_pending = true;
10798        state.save().unwrap();
10799        let mut restored = RunState::load(&state.id).unwrap();
10800        assert!(
10801            resume_observed_head(&mut restored, &old)
10802                .await
10803                .unwrap_err()
10804                .to_string()
10805                .contains("budget exhausted")
10806        );
10807        assert_eq!(
10808            git::remote_head(&state.repo, "origin", "task-head")
10809                .await
10810                .unwrap(),
10811            Some(old)
10812        );
10813    }
10814
10815    #[tokio::test]
10816    async fn a_normal_landing_merges_on_the_first_look() {
10817        let mut state = landing_state();
10818        let forge = Scripted::new(
10819            vec![seen("a", Checks::Green, "CLEAN", false)],
10820            vec![(true, "")],
10821        );
10822        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10823            .await
10824            .unwrap();
10825        // One fresh read, then the head-bound merge.
10826        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
10827        assert_eq!(state.status, RunStatus::Merged);
10828    }
10829
10830    #[tokio::test]
10831    async fn a_successful_merge_command_that_only_queued_is_not_a_merge() {
10832        let mut state = landing_state();
10833        let forge = Scripted::new(
10834            vec![seen("a", Checks::Green, "CLEAN", false)],
10835            std::iter::repeat_n((true, ""), 100).collect(),
10836        );
10837        *forge.queued.lock().unwrap() = true;
10838        let task = async {
10839            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10840                .await
10841                .unwrap();
10842        };
10843        // Still open after the command succeeded: it keeps watching and
10844        // never records a merge (it stops at the wait ceiling instead).
10845        task.await;
10846        assert_ne!(state.status, RunStatus::Merged);
10847    }
10848
10849    #[tokio::test]
10850    async fn an_unreadable_forge_after_a_merge_command_is_not_a_confirmation() {
10851        let mut state = landing_state();
10852        let forge = Scripted::new(
10853            vec![seen("a", Checks::Green, "CLEAN", false)],
10854            std::iter::repeat_n((true, ""), 100).collect(),
10855        );
10856        *forge.unreadable_after_merge.lock().unwrap() = true;
10857        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10858            .await
10859            .ok();
10860        assert_ne!(state.status, RunStatus::Merged);
10861    }
10862
10863    #[tokio::test]
10864    async fn a_task_public_head_is_awaited_on_land_entry() {
10865        let mut state = landing_state();
10866        state.pr_head = Some("magi/task-abcd-1234".into());
10867        state.pr_pushed_head = Some("new".into());
10868        let forge = Scripted::new(
10869            vec![
10870                seen("old", Checks::Green, "CLEAN", false),
10871                seen("new", Checks::Green, "CLEAN", false),
10872            ],
10873            vec![(true, "")],
10874        );
10875        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10876            .await
10877            .unwrap();
10878        assert_eq!(
10879            forge.calls(),
10880            ["view", "poll", "view", "view", "merge", "view"]
10881        );
10882        assert_eq!(state.status, RunStatus::Merged);
10883    }
10884
10885    #[tokio::test]
10886    async fn a_superseded_public_head_owner_cannot_reenter_land() {
10887        let mut state = landing_state();
10888        state.pr_taken_over_by = Some("next".into());
10889        let forge = Scripted::new(vec![seen("a", Checks::Green, "CLEAN", false)], vec![]);
10890        assert!(
10891            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10892                .await
10893                .is_err()
10894        );
10895        assert!(forge.calls().is_empty());
10896    }
10897
10898    #[tokio::test]
10899    async fn after_a_pushed_fix_no_merge_is_tried_until_the_head_matches() {
10900        let mut state = landing_state();
10901        let forge = Scripted::new(
10902            vec![
10903                seen("old", Checks::Green, "CLEAN", true),
10904                // The forge has not moved to the new head yet: still green.
10905                seen("old", Checks::Green, "CLEAN", true),
10906                seen("new", Checks::Pending, "BLOCKED", true),
10907                seen("new", Checks::Green, "CLEAN", true),
10908            ],
10909            vec![(true, "")],
10910        );
10911        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
10912            head: "NEW".to_owned(),
10913        });
10914        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10915            .await
10916            .unwrap();
10917        assert_eq!(
10918            forge.calls(),
10919            [
10920                "view", "fix", "poll", "view", "poll", "view", "poll", "view", "view", "merge",
10921                "view"
10922            ]
10923        );
10924        assert_eq!(state.status, RunStatus::Merged);
10925    }
10926
10927    #[tokio::test]
10928    async fn a_head_that_never_arrives_stops_naming_both_commits() {
10929        let mut state = landing_state();
10930        let forge = Scripted::new(
10931            vec![
10932                seen("old", Checks::Green, "CLEAN", true),
10933                seen("someone-elses", Checks::Green, "CLEAN", true),
10934            ],
10935            vec![],
10936        );
10937        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
10938            head: "mine".to_owned(),
10939        });
10940        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10941            .await
10942            .unwrap();
10943        assert!(!forge.calls().contains(&"merge"));
10944        let why = state.merge.as_ref().unwrap().detail.clone();
10945        assert!(
10946            why.contains("mine") && why.contains("someone-elses"),
10947            "{why}"
10948        );
10949        assert_eq!(state.status, RunStatus::Blocked);
10950    }
10951
10952    #[tokio::test]
10953    async fn a_policy_refusal_while_checks_run_waits_and_then_merges() {
10954        let mut state = landing_state();
10955        let forge = Scripted::new(
10956            vec![
10957                seen("a", Checks::Green, "CLEAN", false),
10958                seen("a", Checks::Green, "CLEAN", false),
10959                seen("a", Checks::Pending, "BLOCKED", false),
10960                seen("a", Checks::Pending, "BLOCKED", false),
10961                seen("a", Checks::Green, "CLEAN", false),
10962            ],
10963            vec![(false, REFUSED), (true, "")],
10964        );
10965        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10966            .await
10967            .unwrap();
10968        assert_eq!(
10969            forge.calls(),
10970            [
10971                "view", "view", "merge", "view", "poll", "view", "poll", "view", "view", "merge",
10972                "view"
10973            ]
10974        );
10975        assert_eq!(state.status, RunStatus::Merged);
10976    }
10977
10978    #[tokio::test]
10979    async fn a_refusal_that_outlives_settled_checks_stops_with_the_merge_state() {
10980        let mut state = landing_state();
10981        let forge = Scripted::new(
10982            vec![
10983                seen("a", Checks::Green, "CLEAN", false),
10984                seen("a", Checks::Green, "BLOCKED", false),
10985            ],
10986            vec![(false, REFUSED), (false, REFUSED)],
10987        );
10988        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10989            .await
10990            .unwrap();
10991        // One re-look is allowed for the forge's own lag, then it is final.
10992        assert_eq!(forge.calls().iter().filter(|c| **c == "merge").count(), 2);
10993        let why = state.merge.as_ref().unwrap().detail.clone();
10994        assert!(
10995            why.contains("policy prohibits") && why.contains("BLOCKED") && why.contains("refused"),
10996            "{why}"
10997        );
10998        assert_eq!(state.status, RunStatus::Blocked);
10999    }
11000
11001    #[test]
11002    fn a_decision_is_bound_to_a_head_only_when_every_signal_agrees() {
11003        assert_eq!(bound_head("abc", "abc", None), Some("abc"));
11004        assert_eq!(bound_head("abc", "ABC", Some("abc")), Some("abc"));
11005        // The pull request is still on the commit before the push.
11006        assert_eq!(bound_head("old", "old", Some("new")), None);
11007        // The checks are the previous commit's.
11008        assert_eq!(bound_head("new", "old", Some("new")), None);
11009        assert_eq!(bound_head("new", "old", None), None);
11010        // Nothing readable.
11011        assert_eq!(bound_head("", "", None), None);
11012        assert_eq!(bound_head("", "", Some("new")), None);
11013        assert_eq!(bound_head("abc", "", None), None);
11014    }
11015
11016    fn view_json(head: &str) -> String {
11017        format!(
11018            r#"{{"url":"https://github.com/o/r/pull/42","number":42,"state":"OPEN",
11019            "title":"t","headRefOid":"{head}","mergeStateStatus":"CLEAN",
11020            "reviews":[],"comments":[]}}"#
11021        )
11022    }
11023
11024    fn node_json(oid: &str, check: &str, has_next: bool) -> String {
11025        format!(
11026            r#"{{"data":{{"repository":{{"pullRequest":{{"commits":{{"nodes":[{{"commit":
11027            {{"oid":"{oid}","statusCheckRollup":{{"contexts":{{"pageInfo":{{"hasNextPage":{has_next}}},
11028            "nodes":[{{"__typename":"CheckRun","name":"ci","status":"COMPLETED",
11029            "conclusion":"{check}","detailsUrl":"https://example.test/1"}}]}}}}}}}}]}}}}}}}}}}"#
11030        )
11031    }
11032
11033    #[test]
11034    fn rollup_is_bound_to_the_commit_in_the_same_node() {
11035        // The view already points at the new head, but the node still answers
11036        // for the old commit with its red check: the head stays unbound.
11037        let s = seen_from(&view_json("new"), Some(&node_json("old", "FAILURE", false))).unwrap();
11038        assert_eq!(s.rollup_head, "old");
11039        assert_eq!(s.pr.checks, Checks::Red);
11040        assert_eq!(bound_head(&s.head, &s.rollup_head, Some("new")), None);
11041        assert_eq!(s.failing_urls.len(), 1);
11042    }
11043
11044    #[test]
11045    fn checks_come_from_the_node_not_the_view() {
11046        let view = view_json("new").replace(
11047            r#""reviews""#,
11048            r#""statusCheckRollup":[{"name":"ci","status":"COMPLETED","conclusion":"FAILURE"}],"reviews""#,
11049        );
11050        let s = seen_from(&view, Some(&node_json("new", "SUCCESS", false))).unwrap();
11051        assert_eq!(s.pr.checks, Checks::Green);
11052        assert!(s.pr.failing.is_empty());
11053        assert_eq!(
11054            bound_head(&s.head, &s.rollup_head, Some("new")),
11055            Some("new")
11056        );
11057    }
11058
11059    #[test]
11060    fn an_unreadable_or_paged_node_leaves_the_head_unbound() {
11061        for node in [
11062            None,
11063            Some("not json".to_owned()),
11064            Some(r#"{"errors":[{"message":"x"}]}"#.to_owned()),
11065            Some(node_json("new", "SUCCESS", true)),
11066        ] {
11067            let s = seen_from(&view_json("new"), node.as_deref()).unwrap();
11068            assert!(s.rollup_head.is_empty());
11069            assert_eq!(s.pr.checks, Checks::Unknown);
11070            assert_eq!(bound_head(&s.head, &s.rollup_head, None), None);
11071        }
11072    }
11073
11074    #[test]
11075    fn the_merge_command_is_pinned_to_the_observed_head() {
11076        let argv = merge_argv_at(7, "feat: x", "deadbeef");
11077        let at = argv
11078            .iter()
11079            .position(|a| a == "--match-head-commit")
11080            .unwrap();
11081        assert_eq!(argv[at + 1], "deadbeef");
11082    }
11083
11084    #[tokio::test]
11085    async fn stale_checks_after_a_fix_push_never_reach_a_merge() {
11086        let mut state = landing_state();
11087        // The pull request is on the pushed head but the rollup is still the
11088        // previous commit's red, non-required result.
11089        let mut stale = seen("new", Checks::Red, "CLEAN", false);
11090        stale.rollup_head = "old".to_owned();
11091        let forge = Scripted::new(
11092            vec![seen("old", Checks::Green, "CLEAN", true), stale],
11093            vec![],
11094        );
11095        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11096            head: "new".to_owned(),
11097        });
11098        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11099            .await
11100            .unwrap();
11101        assert!(!forge.calls().contains(&"merge"));
11102        assert_eq!(state.status, RunStatus::Blocked);
11103        let why = state.merge.as_ref().unwrap().detail.clone();
11104        assert!(why.contains("new") && why.contains("old"), "{why}");
11105    }
11106
11107    #[test]
11108    fn a_refusal_read_against_another_commits_checks_is_pending() {
11109        let mut after = seen("a", Checks::Green, "BLOCKED", false);
11110        after.rollup_head = "old".to_owned();
11111        assert_eq!(
11112            classify_refusal(Some(&after), true, "a", CiExpectation::Expected),
11113            Refused::Pending
11114        );
11115    }
11116
11117    #[tokio::test]
11118    async fn absent_ci_empty_rollup_reaches_approval_then_merges_on_the_approved_head() {
11119        let mut state = landing_state();
11120        state.config.merge.ci = crate::config::MergeCi::None;
11121        state.config.graph.land_approval = true;
11122        let forge = Scripted::new(
11123            vec![seen("a", Checks::Unknown, "CLEAN", false)],
11124            vec![(true, "")],
11125        );
11126        land_with(&mut state, URL, &forge).await.unwrap();
11127        assert!(state.parked);
11128        assert_eq!(forge.calls(), ["view"]);
11129        let store = ask::Questions::open();
11130        let mut q = store
11131            .get(&state.land_approval.as_ref().unwrap().question)
11132            .unwrap();
11133        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
11134        store.put(&mut q).unwrap();
11135
11136        land_with(&mut state, URL, &forge).await.unwrap();
11137        assert_eq!(forge.calls(), ["view", "view", "view", "merge", "view"]);
11138        assert_eq!(state.status, RunStatus::Merged);
11139        assert_eq!(
11140            value_of(&forge.argvs()[0], "--match-head-commit"),
11141            Some("a")
11142        );
11143    }
11144
11145    #[tokio::test]
11146    async fn absent_ci_ignores_failed_workflow_runs_without_rerunning_them() {
11147        let mut state = landing_state();
11148        state.config.merge.ci = crate::config::MergeCi::None;
11149        let forge = Scripted::new(vec![red("a", Some("7"))], vec![(true, "")]);
11150        land_with(&mut state, URL, &forge).await.unwrap();
11151        assert!(forge.reruns.lock().unwrap().is_empty());
11152        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11153        assert_eq!(state.status, RunStatus::Merged);
11154    }
11155
11156    #[test]
11157    fn absent_ci_still_requires_a_readable_matching_head_and_resolved_comments() {
11158        let shown = BTreeSet::new();
11159        let guard = |s: Option<&Seen>| {
11160            direct_merge_is_safe(s, "a", &shown, 0, 4, Duration::ZERO, CiExpectation::Absent)
11161        };
11162        let mut fresh = seen("a", Checks::Unknown, "CLEAN", false);
11163        assert!(guard(Some(&fresh)));
11164        assert!(!guard(None));
11165        fresh.rollup_head = "old".to_owned();
11166        assert!(!guard(Some(&fresh)));
11167        fresh.rollup_head = "a".to_owned();
11168        fresh.head = "b".to_owned();
11169        assert!(!guard(Some(&fresh)));
11170        assert!(!guard(Some(&seen("a", Checks::Unknown, "CLEAN", true))));
11171        assert!(!guard(Some(&seen("a", Checks::Unknown, "DIRTY", false))));
11172    }
11173
11174    #[test]
11175    fn absent_ci_refusal_does_not_wait_for_third_party_checks() {
11176        for checks in [Checks::Unknown, Checks::Pending, Checks::Red, Checks::Green] {
11177            let after = seen("a", checks, "BLOCKED", false);
11178            assert_eq!(
11179                classify_refusal(Some(&after), false, "a", CiExpectation::Absent),
11180                Refused::Recheck
11181            );
11182            assert_eq!(
11183                classify_refusal(Some(&after), true, "a", CiExpectation::Absent),
11184                Refused::Final
11185            );
11186        }
11187    }
11188
11189    #[tokio::test]
11190    async fn a_matching_head_with_red_non_required_checks_still_merges() {
11191        let mut state = landing_state();
11192        let forge = Scripted::new(
11193            vec![seen("a", Checks::Red, "CLEAN", false)],
11194            vec![(true, "")],
11195        );
11196        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11197            .await
11198            .unwrap();
11199        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11200        assert_eq!(state.status, RunStatus::Merged);
11201    }
11202
11203    #[tokio::test]
11204    async fn a_merge_refused_because_the_head_moved_looks_again_instead_of_failing() {
11205        let mut state = landing_state();
11206        let forge = Scripted::new(
11207            vec![
11208                seen("a", Checks::Green, "CLEAN", false),
11209                seen("a", Checks::Green, "CLEAN", false),
11210                // Re-viewed after the refusal: someone pushed.
11211                seen("b", Checks::Green, "BLOCKED", false),
11212                seen("b", Checks::Green, "CLEAN", false),
11213            ],
11214            vec![(false, REFUSED), (true, "")],
11215        );
11216        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
11217            .await
11218            .unwrap();
11219        assert_eq!(
11220            forge.calls(),
11221            [
11222                "view", "view", "merge", "view", "poll", "view", "view", "merge", "view"
11223            ]
11224        );
11225        assert_eq!(state.status, RunStatus::Merged);
11226    }
11227
11228    fn merged_view(head: &str) -> Seen {
11229        let mut m = seen(head, Checks::Green, "CLEAN", false);
11230        m.pr.state = PrLifecycle::Merged;
11231        m
11232    }
11233
11234    fn has(argv: &[String], flag: &str) -> bool {
11235        argv.iter().any(|a| a == flag)
11236    }
11237
11238    fn value_of<'a>(argv: &'a [String], flag: &str) -> Option<&'a str> {
11239        let at = argv.iter().position(|a| a == flag)?;
11240        argv.get(at + 1).map(String::as_str)
11241    }
11242
11243    const URL: &str = "https://github.com/o/r/pull/42";
11244
11245    #[tokio::test]
11246    async fn the_merge_step_merges_directly_on_the_observed_head_and_never_arms() {
11247        let mut state = landing_state();
11248        let forge = Scripted::new(
11249            vec![
11250                seen("abc", Checks::Green, "CLEAN", false),
11251                seen("abc", Checks::Green, "CLEAN", false),
11252            ],
11253            vec![(true, "")],
11254        );
11255        land_with(&mut state, URL, &forge).await.unwrap();
11256        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
11257        let argv = &forge.argvs()[0];
11258        assert!(has(argv, "--squash") && has(argv, "--subject"));
11259        assert!(!has(argv, "--auto") && !has(argv, "--admin"));
11260        assert_eq!(value_of(argv, "--match-head-commit"), Some("abc"));
11261        assert_eq!(state.status, RunStatus::Merged);
11262        assert!(state.land_armed_head.is_none());
11263    }
11264
11265    #[tokio::test]
11266    async fn a_resume_disables_an_arm_left_by_an_older_build_before_merging() {
11267        let mut state = landing_state();
11268        state.land_armed_head = Some("a".to_owned());
11269        let forge = Scripted::new(
11270            vec![seen("a", Checks::Green, "CLEAN", false)],
11271            vec![(true, ""), (true, "")],
11272        );
11273        land_with(&mut state, URL, &forge).await.unwrap();
11274        let argvs = forge.argvs();
11275        assert!(has(&argvs[0], "--disable-auto"));
11276        assert!(!has(&argvs[1], "--auto"));
11277        assert_eq!(value_of(&argvs[1], "--match-head-commit"), Some("a"));
11278        assert_eq!(state.status, RunStatus::Merged);
11279        assert!(state.land_armed_head.is_none());
11280    }
11281
11282    #[tokio::test]
11283    async fn an_approval_never_carries_over_to_a_new_head() {
11284        crate::run::pin_test_home();
11285        let mut state = run_state();
11286        state.config.graph.land_approval = true;
11287        let pr = green_pr();
11288        let store = ask::Questions::open();
11289
11290        approval_gate(&mut state, &pr, "feat: x", None, "aaa")
11291            .await
11292            .unwrap();
11293        let mut q = store
11294            .list()
11295            .into_iter()
11296            .find(|q| q.run == state.id)
11297            .unwrap();
11298        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
11299        store.put(&mut q).unwrap();
11300        assert_eq!(
11301            approval_gate(&mut state, &pr, "feat: x", None, "AAA")
11302                .await
11303                .unwrap(),
11304            ApprovalGate::Approved,
11305            "the same head keeps its approval"
11306        );
11307
11308        // A new head is a new question, not the old word.
11309        assert_eq!(
11310            approval_gate(&mut state, &pr, "feat: x", None, "bbb")
11311                .await
11312                .unwrap(),
11313            ApprovalGate::Pending
11314        );
11315        let all: Vec<_> = store
11316            .list()
11317            .into_iter()
11318            .filter(|q| q.run == state.id)
11319            .collect();
11320        assert_eq!(all.len(), 2);
11321
11322        // A question recorded before heads were tracked is not reused either.
11323        state.land_approval = None;
11324        assert_eq!(
11325            approval_gate(&mut state, &pr, "feat: x", None, "bbb")
11326                .await
11327                .unwrap(),
11328            ApprovalGate::Pending
11329        );
11330        let open = store
11331            .list()
11332            .into_iter()
11333            .filter(|q| q.run == state.id && q.status.open())
11334            .count();
11335        assert_eq!(open, 1, "the superseded question was retired");
11336    }
11337
11338    #[tokio::test]
11339    async fn the_merge_is_bound_to_the_head_it_was_decided_on() {
11340        let mut state = landing_state();
11341        let forge = Scripted::new(
11342            vec![
11343                seen("a", Checks::Green, "CLEAN", false),
11344                // The fresh read before the merge: someone pushed.
11345                seen("b", Checks::Green, "CLEAN", false),
11346            ],
11347            vec![(true, "")],
11348        );
11349        land_with(&mut state, URL, &forge).await.unwrap();
11350        let argvs = forge.argvs();
11351        assert_eq!(argvs.len(), 1, "no merge was tried on the moved head");
11352        assert!(!has(&argvs[0], "--auto"));
11353        assert_eq!(value_of(&argvs[0], "--match-head-commit"), Some("b"));
11354        assert_eq!(state.status, RunStatus::Merged);
11355    }
11356
11357    fn passing(label: &str) -> CheckInfo {
11358        CheckInfo {
11359            label: label.to_owned(),
11360            verdict: Verdict::Pass,
11361            required: Some(false),
11362            run: None,
11363        }
11364    }
11365
11366    fn failing(label: &str, run: Option<&str>) -> (String, Option<String>) {
11367        (label.to_owned(), run.map(str::to_owned))
11368    }
11369
11370    fn reran(head: &str, runs: &[(&str, i64)]) -> LandReruns {
11371        LandReruns {
11372            head: head.to_owned(),
11373            runs: runs.iter().map(|(r, at)| ((*r).to_owned(), *at)).collect(),
11374        }
11375    }
11376
11377    #[test]
11378    fn a_failed_run_is_rerun_once_then_waited_on_then_left_to_the_fixer() {
11379        let f = [failing("test (macos)", Some("7"))];
11380        assert_eq!(
11381            rerun_step(&f, None, "h", 100),
11382            RerunStep::Rerun(vec!["7".to_owned()])
11383        );
11384        let rec = reran("h", &[("7", 100)]);
11385        let grace = crate::release_watch::RERUN_GRACE;
11386        assert_eq!(
11387            rerun_step(&f, Some(&rec), "h", 100 + grace - 1),
11388            RerunStep::Grace
11389        );
11390        assert_eq!(rerun_step(&f, Some(&rec), "h", 100 + grace), RerunStep::Fix);
11391    }
11392
11393    #[test]
11394    fn a_failure_without_a_run_id_goes_to_the_fixer() {
11395        let f = [failing("a", Some("7")), failing("ci/external", None)];
11396        assert_eq!(rerun_step(&f, None, "h", 0), RerunStep::Fix);
11397        assert_eq!(rerun_step(&[], None, "h", 0), RerunStep::Fix);
11398    }
11399
11400    #[test]
11401    fn a_moved_head_forgets_the_reruns() {
11402        let f = [failing("a", Some("7"))];
11403        let rec = reran("old", &[("7", 100)]);
11404        assert_eq!(
11405            rerun_step(&f, Some(&rec), "new", 101),
11406            RerunStep::Rerun(vec!["7".to_owned()])
11407        );
11408    }
11409
11410    #[test]
11411    fn only_unrerun_runs_are_rerun_and_duplicates_collapse() {
11412        let f = [
11413            failing("a", Some("7")),
11414            failing("b", Some("7")),
11415            failing("c", Some("8")),
11416        ];
11417        assert_eq!(
11418            rerun_step(&f, None, "h", 0),
11419            RerunStep::Rerun(vec!["7".to_owned(), "8".to_owned()])
11420        );
11421        let rec = reran("h", &[("7", 0)]);
11422        assert_eq!(
11423            rerun_step(&f, Some(&rec), "h", 1),
11424            RerunStep::Rerun(vec!["8".to_owned()])
11425        );
11426    }
11427
11428    #[test]
11429    fn only_blocking_failures_are_candidates_for_a_rerun() {
11430        let check = |label: &str, verdict, required, run: &str| CheckInfo {
11431            label: label.to_owned(),
11432            verdict,
11433            required,
11434            run: Some(run.to_owned()),
11435        };
11436        let got = rerunnable(&[
11437            check("passed", Verdict::Pass, Some(true), "1"),
11438            check("optional", Verdict::Fail, Some(false), "2"),
11439            check("required", Verdict::Fail, Some(true), "3"),
11440            check("unknown", Verdict::Fail, None, "4"),
11441        ]);
11442        let labels: Vec<_> = got.iter().map(|(l, _)| l.as_str()).collect();
11443        assert_eq!(labels, ["required", "unknown"]);
11444    }
11445
11446    fn unrelated_ci_fixture() -> CiEvidence {
11447        let failure = CiFailure {
11448            path: "tests/web_render.rs".into(),
11449            start_line: 42,
11450            end_line: 42,
11451            title: "question_identity_disclosure_copy_and_live_updates".into(),
11452            message: "assertion failed".into(),
11453        };
11454        CiEvidence {
11455            head: "a".into(),
11456            base: "base-sha".into(),
11457            changed: vec![
11458                "AGENTS.md".into(),
11459                "src/talk.rs".into(),
11460                "tests/consult_investigation.rs".into(),
11461            ],
11462            checks: vec![CiCheckEvidence {
11463                label: "coverage".into(),
11464                head_check: 70,
11465                base_check: 60,
11466                app: 1,
11467                run: "7".into(),
11468                base_run: "6".into(),
11469                head_failures: vec![failure.clone()],
11470                base_failures: vec![failure],
11471                rerun_exhausted: true,
11472            }],
11473        }
11474    }
11475
11476    #[test]
11477    fn unrelated_ci_requires_complete_structural_evidence_for_every_failure() {
11478        let good = unrelated_ci_fixture();
11479        let red = vec!["coverage".into()];
11480        assert!(good.unrelated("a", &red));
11481        assert!(!good.unrelated("another-head", &red));
11482        assert!(!good.unrelated("a", &["coverage".into(), "test".into()]));
11483        assert!(!good.unrelated("a", &[]));
11484        for mutation in 0..8 {
11485            let mut bad = good.clone();
11486            match mutation {
11487                0 => bad.checks[0].rerun_exhausted = false,
11488                1 => bad.checks[0].base_failures.clear(),
11489                2 => bad.checks[0].head_failures.clear(),
11490                3 => bad.changed.push("tests/web_render.rs".into()),
11491                4 => bad.changed.push(".github/workflows/ci.yml".into()),
11492                5 => bad.checks[0].base_failures[0].message = "different failure".into(),
11493                6 => bad.checks.push(bad.checks[0].clone()),
11494                _ => bad.base.clear(),
11495            }
11496            assert!(!bad.unrelated("a", &red), "mutation {mutation}");
11497        }
11498    }
11499
11500    #[test]
11501    fn red_unknown_merge_state_waits_before_repair_but_never_implies_merge() {
11502        let pr = seen("a", Checks::Red, "UNKNOWN", false).pr;
11503        assert_eq!(decide(&pr, 0, 2, Duration::ZERO), Step::Wait);
11504        assert!(matches!(decide(&pr, 0, 2, CHECKS_GRACE), Step::Fix { .. }));
11505        assert!(matches!(
11506            decide(&pr, 2, 2, CHECKS_GRACE),
11507            Step::GiveUp { .. }
11508        ));
11509        let optional = CheckInfo {
11510            label: "coverage".into(),
11511            verdict: Verdict::Fail,
11512            required: Some(false),
11513            run: Some("7".into()),
11514        };
11515        assert!(rerunnable_with(std::slice::from_ref(&optional), false).is_empty());
11516        assert_eq!(
11517            rerunnable_with(&[optional], true),
11518            vec![("coverage".into(), Some("7".into()))]
11519        );
11520    }
11521
11522    #[tokio::test]
11523    async fn unrelated_ci_after_a_comment_round_does_not_charge_a_no_commit_stop() {
11524        let mut state = landing_state();
11525        let mut red = coverage_unknown();
11526        red.pr = seen("a", Checks::Red, "BLOCKED", true).pr;
11527        red.pr.failing = vec!["coverage".into()];
11528        let forge = Scripted::new(vec![red], vec![]);
11529        *forge.evidence.lock().unwrap() = Some(unrelated_ci_fixture());
11530        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11531        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11532        assert!(forge.calls().contains(&"fix"));
11533        assert!(state.land_unrelated.is_some());
11534        assert!(state.parked);
11535        assert!(
11536            !state
11537                .events
11538                .iter()
11539                .any(|e| e.message.contains("fixer produced no commit"))
11540        );
11541    }
11542
11543    fn coverage_unknown() -> Seen {
11544        let mut s = red("a", Some("7"));
11545        s.pr.blocking = Blocking::Unsaid;
11546        s.merge_state = "UNKNOWN".into();
11547        s.pr.failing = vec!["coverage".into()];
11548        s.contexts[0].label = "coverage".into();
11549        s.contexts[0].required = Some(false);
11550        s
11551    }
11552
11553    #[tokio::test]
11554    async fn run_196c_unknown_then_unstable_does_not_spend_a_fix_round() {
11555        let mut state = landing_state();
11556        let unknown = coverage_unknown();
11557        let mut unstable = unknown.clone();
11558        unstable.pr.blocking = Blocking::of("UNSTABLE");
11559        unstable.merge_state = "UNSTABLE".into();
11560        let forge = Scripted::new(vec![unknown, unstable], vec![(true, "")]);
11561        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11562        assert!(!forge.calls().contains(&"fix"));
11563        assert!(!forge.calls().contains(&"rerun"));
11564        assert_eq!(state.status, RunStatus::Merged);
11565        assert_eq!(state.pr.unwrap().round, 0);
11566    }
11567
11568    #[tokio::test]
11569    async fn run_196c_persistent_unknown_reruns_optional_once_then_parks_with_evidence() {
11570        let mut state = landing_state();
11571        let forge = Scripted::new(vec![coverage_unknown()], vec![]);
11572        *forge.evidence.lock().unwrap() = Some(unrelated_ci_fixture());
11573        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11574        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11575        assert!(!forge.calls().contains(&"fix"));
11576        assert!(state.parked);
11577        assert_eq!(state.status, RunStatus::Landing);
11578        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11579        let hold = state.land_unrelated.as_ref().unwrap();
11580        let q = ask::Questions::open().get(&hold.question).unwrap();
11581        assert!(
11582            q.actions
11583                .values()
11584                .any(|a| matches!(a, ask::ChoiceAction::Resume { .. }))
11585        );
11586        assert!(
11587            state
11588                .events
11589                .iter()
11590                .any(|e| e.message.contains("[ci-unrelated]") && e.message.contains("base-sha"))
11591        );
11592        let first = state.land_unsaid.clone();
11593        // A resume on this head neither extends UNKNOWN grace nor reruns 7.
11594        state.parked = false;
11595        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11596        assert_eq!(state.land_unsaid, first);
11597        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11598    }
11599
11600    fn red(head: &str, run: Option<&str>) -> Seen {
11601        let mut s = seen(head, Checks::Red, "BLOCKED", false);
11602        s.pr.failing = vec!["test (macos)".to_owned()];
11603        s.contexts = vec![CheckInfo {
11604            label: "test (macos)".to_owned(),
11605            verdict: Verdict::Fail,
11606            required: Some(true),
11607            run: run.map(str::to_owned),
11608        }];
11609        s
11610    }
11611
11612    const RERUN_PR: &str = "https://github.com/o/r/pull/42";
11613
11614    #[tokio::test]
11615    async fn a_flaky_red_check_is_rerun_without_a_fix_round_and_then_merges() {
11616        let mut state = landing_state();
11617        let forge = Scripted::new(
11618            vec![
11619                red("a", Some("7")),
11620                seen("a", Checks::Pending, "BLOCKED", false),
11621                seen("a", Checks::Green, "CLEAN", false),
11622            ],
11623            vec![(true, "")],
11624        );
11625        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11626        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11627        assert!(!forge.calls().contains(&"fix"));
11628        assert_eq!(state.status, RunStatus::Merged);
11629        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11630        let argvs = forge.argvs();
11631        assert_eq!(value_of(&argvs[0], "--match-head-commit"), Some("a"));
11632        assert!(
11633            state
11634                .events
11635                .iter()
11636                .any(|e| e.message.contains("test (macos)") && e.message.contains("run 7"))
11637        );
11638    }
11639
11640    #[tokio::test]
11641    async fn still_red_after_the_grace_goes_to_the_fixer_and_a_run_is_not_rerun_twice() {
11642        let mut state = landing_state();
11643        let forge = Scripted::new(
11644            vec![
11645                red("a", Some("7")),
11646                seen("a", Checks::Green, "CLEAN", false),
11647            ],
11648            vec![(true, "")],
11649        );
11650        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11651        // The red view repeats for the grace, then the fixer is asked once.
11652        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11653        assert_eq!(forge.reruns.lock().unwrap().len(), 1);
11654        let calls = forge.calls();
11655        let rerun_at = calls.iter().position(|c| *c == "rerun").unwrap();
11656        let fix_at = calls.iter().position(|c| *c == "fix");
11657        assert!(fix_at.is_none_or(|f| f > rerun_at));
11658    }
11659
11660    #[tokio::test]
11661    async fn a_failed_run_is_rerun_while_another_run_is_still_pending() {
11662        let mut state = landing_state();
11663        let mut v = red("a", Some("7"));
11664        v.pr.checks = Checks::Pending;
11665        v.contexts.push(CheckInfo {
11666            label: "slow".to_owned(),
11667            verdict: Verdict::Pending,
11668            required: Some(true),
11669            run: Some("8".to_owned()),
11670        });
11671        let forge = Scripted::new(
11672            vec![v, seen("a", Checks::Green, "CLEAN", false)],
11673            vec![(true, "")],
11674        );
11675        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11676        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11677        assert_eq!(state.status, RunStatus::Merged);
11678    }
11679
11680    #[test]
11681    fn a_run_with_a_job_still_going_is_not_rerun_yet() {
11682        let mut v = red("a", Some("7"));
11683        v.contexts.push(CheckInfo {
11684            label: "same run, still going".to_owned(),
11685            verdict: Verdict::Pending,
11686            required: Some(true),
11687            run: Some("7".to_owned()),
11688        });
11689        assert!(rerunnable(&v.contexts).is_empty());
11690    }
11691
11692    #[tokio::test]
11693    async fn the_rerun_is_made_even_when_the_fix_budget_is_spent() {
11694        let mut state = landing_state();
11695        state.config.graph.land_rounds = 0;
11696        let forge = Scripted::new(
11697            vec![
11698                red("a", Some("7")),
11699                seen("a", Checks::Green, "CLEAN", false),
11700            ],
11701            vec![(true, "")],
11702        );
11703        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11704        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11705        assert_eq!(state.status, RunStatus::Merged);
11706        assert!(!forge.calls().contains(&"fix"));
11707        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11708    }
11709
11710    #[tokio::test]
11711    async fn a_deferred_landing_fix_keeps_its_round_for_resume() {
11712        let mut state = landing_state();
11713        state.config.graph.land_rounds = 1;
11714        let forge = Scripted::new(vec![seen("a", Checks::Green, "CLEAN", true)], vec![]);
11715        *forge.fix.lock().unwrap() = Some(Fixed::Deferred);
11716        let pr = land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11717        assert_eq!(pr.state, PrLifecycle::Open);
11718        assert_eq!(state.status, RunStatus::Blocked);
11719        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11720        assert!(
11721            state.merge_decision.is_none(),
11722            "no ordinary failure handoff"
11723        );
11724        assert!(forge.argvs().is_empty(), "no merge on outage");
11725
11726        let recovered = Scripted::new(
11727            vec![
11728                seen("a", Checks::Green, "CLEAN", true),
11729                seen("b", Checks::Green, "CLEAN", false),
11730            ],
11731            vec![(true, "")],
11732        );
11733        *recovered.fix.lock().unwrap() = Some(Fixed::Committed { head: "b".into() });
11734        land_with(&mut state, RERUN_PR, &recovered).await.unwrap();
11735        assert_eq!(state.status, RunStatus::Merged);
11736        assert_eq!(state.pr.as_ref().unwrap().round, 1);
11737        assert_eq!(recovered.calls().iter().filter(|c| **c == "fix").count(), 1);
11738    }
11739
11740    #[tokio::test]
11741    async fn the_last_fix_rounds_new_head_gets_its_rerun() {
11742        let mut state = landing_state();
11743        state.config.graph.land_rounds = 1;
11744        let forge = Scripted::new(
11745            vec![
11746                seen("a", Checks::Green, "CLEAN", true),
11747                red("b", Some("7")),
11748                seen("b", Checks::Green, "CLEAN", false),
11749            ],
11750            vec![(true, "")],
11751        );
11752        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11753            head: "b".to_owned(),
11754        });
11755        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11756        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11757        assert_eq!(forge.calls().iter().filter(|c| **c == "fix").count(), 1);
11758        assert_eq!(state.pr.as_ref().unwrap().round, 1);
11759        assert_eq!(state.status, RunStatus::Merged);
11760        assert_eq!(state.land_reruns.as_ref().unwrap().head, "b");
11761        assert_eq!(
11762            value_of(&forge.argvs()[0], "--match-head-commit"),
11763            Some("b")
11764        );
11765    }
11766
11767    #[tokio::test]
11768    async fn a_failed_rerun_call_falls_through_to_the_fix_in_the_same_lap() {
11769        let mut state = landing_state();
11770        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
11771        *forge.rerun_fails.lock().unwrap() = true;
11772        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11773        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11774        assert_eq!(forge.reruns.lock().unwrap().len(), 1, "never retried");
11775        assert_eq!(
11776            forge.calls().iter().filter(|c| **c == "fix").count(),
11777            1,
11778            "{:?}",
11779            forge.calls()
11780        );
11781    }
11782
11783    #[tokio::test]
11784    async fn a_saved_rerun_record_stops_a_restart_from_rerunning() {
11785        let mut state = landing_state();
11786        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
11787        // The record was written just before the previous pass died.
11788        state.land_reruns = Some(reran("a", &[("7", *forge.clock.lock().unwrap())]));
11789        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11790        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11791        assert!(forge.reruns.lock().unwrap().is_empty());
11792    }
11793
11794    #[tokio::test]
11795    async fn the_switch_off_and_a_missing_run_id_go_straight_to_the_fixer() {
11796        let mut state = landing_state();
11797        state.config.graph.rerun_flaky_checks = false;
11798        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
11799        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11800        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11801        assert!(forge.reruns.lock().unwrap().is_empty());
11802        assert!(forge.calls().contains(&"fix"));
11803
11804        let mut state = landing_state();
11805        let forge = Scripted::new(vec![red("a", None)], vec![]);
11806        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11807        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11808        assert!(forge.reruns.lock().unwrap().is_empty());
11809        assert!(forge.calls().contains(&"fix"));
11810    }
11811
11812    fn names(xs: &[&str]) -> BTreeSet<String> {
11813        xs.iter().map(|x| (*x).to_owned()).collect()
11814    }
11815
11816    #[test]
11817    fn a_required_check_the_rollup_never_listed_is_named() {
11818        let req = names(&["build"]);
11819        let why = waiting_on("BLOCKED", &[passing("review")], Some(&req));
11820        assert!(why.contains("never reported: build"), "{why}");
11821        assert!(!why.contains("probably waiting for a review"), "{why}");
11822    }
11823
11824    #[test]
11825    fn an_unreadable_required_list_is_not_read_as_a_review_wait() {
11826        let why = waiting_on("BLOCKED", &[passing("review")], None);
11827        assert!(why.contains("could not be read"), "{why}");
11828        assert!(!why.contains("probably waiting for a review"), "{why}");
11829    }
11830
11831    #[test]
11832    fn all_required_reported_keeps_the_review_guess() {
11833        let req = names(&["build"]);
11834        let why = waiting_on("BLOCKED", &[passing("build")], Some(&req));
11835        assert!(why.contains("probably waiting for a review"), "{why}");
11836        assert!(!why.contains("never reported"), "{why}");
11837    }
11838
11839    #[test]
11840    fn required_names_match_the_rollup_ignoring_case_only() {
11841        let req = names(&["Build"]);
11842        let why = waiting_on("BLOCKED", &[passing("build")], Some(&req));
11843        assert!(!why.contains("never reported"), "{why}");
11844    }
11845
11846    #[test]
11847    fn required_contexts_are_read_from_protection_and_rulesets() {
11848        let classic = r#"{"contexts":["build"],"checks":[{"context":"lint","app_id":1}]}"#;
11849        assert_eq!(
11850            parse_classic_required(classic),
11851            Some(names(&["build", "lint"]))
11852        );
11853        let rules = r#"[{"type":"pull_request","parameters":{}},
11854            {"type":"required_status_checks","parameters":{"required_status_checks":[{"context":"test"}]}}]"#;
11855        assert_eq!(parse_ruleset_required(rules), Some(names(&["test"])));
11856        assert_eq!(parse_ruleset_required("nope"), None);
11857        assert_eq!(encode_path_segment("release/1.x"), "release%2F1.x");
11858    }
11859
11860    #[test]
11861    fn the_direct_merge_guard_needs_the_approved_head_bound_to_its_checks() {
11862        let shown = BTreeSet::new();
11863        let ok = seen("a", Checks::Green, "CLEAN", false);
11864        let guard = |s: Option<&Seen>| {
11865            direct_merge_is_safe(
11866                s,
11867                "A",
11868                &shown,
11869                0,
11870                4,
11871                Duration::ZERO,
11872                CiExpectation::Expected,
11873            )
11874        };
11875        assert!(guard(Some(&ok)));
11876        assert!(!guard(None));
11877        assert!(!guard(Some(&seen("b", Checks::Green, "CLEAN", false))));
11878        let mut stale = ok.clone();
11879        stale.rollup_head = "old".to_owned();
11880        assert!(!guard(Some(&stale)));
11881        assert!(!guard(Some(&seen("a", Checks::Pending, "BLOCKED", false))));
11882        assert!(!guard(Some(&merged_view("a"))));
11883    }
11884
11885    #[test]
11886    fn the_rollup_node_carries_whether_each_check_is_required() {
11887        let node = node_json("new", "SUCCESS", false)
11888            .replace(r#""name":"ci","#, r#""name":"ci","isRequired":true,"#);
11889        let s = seen_from(&view_json("new"), Some(&node)).unwrap();
11890        assert_eq!(s.contexts.len(), 1);
11891        assert_eq!(s.contexts[0].required, Some(true));
11892        let s = seen_from(&view_json("new"), Some(&node_json("new", "SUCCESS", false))).unwrap();
11893        assert_eq!(s.contexts[0].required, None);
11894    }
11895
11896    #[tokio::test]
11897    async fn a_resume_that_cannot_disable_a_recorded_arm_stops_and_keeps_the_record() {
11898        let mut state = landing_state();
11899        state.land_armed_head = Some("a".to_owned());
11900        let forge = Scripted::new(
11901            vec![seen("a", Checks::Green, "CLEAN", true)],
11902            vec![(false, "disable exploded")],
11903        );
11904        land_with(&mut state, URL, &forge).await.unwrap();
11905        assert!(!forge.calls().contains(&"fix"));
11906        assert_eq!(state.status, RunStatus::Blocked);
11907        assert_eq!(state.land_armed_head.as_deref(), Some("a"));
11908        let why = state.merge.as_ref().unwrap().detail.clone();
11909        assert!(why.contains("disable exploded"), "{why}");
11910    }
11911
11912    /// Create a cross-platform fake `gh` executable in `dir` backed by exact
11913    /// fixture files, avoiding shell quoting differences and global `PATH`
11914    /// mutation.
11915    pub(crate) fn fake_gh_script(
11916        dir: &Path,
11917        name: &str,
11918        stdout: &str,
11919        stderr: &str,
11920        exit_code: i32,
11921    ) -> PathBuf {
11922        let out_path = dir.join(format!("{name}.stdout"));
11923        let err_path = dir.join(format!("{name}.stderr"));
11924        std::fs::write(&out_path, stdout).unwrap();
11925        std::fs::write(&err_path, stderr).unwrap();
11926        #[cfg(windows)]
11927        {
11928            let script = dir.join(format!("{name}.cmd"));
11929            let mut body = String::from("@echo off\r\n");
11930            if !stdout.is_empty() {
11931                body.push_str(&format!("type \"{}\"\r\n", out_path.display()));
11932            }
11933            if !stderr.is_empty() {
11934                body.push_str(&format!("type \"{}\" 1>&2\r\n", err_path.display()));
11935            }
11936            body.push_str(&format!("exit /b {exit_code}\r\n"));
11937            std::fs::write(&script, body).unwrap();
11938            script
11939        }
11940        #[cfg(unix)]
11941        {
11942            use std::os::unix::fs::PermissionsExt as _;
11943            let quote = |p: &Path| format!("'{}'", p.display().to_string().replace('\'', "'\\''"));
11944            let script = dir.join(name);
11945            let mut body = String::from("#!/bin/sh\n");
11946            if !stdout.is_empty() {
11947                body.push_str(&format!("cat {}\n", quote(&out_path)));
11948            }
11949            if !stderr.is_empty() {
11950                body.push_str(&format!("cat {} >&2\n", quote(&err_path)));
11951            }
11952            body.push_str(&format!("exit {exit_code}\n"));
11953            let status = std::process::Command::new("sh")
11954                .args(["-c", "printf '%s' \"$2\" > \"$1\"", "fixture"])
11955                .arg(&script)
11956                .arg(&body)
11957                .status()
11958                .unwrap();
11959            assert!(status.success());
11960            std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
11961            script
11962        }
11963    }
11964
11965    #[test]
11966    fn gh_output_combined_preserves_and_separates_both_streams() {
11967        let mk = |ok, stdout: &str, stderr: &str| GhOutput {
11968            ok,
11969            stdout: stdout.into(),
11970            stderr: stderr.into(),
11971        };
11972        assert_eq!(mk(true, "  ", "\n").combined(), "");
11973        assert_eq!(mk(true, "  only out \n", " \t ").combined(), "only out");
11974        assert_eq!(mk(false, "", "  only err\n").combined(), "only err");
11975        assert_eq!(
11976            mk(false, "{\"status\":\"404\"}", "gh: Not Found (HTTP 404)\n").combined(),
11977            "{\"status\":\"404\"}\ngh: Not Found (HTTP 404)"
11978        );
11979    }
11980
11981    #[tokio::test]
11982    async fn gh_separates_json_stdout_from_stderr_diagnostics() {
11983        let tmp = tempfile::tempdir().unwrap();
11984        let hint = "hint: to listen to pull request events, run `gh pr view --web`\n";
11985        let valid_view = r#"{"url":"https://github.com/example/repo/pull/1","number":1,"state":"OPEN","title":"feat: test","reviews":[],"comments":[],"mergeStateStatus":"CLEAN","headRefOid":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","baseRefName":"main"}"#;
11986        let valid_list = r#"[{"number":1,"url":"https://github.com/example/repo/pull/1","title":"feat: test","baseRefName":"main","isCrossRepository":false}]"#;
11987
11988        // Valid JSON stdout + nonempty stderr hint on exit 0: structured reads
11989        // parse stdout cleanly while stderr remains available via `combined()`.
11990        let ok_view = fake_gh_script(tmp.path(), "ok-view", &format!("{valid_view}\n"), hint, 0);
11991        let out = gh_with(&ok_view, tmp.path(), &["pr".into(), "view".into()])
11992            .await
11993            .unwrap();
11994        assert!(out.ok);
11995        assert_eq!(parse_pr(&out.stdout).unwrap().state, PrLifecycle::Open);
11996        assert!(out.stderr.contains("listen to pull request events"));
11997        assert!(out.combined().contains("listen to pull request events"));
11998        assert!(out.combined().contains("feat: test"));
11999
12000        let ok_list = fake_gh_script(tmp.path(), "ok-list", &format!("{valid_list}\n"), hint, 0);
12001        assert_eq!(
12002            find_open_pr_with(&ok_list, tmp.path(), "magi/task-t", "main")
12003                .await
12004                .unwrap(),
12005            OpenPr::One {
12006                url: "https://github.com/example/repo/pull/1".into(),
12007                title: "feat: test".into(),
12008            }
12009        );
12010
12011        // Malformed stdout with trailing characters still fails strict JSON parsing.
12012        let malformed = fake_gh_script(
12013            tmp.path(),
12014            "malformed",
12015            &format!("{valid_view}\ntrailing garbage\n"),
12016            "",
12017            0,
12018        );
12019        let out = gh_with(&malformed, tmp.path(), &["pr".into(), "view".into()])
12020            .await
12021            .unwrap();
12022        assert!(out.ok);
12023        let err = parse_pr(&out.stdout).unwrap_err();
12024        assert!(
12025            format!("{err:#}").contains("trailing characters"),
12026            "{err:#}"
12027        );
12028
12029        // Empty stdout + nonempty stderr on exit 0 never substitutes stderr.
12030        let empty = fake_gh_script(tmp.path(), "empty", "", hint, 0);
12031        let out = gh_with(&empty, tmp.path(), &["pr".into(), "view".into()])
12032            .await
12033            .unwrap();
12034        assert!(out.ok);
12035        assert!(out.stdout.trim().is_empty());
12036        assert!(parse_pr(&out.stdout).is_err());
12037
12038        // Non-zero exit with valid JSON on stdout and error on stderr reports
12039        // failure and preserves both streams in `combined()`.
12040        let failed = fake_gh_script(
12041            tmp.path(),
12042            "failed",
12043            &format!("{valid_view}\n"),
12044            "gh: HTTP 404 Not Found\n",
12045            1,
12046        );
12047        let out = gh_with(&failed, tmp.path(), &["pr".into(), "view".into()])
12048            .await
12049            .unwrap();
12050        assert!(!out.ok);
12051        let diag = out.combined();
12052        assert!(diag.contains("HTTP 404 Not Found"), "{diag}");
12053        assert!(diag.contains("feat: test"), "{diag}");
12054        let list_err = find_open_pr_with(&failed, tmp.path(), "magi/task-t", "main")
12055            .await
12056            .unwrap_err()
12057            .to_string();
12058        assert!(list_err.contains("HTTP 404 Not Found"), "{list_err}");
12059    }
12060}