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()
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
1775            .list()
1776            .into_iter()
1777            .filter(|q| q.run == state.id && q.node == APPROVAL_NODE && q.status.open())
1778        {
1779            let why =
1780                "the pull request head or operator decision changed; asked again for approval";
1781            if let Err(e) = store.update(&stale.id, |q| {
1782                q.abandon(why);
1783                Ok(())
1784            }) {
1785                tracing::warn!("could not retire the superseded approval question: {e:#}");
1786            }
1787        }
1788    }
1789
1790    let q = match reusable {
1791        Some(mut q) => {
1792            if upgrade_repair_choice(&mut q, state) {
1793                q = store
1794                    .update(&q.id, |current| {
1795                        upgrade_repair_choice(current, state);
1796                        Ok(())
1797                    })?
1798                    .0;
1799            }
1800            q
1801        }
1802        None => {
1803            let worktree = match state.winner() {
1804                Some(w) => w.worktree.clone(),
1805                None => state.repo.clone(),
1806            };
1807            // The diff is built from the commit being approved, not from the
1808            // branch name, which may already point somewhere else.
1809            let head = if head.is_empty() {
1810                state
1811                    .winner()
1812                    .map_or_else(|| "HEAD".to_owned(), |w| w.branch.clone())
1813            } else {
1814                head.to_owned()
1815            };
1816            // The diff is against what the remote's base holds, never the
1817            // local branch of that name; unreadable means less evidence.
1818            let remote = &state.config.merge.remote;
1819            let tracking = format!("{remote}/{}", state.base_branch);
1820            let base = if git::rev_exists(&worktree, &tracking).await {
1821                tracking
1822            } else {
1823                String::new()
1824            };
1825            let range = format!("{base}...{head}");
1826            // A failed `git` must not decide the merge: the panel degrades to
1827            // less evidence and the owner still chooses. Merging because the
1828            // diff could not be read would be the worst of both.
1829            let numstat = if base.is_empty() {
1830                String::new()
1831            } else {
1832                git::git_raw(&worktree, &["diff", "--numstat", "-M", &range])
1833                    .await
1834                    .map(|o| o.stdout)
1835                    .unwrap_or_default()
1836            };
1837            let diff = if base.is_empty() {
1838                String::new()
1839            } else {
1840                git::diff(&worktree, &base, &head).await.unwrap_or_default()
1841            };
1842            let commits: Vec<String> = if base.is_empty() {
1843                Vec::new()
1844            } else {
1845                git::git_raw(
1846                    &worktree,
1847                    &[
1848                        "log",
1849                        "--reverse",
1850                        "--format=%s",
1851                        &format!("{base}..{head}"),
1852                    ],
1853                )
1854                .await
1855                .map(|o| o.stdout)
1856                .unwrap_or_default()
1857                .lines()
1858                .filter(|l| !l.trim().is_empty())
1859                .map(str::to_owned)
1860                .collect()
1861            };
1862
1863            let w = words(&state.config.graph.language);
1864            let html = approval_panel(state, pr, &numstat, &diff, &commits, subject);
1865            let mut fresh = ask::Question::new(
1866                state.id.clone(),
1867                APPROVAL_NODE.to_owned(),
1868                "land".to_owned(),
1869                w.approval_summary(pr.number, subject),
1870                format!(
1871                    "{}\n\n{}",
1872                    approval_evidence(state),
1873                    w.approval_detail(&pr.url, &state.base_branch, subject, contested)
1874                ),
1875                approval_choices(state),
1876            );
1877            fresh.merge_target = Some(crate::merge_decision::Target {
1878                pr: pr.url.clone(),
1879                head: head.clone(),
1880                language: state.config.graph.language.clone(),
1881            });
1882            if fresh.choices.iter().any(|c| c == REPAIR) {
1883                fresh.actions.insert(
1884                    REPAIR.to_owned(),
1885                    ask::ChoiceAction::Resume {
1886                        run: state.id.clone(),
1887                    },
1888                );
1889                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.");
1890            }
1891            for choice in fresh.choices.clone() {
1892                if crate::merge_decision::stops(&choice)
1893                    && choice != HOLD
1894                    && choice != crate::merge_decision::DISMISS
1895                {
1896                    fresh.actions.insert(
1897                        choice,
1898                        ask::ChoiceAction::Resume {
1899                            run: state.id.clone(),
1900                        },
1901                    );
1902                }
1903            }
1904            store
1905                .put_panel(&mut fresh, &html, &[])
1906                .context("write the merge approval panel")?;
1907            store
1908                .put_executable(&mut fresh)
1909                .context("file the merge approval question")?;
1910            state.land_approval = Some(LandApproval {
1911                question: fresh.id.clone(),
1912                head: head.clone(),
1913            });
1914            state.event(
1915                "land",
1916                format!("asking for merge approval ({})", fresh.short()),
1917            );
1918            state.save()?;
1919            if let Err(e) = ask::notify(&state.config.notify, &fresh).await {
1920                // A broken webhook is not a reason to lose the merge: the
1921                // question is already on disk and the web UI already shows
1922                // it, so the operator still has a way in.
1923                tracing::warn!(
1924                    "could not notify about merge approval question {}: {e:#} - \
1925                     the web UI is the only surface for it now",
1926                    fresh.short()
1927                );
1928            }
1929            fresh
1930        }
1931    };
1932
1933    Ok(match q.status {
1934        ask::QuestionStatus::Open => ApprovalGate::Pending,
1935        // Nobody answered before `state.config.graph.answer_timeout` passed,
1936        // or the question was closed with no decision recorded underneath
1937        // this run - either way there is nothing left to wait on.
1938        ask::QuestionStatus::Abandoned => ApprovalGate::Held,
1939        // The merge gate does not speak `--thread`: an owner who talked back
1940        // instead of choosing never reaches `Answered`, so this arm only
1941        // ever sees an actual decision.
1942        ask::QuestionStatus::Answered => match approval(q.resolution().as_deref()) {
1943            Approval::Merge => ApprovalGate::Approved,
1944            Approval::Repair if !state.reviews.is_empty() => {
1945                if !state.merge_repairs.iter().any(|r| r.question == q.id) {
1946                    state.merge_repairs.push(crate::run::MergeRepair {
1947                        question: q.id.clone(),
1948                        head: head.to_owned(),
1949                        pr: pr.url.clone(),
1950                        reviews: state.reviews.clone(),
1951                        gate: state.gate.clone(),
1952                        gate_head: state.gate_head.clone(),
1953                        gate_fixes: state.gate_fixes.clone(),
1954                        pre_gate: state.pre_gate.clone(),
1955                        phase: crate::run::MergeRepairPhase::Requested,
1956                        failure: None,
1957                    });
1958                    state.land_approval = None;
1959                    state.event(
1960                        "repair",
1961                        "owner requested fix findings and re-review; merge is not approved",
1962                    );
1963                    state.save()?;
1964                }
1965                ApprovalGate::Repair
1966            }
1967            Approval::Repair | Approval::Hold => ApprovalGate::Held,
1968        },
1969    })
1970}
1971
1972/// Fold a rollup's entries into one verdict plus the failing checks' labels.
1973/// No I/O. An empty rollup is `Unknown`, never green.
1974fn rollup_verdict(rollup: &[GhCheck]) -> (Checks, Vec<String>) {
1975    let mut failing = Vec::new();
1976    let mut pending = false;
1977    let mut unknown = false;
1978    for check in rollup {
1979        match check.verdict() {
1980            Verdict::Pass => {}
1981            Verdict::Pending => pending = true,
1982            Verdict::Fail => failing.push(check.label()),
1983            Verdict::Unknown => unknown = true,
1984        }
1985    }
1986    let checks = if rollup.is_empty() {
1987        Checks::Unknown
1988    } else if pending {
1989        Checks::Pending
1990    } else if !failing.is_empty() {
1991        Checks::Red
1992    } else if unknown {
1993        Checks::Unknown
1994    } else {
1995        Checks::Green
1996    };
1997    (checks, failing)
1998}
1999
2000/// Parse `gh pr view --json url,number,state,statusCheckRollup,reviews,comments`
2001/// output into a [`PrState`]. No I/O.
2002pub fn parse_pr(json: &str) -> Result<PrState> {
2003    let raw: GhPr = serde_json::from_str(json).context("parse `gh pr view --json ...` output")?;
2004    let state = match raw.state.to_ascii_uppercase().as_str() {
2005        "OPEN" => PrLifecycle::Open,
2006        "MERGED" => PrLifecycle::Merged,
2007        "CLOSED" => PrLifecycle::Closed,
2008        other => bail!("unknown pull request state `{other}`"),
2009    };
2010
2011    let (checks, failing) = rollup_verdict(&raw.status_check_rollup);
2012
2013    let mut review_comments = Vec::new();
2014    for r in raw.reviews {
2015        push_if_outstanding(
2016            &mut review_comments,
2017            ReviewComment {
2018                author: r.author.login,
2019                path: None,
2020                line: None,
2021                body: r.body,
2022            },
2023        );
2024    }
2025    for c in raw.comments {
2026        push_if_outstanding(
2027            &mut review_comments,
2028            ReviewComment {
2029                author: c.author.login,
2030                path: None,
2031                line: None,
2032                body: c.body,
2033            },
2034        );
2035    }
2036
2037    Ok(PrState {
2038        url: raw.url,
2039        number: raw.number,
2040        state,
2041        checks,
2042        failing,
2043        review_comments,
2044        blocking: Blocking::of(&raw.merge_state_status),
2045    })
2046}
2047
2048/// One rollup entry as the release watcher reads it.
2049#[derive(Debug, Clone, PartialEq, Eq)]
2050pub(crate) struct CheckView {
2051    pub name: String,
2052    pub verdict: Verdict,
2053    /// Workflow run behind the check, when its url names one.
2054    pub run: Option<String>,
2055    pub url: Option<String>,
2056}
2057
2058/// A pull request's lifecycle, head commit and per-check verdicts, without
2059/// [`rollup_verdict`]'s aggregation (a pending check anywhere hides a failure
2060/// from it, which is exactly what the release watcher must not inherit).
2061#[derive(Debug, Clone, PartialEq, Eq)]
2062pub(crate) struct RollupView {
2063    pub url: String,
2064    pub number: u64,
2065    pub state: PrLifecycle,
2066    pub head: String,
2067    pub checks: Vec<CheckView>,
2068}
2069
2070/// Parse `gh pr view --json url,number,state,headRefOid,statusCheckRollup`
2071/// output. No I/O.
2072pub(crate) fn parse_rollup(json: &str) -> Result<RollupView> {
2073    let raw: GhPr = serde_json::from_str(json).context("parse `gh pr view --json ...` output")?;
2074    let state = match raw.state.to_ascii_uppercase().as_str() {
2075        "OPEN" => PrLifecycle::Open,
2076        "MERGED" => PrLifecycle::Merged,
2077        "CLOSED" => PrLifecycle::Closed,
2078        other => bail!("unknown pull request state `{other}`"),
2079    };
2080    let checks = raw
2081        .status_check_rollup
2082        .iter()
2083        .map(|c| CheckView {
2084            name: c.label(),
2085            verdict: c.verdict(),
2086            run: c.url().and_then(run_of),
2087            url: c.url().map(str::to_owned),
2088        })
2089        .collect();
2090    Ok(RollupView {
2091        url: raw.url,
2092        number: raw.number,
2093        state,
2094        head: raw.head_ref_oid,
2095        checks,
2096    })
2097}
2098
2099/// Read just a pull request's lifecycle state - open, merged, or closed -
2100/// with none of the checks/reviews/comments [`land`] itself needs to decide
2101/// what to do next.
2102///
2103/// For a caller that only ever wants one fact and must not risk anything
2104/// else: `magi fold --merged` uses this to confirm a URL the operator hands
2105/// it is actually a merged pull request *before* touching a run's state, so a
2106/// typo or a still-open PR fails loudly instead of quietly recording a merge
2107/// that never happened.
2108pub async fn lifecycle(repo: &Path, pr_url: &str) -> Result<PrLifecycle> {
2109    let view = gh(
2110        repo,
2111        &[
2112            "pr".to_owned(),
2113            "view".to_owned(),
2114            pr_url.to_owned(),
2115            "--json".to_owned(),
2116            "state".to_owned(),
2117        ],
2118    )
2119    .await?;
2120    if !view.0 {
2121        bail!("gh pr view {pr_url}: {}", view.1);
2122    }
2123    // `parse_pr` reads every other field of `GhPr` as its serde default
2124    // (empty string, empty vec, zero) when this narrower `--json` selection
2125    // does not carry them - harmless, since only `.state` is read back.
2126    Ok(parse_pr(&view.1)?.state)
2127}
2128
2129/// A pull request the operator merged outside of `land::land`'s own loop,
2130/// found by asking GitHub about the run's own winning branch rather than
2131/// requiring the operator to go and find the URL themselves.
2132#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
2133pub struct ExternalMerge {
2134    /// The pull request's URL, ready to hand to [`correct_manual_merge`].
2135    pub url: String,
2136    /// The pull request's number.
2137    pub number: u64,
2138}
2139
2140#[derive(Debug, Deserialize)]
2141#[serde(rename_all = "camelCase")]
2142struct GhMergedPr {
2143    url: String,
2144    number: u64,
2145    merged_at: String,
2146    base_ref_name: String,
2147}
2148
2149/// Pure half of [`find_external_merge`]: given the raw `gh pr list --head
2150/// <branch> --state merged --json url,number,mergedAt,baseRefName` output,
2151/// decide whether exactly one of the pull requests it lists could actually
2152/// be *this* run's.
2153///
2154/// A branch name alone does not prove it: [`RunState::branch_for`] derives it
2155/// from the run's own short id, so a collision with some other, unrelated
2156/// task's merged pull request from a same-named branch is rare but not
2157/// impossible once branches are deleted and ids run out. Filtering on
2158/// `base_ref_name` (the branch this run actually targets) and `merged_at`
2159/// (which cannot predate the run itself) rules that case out. More than one
2160/// survivor is exactly as uninformative as zero — something this run cannot
2161/// tell apart from another — so only a unique survivor is returned.
2162fn pick_merged_pr(
2163    json: &str,
2164    base_branch: &str,
2165    created_at: Timestamp,
2166) -> Result<Option<ExternalMerge>> {
2167    let raw: Vec<GhMergedPr> =
2168        serde_json::from_str(json).context("parse `gh pr list ... --json ...` output")?;
2169    let mut matches: Vec<ExternalMerge> = Vec::new();
2170    for pr in raw {
2171        if pr.base_ref_name != base_branch {
2172            continue;
2173        }
2174        let Ok(merged_at) = pr.merged_at.parse::<Timestamp>() else {
2175            continue;
2176        };
2177        if merged_at < created_at {
2178            continue;
2179        }
2180        matches.push(ExternalMerge {
2181            url: pr.url,
2182            number: pr.number,
2183        });
2184    }
2185    if matches.len() == 1 {
2186        Ok(matches.pop())
2187    } else {
2188        Ok(None)
2189    }
2190}
2191
2192/// What `gh pr list --head <branch> --base <base> --state open` found.
2193#[derive(Debug, Clone, PartialEq, Eq)]
2194pub enum OpenPr {
2195    /// Nothing open: the caller creates one.
2196    None,
2197    /// Exactly one: the caller adopts it instead of creating a second.
2198    One {
2199        /// The pull request's URL.
2200        url: String,
2201        /// Its current title.
2202        title: String,
2203    },
2204    /// More than one: magi does not pick between them.
2205    Many(Vec<String>),
2206}
2207
2208#[derive(Debug, Deserialize)]
2209#[serde(rename_all = "camelCase")]
2210struct GhOpenPr {
2211    // `url` and `baseRefName` are required: a record missing either must be a
2212    // parse error, not a pull request that silently fails the base filter and
2213    // reads as "none open" (which would go on to create a duplicate).
2214    url: String,
2215    #[serde(default)]
2216    title: String,
2217    base_ref_name: String,
2218    // A fork's branch of the same name is not the task head; `gh pr list --head`
2219    // matches by branch name alone, so the filter has to be ours.
2220    #[serde(default)]
2221    is_cross_repository: bool,
2222}
2223
2224/// Pure half of [`find_open_pr`]: classify the raw `--json
2225/// number,url,title,baseRefName` output. Entries whose base is not `base` are
2226/// dropped even though the query already filtered on it, so a stub or an old
2227/// `gh` that ignores `--base` cannot get a pull request into the wrong branch
2228/// adopted.
2229pub fn pick_open_pr(json: &str, base: &str) -> Result<OpenPr> {
2230    let raw: Vec<GhOpenPr> =
2231        serde_json::from_str(json).context("parse `gh pr list ... --json ...` output")?;
2232    let mut hits: Vec<GhOpenPr> = raw
2233        .into_iter()
2234        .filter(|p| p.base_ref_name == base && !p.is_cross_repository)
2235        .collect();
2236    Ok(match hits.len() {
2237        0 => OpenPr::None,
2238        1 => {
2239            let p = hits.remove(0);
2240            OpenPr::One {
2241                url: p.url,
2242                title: p.title,
2243            }
2244        }
2245        _ => OpenPr::Many(hits.into_iter().map(|p| p.url).collect()),
2246    })
2247}
2248
2249/// Open pull requests whose head is `branch` and whose base is `base`. A
2250/// failing `gh` is an error carrying its own output, never "none": guessing
2251/// there is how a duplicate gets created.
2252pub async fn find_open_pr(repo: &Path, branch: &str, base: &str) -> Result<OpenPr> {
2253    let (ok, out) = gh(
2254        repo,
2255        &[
2256            "pr".to_owned(),
2257            "list".to_owned(),
2258            "--head".to_owned(),
2259            branch.to_owned(),
2260            "--base".to_owned(),
2261            base.to_owned(),
2262            "--state".to_owned(),
2263            "open".to_owned(),
2264            "--json".to_owned(),
2265            "number,url,title,baseRefName,isCrossRepository".to_owned(),
2266        ],
2267    )
2268    .await?;
2269    if !ok {
2270        bail!("gh pr list failed: {out}");
2271    }
2272    pick_open_pr(&out, base)
2273}
2274
2275#[derive(Debug, Deserialize)]
2276#[serde(rename_all = "camelCase")]
2277struct GhPrHead {
2278    head_ref_name: String,
2279    base_ref_name: String,
2280    state: String,
2281    // Required, like `GhOpenPr`'s fields: a record that cannot say whether the
2282    // head lives in a fork must be a parse error, never "same repository".
2283    is_cross_repository: bool,
2284    // Required too: it is what ties the pull request to the commits that were
2285    // actually proven to be on the base.
2286    head_ref_oid: String,
2287}
2288
2289/// Why [`closable`] said no, and whether asking again later could say yes.
2290#[derive(Debug, Clone, PartialEq, Eq)]
2291pub struct Refusal {
2292    /// A later attempt may succeed (the head moved, the view was unreadable);
2293    /// `false` means this pull request is simply not the run's to close.
2294    pub retry: bool,
2295    /// What was wrong.
2296    pub why: String,
2297}
2298
2299impl Refusal {
2300    fn final_(why: String) -> Self {
2301        Self { retry: false, why }
2302    }
2303}
2304
2305/// Pure half of [`close_superseded_pr`]: read `gh pr view --json
2306/// headRefName,baseRefName,state,isCrossRepository` and say whether closing
2307/// is safe, `Err` carrying the reason when it is not.
2308///
2309/// Closing is outward-facing, so every property is checked on what the forge
2310/// says now, not on what magi recorded: the head must be exactly `branch` in
2311/// this repository (a fork's branch of the same name is somebody else's), the
2312/// base must be `base`, and the pull request must still be open.
2313pub fn closable(
2314    json: &str,
2315    branch: &str,
2316    base: &str,
2317    verified: &[String],
2318) -> std::result::Result<(), Refusal> {
2319    let pr: GhPrHead = serde_json::from_str(json).map_err(|e| Refusal {
2320        retry: true,
2321        why: format!("could not read the pull request ({e})"),
2322    })?;
2323    if pr.head_ref_name != branch {
2324        return Err(Refusal::final_(format!(
2325            "its head is `{}`, not this run's `{branch}`",
2326            pr.head_ref_name
2327        )));
2328    }
2329    if pr.is_cross_repository {
2330        return Err(Refusal::final_("its head lives in a fork".to_owned()));
2331    }
2332    if pr.base_ref_name != base {
2333        return Err(Refusal::final_(format!(
2334            "it targets `{}`, not `{base}`",
2335            pr.base_ref_name
2336        )));
2337    }
2338    if !pr.state.eq_ignore_ascii_case("open") {
2339        return Err(Refusal::final_(format!(
2340            "it is already {}",
2341            pr.state.to_ascii_lowercase()
2342        )));
2343    }
2344    // Last, so a pull request that is not this run's at all is reported as
2345    // such. A head that is this branch but not a commit checked against the
2346    // base (somebody pushed since) may well get checked next time: retry.
2347    if !verified.contains(&pr.head_ref_oid) {
2348        return Err(Refusal {
2349            retry: true,
2350            why: format!(
2351                "its head {} is not a commit this run checked against the base",
2352                crate::already::short_sha(&pr.head_ref_oid)
2353            ),
2354        });
2355    }
2356    Ok(())
2357}
2358
2359/// Does `remote` point at something a forge could host - a URL or an scp-style
2360/// `user@host:path` - rather than a filesystem path or nothing at all? Judged
2361/// from the URL alone, so it answers the same on every machine, whatever `gh`
2362/// happens to be installed or logged in to.
2363async fn remote_is_forge(repo: &Path, remote: &str) -> bool {
2364    let Ok(url) = git::git(repo, &["remote", "get-url", remote]).await else {
2365        return false;
2366    };
2367    is_forge_url(url.trim())
2368}
2369
2370fn is_forge_url(url: &str) -> bool {
2371    url.contains("://") && !url.starts_with("file://")
2372        || url
2373            .split_once(':')
2374            .is_some_and(|(host, _)| host.contains('@') && !host.contains(['/', '\\']))
2375}
2376
2377/// Does this `gh` failure mean there is no GitHub to ask, as opposed to a
2378/// request that failed?
2379fn forge_unavailable(message: &str) -> bool {
2380    message.contains("known GitHub host") || message.contains("spawn gh")
2381}
2382
2383/// The comment left on a pull request closed because its change is already on
2384/// the base.
2385pub fn superseded_comment(base: &str, evidence: &crate::already::Evidence) -> String {
2386    let how = match evidence.proof {
2387        crate::already::Proof::PatchId => format!(
2388            "carried by commit {} on `{base}` with the same patch",
2389            evidence.names()
2390        ),
2391        crate::already::Proof::Ancestry => {
2392            format!("already in the history of `{base}` as {}", evidence.names())
2393        }
2394        crate::already::Proof::Tree => format!(
2395            "already part of `{base}` (merging this branch changes nothing at {})",
2396            crate::already::short_sha(&evidence.tip)
2397        ),
2398    };
2399    format!(
2400        "Closing: everything this branch adds is {how}, so there is nothing left to \
2401         land. This pull request was closed automatically after that was verified; \
2402         reopen it if you disagree."
2403    )
2404}
2405
2406/// Close the open pull request for `branch`, if there is one and it is
2407/// provably this run's, with a comment naming what supersedes it. `Ok(Ok(url))` is
2408/// the URL closed; `Ok(Err(why))` is a final "nothing to close" (no pull request,
2409/// not this run's, no forge); `Err` is anything a later attempt could resolve (a
2410/// failed `gh` call, a head that moved since it was checked), which the caller
2411/// must not treat as settled.
2412///
2413/// The recorded `state.pr` is preferred, else the forge is asked for an open
2414/// pull request on `branch`; either way the candidate is re-read and passed
2415/// through [`closable`] before anything is written; `verified` lists the
2416/// commits proven to be on the base, and the pull request's head must be one.
2417pub async fn close_superseded_pr(
2418    state: &mut RunState,
2419    branch: &str,
2420    evidence: &crate::already::Evidence,
2421    verified: &[String],
2422) -> Result<std::result::Result<String, String>> {
2423    let repo = state.repo.clone();
2424    let base = state.base_branch.clone();
2425    let url = match state.pr.as_ref().filter(|p| p.state == "open") {
2426        Some(p) => p.url.clone(),
2427        // No recorded pull request. A forge that cannot be asked at all (no
2428        // GitHub remote, no `gh`) says nothing about this run, so that is
2429        // "none found"; any other lookup failure is an error, because "could
2430        // not look" is not "nothing there" and the caller must retry.
2431        None if !remote_is_forge(&repo, &state.config.merge.remote).await => {
2432            return Ok(Err(
2433                "the remote is not a forge, so there is no pull request".to_owned(),
2434            ));
2435        }
2436        None => match find_open_pr(&repo, branch, &base).await {
2437            Err(e) if forge_unavailable(&format!("{e:#}")) => {
2438                return Ok(Err(format!("no forge to ask: {e:#}")));
2439            }
2440            Err(e) => return Err(e),
2441            Ok(OpenPr::One { url, .. }) => url,
2442            Ok(OpenPr::None) => return Ok(Err("no open pull request".to_owned())),
2443            Ok(OpenPr::Many(urls)) => {
2444                return Ok(Err(format!(
2445                    "{} open pull requests name it; not choosing between them",
2446                    urls.len()
2447                )));
2448            }
2449        },
2450    };
2451    let (ok, view) = gh(
2452        &repo,
2453        &[
2454            "pr".to_owned(),
2455            "view".to_owned(),
2456            url.clone(),
2457            "--json".to_owned(),
2458            "headRefName,headRefOid,baseRefName,state,isCrossRepository".to_owned(),
2459        ],
2460    )
2461    .await?;
2462    if !ok {
2463        bail!("gh pr view {url} failed: {view}");
2464    }
2465    if let Err(refusal) = closable(&view, branch, &base, verified) {
2466        // A pull request whose head cannot be tied to what was proven is not
2467        // one to walk away from: the caller keeps the run resumable.
2468        if refusal.retry {
2469            bail!("left {url} open: {}", refusal.why);
2470        }
2471        return Ok(Err(format!("left {url} open: {}", refusal.why)));
2472    }
2473    let (ok, out) = gh(
2474        &repo,
2475        &[
2476            "pr".to_owned(),
2477            "close".to_owned(),
2478            url.clone(),
2479            "--comment".to_owned(),
2480            superseded_comment(&base, evidence),
2481        ],
2482    )
2483    .await?;
2484    if !ok {
2485        bail!("gh pr close {url} failed: {out}");
2486    }
2487    if let Some(p) = state.pr.as_mut().filter(|p| p.url == url) {
2488        p.state = "closed".to_owned();
2489    }
2490    Ok(Ok(url))
2491}
2492
2493/// `gh pr edit <url> --title <title>`, for an adopted pull request whose title
2494/// differs from the one this run computed. Only the title: the body may have
2495/// been edited by the owner and cannot be compared.
2496pub async fn set_pr_title(state: &mut RunState, repo: &Path, url: &str, title: &str) -> Result<()> {
2497    let (title, _) = crate::github_text::prepare(state, title, "");
2498    edit_pr_title(repo, url, &title).await
2499}
2500
2501/// [`set_pr_title`] for a title the owner explicitly chose to post unmodified
2502/// (`github_text::POST_ORIGINAL` or `github_text::USE_REWRITE`): the posting
2503/// gate is skipped on purpose.
2504pub async fn set_pr_title_verbatim(repo: &Path, url: &str, title: &str) -> Result<()> {
2505    edit_pr_title(repo, url, title).await
2506}
2507
2508/// Post both fields of the owner's chosen rewrite to an adopted pull request,
2509/// unmodified and without the posting gate.
2510pub async fn set_pr_text_verbatim(repo: &Path, url: &str, title: &str, body: &str) -> Result<()> {
2511    let (ok, _) = gh(
2512        repo,
2513        &[
2514            "pr".to_owned(),
2515            "edit".to_owned(),
2516            url.to_owned(),
2517            "--title".to_owned(),
2518            title.to_owned(),
2519            "--body".to_owned(),
2520            body.to_owned(),
2521        ],
2522    )
2523    .await
2524    .map_err(|_| anyhow::anyhow!("could not run gh pr edit for the chosen rewrite"))?;
2525    if !ok {
2526        // Command output may echo the chosen text; keep it out of run events.
2527        bail!("gh pr edit failed while posting the chosen rewrite");
2528    }
2529    Ok(())
2530}
2531
2532async fn edit_pr_title(repo: &Path, url: &str, title: &str) -> Result<()> {
2533    let (ok, out) = gh(
2534        repo,
2535        &[
2536            "pr".to_owned(),
2537            "edit".to_owned(),
2538            url.to_owned(),
2539            "--title".to_owned(),
2540            title.to_owned(),
2541        ],
2542    )
2543    .await?;
2544    if !ok {
2545        bail!("gh pr edit failed: {out}");
2546    }
2547    Ok(())
2548}
2549
2550/// Ask GitHub whether this run's winning candidate branch was actually merged
2551/// somewhere `land::land`'s own loop never saw — the gap `magi fold
2552/// --merged` exists to close, minus the operator having to find the URL by
2553/// hand.
2554///
2555/// `Ok(None)` covers every case where nothing can be said with confidence: no
2556/// winner decided yet (nothing to check a branch for), no merged pull request
2557/// found, or [`pick_merged_pr`] found more than one candidate and would not
2558/// guess between them. Never wired to a weaker, URL-less signal like
2559/// [`branch_is_ancestor`] — a caller wanting that has to ask for it
2560/// separately, precisely because it cannot drive an automatic correction on
2561/// its own (see that function's own doc).
2562pub async fn find_external_merge(state: &RunState) -> Result<Option<ExternalMerge>> {
2563    let Some(winner) = state.winner() else {
2564        return Ok(None);
2565    };
2566    let branch = state.pr_branch().unwrap_or(&winner.branch).to_owned();
2567    let out = gh(
2568        &state.repo,
2569        &[
2570            "pr".to_owned(),
2571            "list".to_owned(),
2572            "--head".to_owned(),
2573            branch.clone(),
2574            "--state".to_owned(),
2575            "merged".to_owned(),
2576            "--json".to_owned(),
2577            "url,number,mergedAt,baseRefName".to_owned(),
2578        ],
2579    )
2580    .await?;
2581    if !out.0 {
2582        bail!("gh pr list --head {branch}: {}", out.1);
2583    }
2584    pick_merged_pr(&out.1, &state.base_branch, state.created_at)
2585}
2586
2587/// Whether `branch` is, right now, an ancestor of `base_branch` in the local
2588/// git graph — the weaker, URL-less signal that a branch landed somewhere.
2589///
2590/// Deliberately never consulted by [`find_external_merge`]: a base branch
2591/// that has moved since the run started can make an old, abandoned branch
2592/// look like an ancestor of the *current* base for reasons that have nothing
2593/// to do with a merge (a later commit that happens to supersede it, an
2594/// unrelated squash), and there is no pull request URL here to confirm
2595/// against or to land through anyway. Its only honest use is a weaker
2596/// notice — "this looks merged, go check" — never an automatic rewrite of
2597/// `status`/`merge`.
2598pub async fn branch_is_ancestor(repo: &Path, branch: &str, base_branch: &str) -> Result<bool> {
2599    let out = tokio::process::Command::new("git")
2600        .args(["merge-base", "--is-ancestor", branch, base_branch])
2601        .current_dir(repo)
2602        .quiet()
2603        .stdin(std::process::Stdio::null())
2604        .output()
2605        .await
2606        .context("spawn git merge-base --is-ancestor")?;
2607    Ok(out.status.success())
2608}
2609
2610/// Parse `host/owner/repo` out of a forge URL, with no network access.
2611///
2612/// The host is part of the slug, not discarded: `owner/repo` alone would
2613/// treat `github.example.com/o/r` and `github.com/o/r` as the same
2614/// repository, which is exactly the mix-up the same-repo guard exists to
2615/// catch. Returns `None` for anything that doesn't have a `<host>/<path>`
2616/// shape at all.
2617fn forge_slug(url: &str) -> Option<(String, &str)> {
2618    let rest = url.rsplit("://").next()?;
2619    let (host, path) = rest.split_once('/')?;
2620    if host.is_empty() {
2621        return None;
2622    }
2623    Some((host.to_ascii_lowercase(), path))
2624}
2625
2626/// Parse `host/owner/repo` out of a GitHub pull request URL, with no network
2627/// access - the first half of the same-repo guard [`correct_manual_merge`]
2628/// applies before it writes anything.
2629///
2630/// Returns `None` for anything that does not look like
2631/// `https://<host>/<owner>/<repo>/pull/<n>`, which the caller treats as
2632/// fail-closed: a URL this cannot make sense of refuses rather than guesses.
2633pub(crate) fn slug_of_pr_url(url: &str) -> Option<String> {
2634    let (host, path) = forge_slug(url)?;
2635    let mut segments = path.split('/');
2636    let owner = segments.next()?;
2637    let repo = segments.next()?;
2638    let kind = segments.next()?;
2639    if owner.is_empty() || repo.is_empty() || kind != "pull" {
2640        return None;
2641    }
2642    Some(format!("{host}/{owner}/{repo}"))
2643}
2644
2645/// Parse `host/owner/repo` out of a plain repository URL (no `/pull/<n>`
2646/// suffix), the shape `gh repo view --json url` returns - the other half of
2647/// the same-repo guard, matched against [`slug_of_pr_url`]'s output.
2648fn slug_of_repo_url(url: &str) -> Option<String> {
2649    let (host, path) = forge_slug(url)?;
2650    let mut segments = path.split('/');
2651    let owner = segments.next()?;
2652    let repo = segments.next()?;
2653    if owner.is_empty() || repo.is_empty() {
2654        return None;
2655    }
2656    Some(format!("{host}/{owner}/{repo}"))
2657}
2658
2659/// Refuse to correct a run against a pull request from a different
2660/// repository than the one it is recorded against.
2661///
2662/// This is the guard the shun/8c75 incident argued for: an operator ran
2663/// `magi fold --merged <shun PR url>` meaning to correct an old `Blocked` run
2664/// in a different repository, omitted the run id, and the id defaulted to
2665/// this machine's most recently created run - an unrelated, still-in-progress
2666/// run in a completely different repository - which then had its `status`
2667/// rewritten to `merged` from a pull request it had nothing to do with.
2668/// `correct_manual_merge` now requires an explicit id (see `magi fold`'s own
2669/// CLI help), but a mistyped or stale id could still name a run in a
2670/// different repository than the one the URL belongs to, so this checks that
2671/// independently rather than trusting the id alone.
2672///
2673/// Comparison is case-insensitive - GitHub owner/repo names are - and a
2674/// mismatch names both slugs rather than just refusing, so an operator whose
2675/// local checkout's `origin` is a fork of the repository the pull request was
2676/// opened against (a legitimate setup this cannot tell apart from a genuine
2677/// mix-up) can judge for themselves rather than being blocked with no way to
2678/// see why.
2679pub(crate) fn ensure_same_repo(run_repo_slug: &str, pr_repo_slug: &str) -> Result<()> {
2680    if run_repo_slug.eq_ignore_ascii_case(pr_repo_slug) {
2681        return Ok(());
2682    }
2683    bail!(
2684        "refusing to correct this run: it is recorded against {run_repo_slug}, but the pull \
2685         request URL belongs to {pr_repo_slug} - pass the run id whose repository the URL \
2686         actually belongs to (or, if `origin` is a fork opened against a different upstream, \
2687         verify by hand before treating this as a false positive)"
2688    );
2689}
2690
2691/// Ask the forge which `host/owner/repo` a local checkout's `origin` remote
2692/// actually resolves to, for the same-repo guard in [`correct_manual_merge`].
2693///
2694/// Asking `gh` rather than parsing `git remote -v` locally is deliberate: it
2695/// normalizes case, SSH vs. HTTPS remotes, and a renamed or transferred
2696/// repository the same way GitHub itself would recognize it, so the
2697/// comparison in [`ensure_same_repo`] is against the same canonical slug on
2698/// both sides. Reads `url` rather than `nameWithOwner` so the host is part of
2699/// the answer too - `nameWithOwner` alone cannot tell a `github.com` repo from
2700/// a same-named one on a GitHub Enterprise host.
2701async fn repo_slug(repo: &Path) -> Result<String> {
2702    let out = gh(
2703        repo,
2704        &[
2705            "repo".to_owned(),
2706            "view".to_owned(),
2707            "--json".to_owned(),
2708            "url".to_owned(),
2709        ],
2710    )
2711    .await?;
2712    if !out.0 {
2713        bail!("gh repo view --json url: {}", out.1);
2714    }
2715    #[derive(Debug, Deserialize)]
2716    struct GhRepo {
2717        url: String,
2718    }
2719    let parsed: GhRepo = serde_json::from_str(&out.1)
2720        .with_context(|| format!("parse `gh repo view` output: {}", out.1))?;
2721    slug_of_repo_url(&parsed.url)
2722        .with_context(|| format!("could not parse a host/owner/repo out of {}", parsed.url))
2723}
2724
2725/// Confirm `url` is actually a merged pull request, then rewrite `state`'s
2726/// `status` and `merge` exactly as the automatic land loop (`land::land`)
2727/// would have written them had magi opened and merged this pull request
2728/// itself.
2729///
2730/// This is `magi fold --merged`'s whole implementation, and also what the
2731/// web `fold-merged` route calls once it has a URL in hand — an operator
2732/// recovery path for a merge magi could not finish on its own: a PR title too
2733/// long for the GraphQL mutation, `gh pr create` unreachable, a stale token -
2734/// closed by hand with a pull request magi never opened and so never
2735/// recorded. Reusing `land::land` rather than writing `status`/`merge`
2736/// directly keeps this one authoritative: a merged pull request decides
2737/// `Step::Done { merged: true }` on the very first read, before any of
2738/// `land`'s own checks/fix/rebase machinery can run, which is what makes it
2739/// safe to call here even though this pull request was never magi's own.
2740///
2741/// [`ensure_same_repo`] is checked before anything else: a pull request from
2742/// a different repository than the one `state` is recorded against is
2743/// refused outright, regardless of its lifecycle. This is the guard for a
2744/// URL an *operator* hands in - the CLI or the web route - where a stale or
2745/// mistyped run id could otherwise get corrected from an unrelated
2746/// repository's pull request (see the shun/8c75 incident in `magi fold`'s own
2747/// CLI help). The automatic janitor sweep (`clean::reconcile_external_merges`)
2748/// goes through [`correct_confirmed_external_merge`] instead, which skips
2749/// this check: its `url` was never operator-supplied, it comes from
2750/// [`find_external_merge`] querying `gh` from inside `state.repo` itself, so
2751/// it is already guaranteed to name a pull request in that same repository -
2752/// re-deriving and re-checking the repository here would only be a second
2753/// `gh repo view` call that can fail for reasons that have nothing to do with
2754/// correctness (a rate limit, a network blip), turning a self-heal that would
2755/// otherwise have succeeded into a run left `Blocked` for another pass.
2756///
2757/// [`lifecycle`] is checked next and separately so a mistyped or still-open
2758/// URL fails loudly without writing anything, rather than handing an open
2759/// pull request to the full autonomous loop by accident.
2760///
2761/// Correcting `status` this way does not run `bump::after_merge`
2762/// (`src/bump.rs`): that call is made only from `graph::Runner::run_land`,
2763/// which this path never goes through. A release version bump the change
2764/// might have earned is therefore not filed automatically and has to be
2765/// requested by hand - recorded as an event on the run so the gap is visible
2766/// to whoever reads it later, not just wherever this was called from. Follow-up
2767/// tasks for findings the merge left open (`crate::followup`) *are* filed here.
2768///
2769/// Returns the status before and after, so every caller (CLI, janitor, web
2770/// route) can build its own log line or response from the same pair rather
2771/// than each re-deriving it.
2772pub async fn correct_manual_merge(
2773    state: &mut RunState,
2774    url: &str,
2775) -> Result<(RunStatus, RunStatus)> {
2776    let Some(pr_slug) = slug_of_pr_url(url) else {
2777        bail!(
2778            "could not parse an owner/repo out of {url}; refusing to guess which repository \
2779             this pull request belongs to"
2780        );
2781    };
2782    let run_slug = repo_slug(&state.repo).await?;
2783    ensure_same_repo(&run_slug, &pr_slug)?;
2784    correct_merge(state, url).await
2785}
2786
2787/// The janitor's own entry point into the same correction
2788/// [`correct_manual_merge`] performs for an operator-supplied URL, minus the
2789/// same-repo guard - see that function's own doc for why skipping it here is
2790/// safe rather than a hole: [`clean::reconcile_external_merges`] only ever
2791/// calls this with a `url` [`find_external_merge`] already found by querying
2792/// `state.repo`'s own remote, so the guard could never do anything here but
2793/// fail on its own transient errors.
2794///
2795/// [`crate::clean`] is the only caller; `pub(crate)` rather than private only
2796/// because it lives in a different module.
2797pub(crate) async fn correct_confirmed_external_merge(
2798    state: &mut RunState,
2799    url: &str,
2800) -> Result<(RunStatus, RunStatus)> {
2801    correct_merge(state, url).await
2802}
2803
2804/// Same pull request, same repository: the url, or the number within one repo.
2805fn names_same_pr(a: &RunState, url: &str, number: u64, repo: &Path) -> bool {
2806    let Some(pr) = a.pr.as_ref() else {
2807        return false;
2808    };
2809    if !url.is_empty()
2810        && pr
2811            .url
2812            .trim_end_matches('/')
2813            .eq_ignore_ascii_case(url.trim_end_matches('/'))
2814    {
2815        return true;
2816    }
2817    number > 0
2818        && pr.number == number
2819        && match (a.repo.canonicalize(), repo.canonicalize()) {
2820            (Ok(x), Ok(y)) => x == y,
2821            _ => a.repo == repo,
2822        }
2823}
2824
2825/// Rewrite `pr.state` to a final state on every run record under `home` that
2826/// `decide` picks, and report how many were rewritten.
2827///
2828/// Lifecycle writes through to other runs are deliberately narrow (task-head
2829/// ownership is recorded separately): only a **terminal** run (never one a
2830/// driver may still be writing), only a proven-stopped driver with no daemon
2831/// claim (the shared liveness judge), only a record
2832/// whose `pr.state` is still `open`, and only `merged` / `closed` ever goes in.
2833/// The record is read as folding reads it (no schema check: every bump so far
2834/// only added fields, and the whole struct round-trips) and written through
2835/// [`RunState::save_under`], the path every record uses, so nothing but
2836/// `pr.state` and an event line changes (and `updated_at`, as for any save).
2837/// A run that cannot be read or written is skipped with a warning.
2838fn rewrite_open_prs(
2839    home: &Path,
2840    decide: &mut dyn FnMut(&RunState) -> Option<PrLifecycle>,
2841) -> usize {
2842    let now = Timestamp::now();
2843    let mut changed = 0;
2844    for id in crate::run::list_ids_in(&home.join("runs")) {
2845        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2846            continue;
2847        };
2848        let path = home.join("runs").join(&id).join("run.json");
2849        let Ok(body) = std::fs::read_to_string(&path) else {
2850            continue;
2851        };
2852        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2853            continue;
2854        };
2855        if !state.status.done()
2856            || state.pr.as_ref().is_none_or(|p| p.state != "open")
2857            || state.liveness_under(home, crate::daemon::is_working_on(home, &id, now))
2858                != crate::run::Liveness::Dead
2859        {
2860            continue;
2861        }
2862        let Some(to @ (PrLifecycle::Merged | PrLifecycle::Closed)) = decide(&state) else {
2863            continue;
2864        };
2865        if let Some(pr) = state.pr.as_mut() {
2866            pr.state = to.as_str().to_owned();
2867        }
2868        let url = state.pr.as_ref().map(|p| p.url.clone()).unwrap_or_default();
2869        state.event(
2870            "land",
2871            format!("recorded {url} as {}: another run settled it", to.as_str()),
2872        );
2873        match state.save_under(home) {
2874            Ok(()) => changed += 1,
2875            Err(e) => tracing::warn!("write pr state through to run {id}: {e:#}"),
2876        }
2877    }
2878    changed
2879}
2880
2881/// A run reached a final state for its pull request: tell every other terminal
2882/// run in the same repository that names the same pull request (handed-over
2883/// predecessors, blocked attempts, anything), so their records stop saying
2884/// `open`. Best effort; `run`'s own record is the caller's.
2885pub(crate) fn write_pr_state_through(run: &RunState, to: PrLifecycle) {
2886    if to == PrLifecycle::Open {
2887        return;
2888    }
2889    let Some(home) = crate::run::try_home() else {
2890        return;
2891    };
2892    write_pr_state_through_in(&home, run, to);
2893}
2894
2895pub(crate) fn write_pr_state_through_in(home: &Path, run: &RunState, to: PrLifecycle) -> usize {
2896    let Some(pr) = run.pr.as_ref() else {
2897        return 0;
2898    };
2899    let (url, number) = (pr.url.clone(), pr.number);
2900    rewrite_open_prs(home, &mut |other| {
2901        (other.id != run.id && names_same_pr(other, &url, number, &run.repo)).then_some(to)
2902    })
2903}
2904
2905/// Terminal runs whose record still says their pull request is open, as
2906/// `(run id, repo, url)`, for [`repair_stale_pr_states`].
2907pub(crate) fn stale_open_prs(home: &Path) -> Vec<(String, PathBuf, String)> {
2908    let now = Timestamp::now();
2909    let mut out = Vec::new();
2910    for id in crate::run::list_ids_in(&home.join("runs")) {
2911        let path = home.join("runs").join(&id).join("run.json");
2912        let Ok(body) = std::fs::read_to_string(&path) else {
2913            continue;
2914        };
2915        let Ok(state) = serde_json::from_str::<RunState>(&body) else {
2916            continue;
2917        };
2918        if let Some(pr) = state.pr.as_ref()
2919            && state.status.done()
2920            && pr.state == "open"
2921            && !pr.url.is_empty()
2922            && !crate::daemon::is_working_on(home, &id, now)
2923        {
2924            out.push((id, state.repo.clone(), pr.url.clone()));
2925        }
2926    }
2927    out
2928}
2929
2930/// Apply forge answers (`pr url -> state`) to every stale terminal record.
2931/// A url with no answer (the forge was unreadable) changes nothing.
2932pub(crate) fn apply_pr_states(home: &Path, known: &BTreeMap<String, PrLifecycle>) -> usize {
2933    rewrite_open_prs(home, &mut |s| {
2934        s.pr.as_ref().and_then(|p| known.get(&p.url)).copied()
2935    })
2936}
2937
2938/// One-time (and idempotent) repair of records that froze an `open` pull
2939/// request: ask the forge about each distinct pull request that a terminal run
2940/// still calls open - at most `max_lookups` of them - and rewrite the merged
2941/// and closed ones. A genuinely open pull request is left alone, and a lookup
2942/// that fails is "unknown, change nothing". Returns `(records rewritten,
2943/// lookups that failed)`.
2944pub async fn repair_stale_pr_states(home: &Path, max_lookups: usize) -> (usize, usize) {
2945    let mut known = BTreeMap::new();
2946    let mut failed = 0;
2947    let mut seen = BTreeSet::new();
2948    for (_, repo, url) in stale_open_prs(home) {
2949        if known.len() + failed >= max_lookups || !seen.insert(url.clone()) {
2950            continue;
2951        }
2952        match lifecycle(&repo, &url).await {
2953            Ok(state) => {
2954                known.insert(url, state);
2955            }
2956            Err(e) => {
2957                tracing::warn!("repair pr state of {url}: {e:#}");
2958                failed += 1;
2959            }
2960        }
2961    }
2962    (apply_pr_states(home, &known), failed)
2963}
2964
2965async fn correct_merge(state: &mut RunState, url: &str) -> Result<(RunStatus, RunStatus)> {
2966    match lifecycle(&state.repo, url).await? {
2967        PrLifecycle::Merged => {}
2968        other => bail!(
2969            "{url} is {}, not merged; refusing to record {} as merged on a guess",
2970            other.as_str(),
2971            state.id
2972        ),
2973    }
2974    let before = state.status;
2975    if let Err(e) = land(state, url).await {
2976        // `land` sets `status` to `Landing` and saves before its first read
2977        // of the pull request — see its own doc — so a failure here (a
2978        // transient `gh` hiccup between the two forge reads this function
2979        // makes) can leave the run stuck on that in-between value with
2980        // nothing left driving it. Land it on the same terminal shape an
2981        // automated `land` failure lands on instead of leaving it stuck.
2982        state.status = RunStatus::Blocked;
2983        state.event("fold", format!("manual-merge correction failed: {e:#}"));
2984        state.save()?;
2985        return Err(e).context(format!("confirming the merge of {url}"));
2986    }
2987    state.event(
2988        "fold",
2989        "operator recorded this pull request as a manual merge; this run never \
2990         re-entered `land`, so `bump::after_merge` did not run for it - a release \
2991         bump this change might warrant has to be filed by hand",
2992    );
2993    // Unlike the bump, the findings the merge left open are filed on this
2994    // path too: nothing else would ever carry them forward.
2995    if state.status == RunStatus::Merged {
2996        crate::followup::after_merge(state, url).await;
2997    }
2998    state.save()?;
2999    Ok((before, state.status))
3000}
3001
3002/// Parse `gh api repos/{owner}/{repo}/pulls/<n>/comments` into inline review
3003/// comments. No I/O.
3004///
3005/// `gh pr view` does not surface inline comments, and inline is exactly where
3006/// both review bots put their findings - a landing loop that read only the
3007/// top-level thread would never see the thing it is supposed to fix.
3008pub fn parse_inline_comments(json: &str) -> Result<Vec<ReviewComment>> {
3009    let raw: Vec<GhInline> =
3010        serde_json::from_str(json).context("parse `gh api .../pulls/<n>/comments` output")?;
3011    let mut out = Vec::new();
3012    for c in raw {
3013        push_if_outstanding(
3014            &mut out,
3015            ReviewComment {
3016                author: c.user.login,
3017                path: c.path,
3018                line: c.line,
3019                body: c.body,
3020            },
3021        );
3022    }
3023    Ok(out)
3024}
3025
3026/// Keep a comment only when it asks for something.
3027///
3028/// An inline comment always does: it names a file and a line. A top-level
3029/// comment is dropped when it is empty, when it is magi's own, or when it is
3030/// [noise](is_noise).
3031fn push_if_outstanding(out: &mut Vec<ReviewComment>, comment: ReviewComment) {
3032    if comment.body.trim().is_empty() || comment.body.contains(MARKER) {
3033        return;
3034    }
3035    if comment.path.is_none() && is_noise(&comment.body) {
3036        return;
3037    }
3038    out.push(comment);
3039}
3040
3041/// Is this comment body machinery rather than a finding?
3042///
3043/// Two tests, both structural, because guessing from prose is how a "looks
3044/// good to me" turns into a fix round:
3045///
3046/// 1. The bot said so - the body carries one of the [`NOT_A_REVIEW`] markers
3047///    with which CodeRabbit labels its trigger notice, its walkthrough, and its
3048///    footer.
3049/// 2. It asks for nothing - once HTML comments, `<details>` blocks, headings,
3050///    horizontal rules, and the bot's own status banner are removed, every
3051///    remaining line is a task-list item. That is exactly the shape of the
3052///    comment the Claude review job posts while it is still working.
3053///
3054/// Anything else is input, including bot prose. A bot that writes a paragraph
3055/// has said something, and the fix prompt tells the fixer it may decline a
3056/// comment with an argument - a wasted sentence in a prompt is cheaper than a
3057/// missed finding.
3058pub fn is_noise(body: &str) -> bool {
3059    if NOT_A_REVIEW.iter().any(|m| body.contains(m)) {
3060        return true;
3061    }
3062    let mut content = false;
3063    for line in strip_blocks(body).lines() {
3064        let line = unquote(line);
3065        if line.is_empty() || is_checklist(line) || is_decoration(line) || is_banner(line) {
3066            continue;
3067        }
3068        content = true;
3069        break;
3070    }
3071    !content
3072}
3073
3074/// Remove HTML comments and collapsed `<details>` blocks.
3075fn strip_blocks(body: &str) -> String {
3076    let mut out = String::with_capacity(body.len());
3077    let mut rest = body;
3078    loop {
3079        let open = ["<!--", "<details>"]
3080            .iter()
3081            .filter_map(|tag| rest.find(tag).map(|i| (i, *tag)))
3082            .min_by_key(|(i, _)| *i);
3083        let Some((at, tag)) = open else {
3084            out.push_str(rest);
3085            return out;
3086        };
3087        out.push_str(&rest[..at]);
3088        let after = &rest[at + tag.len()..];
3089        let close = if tag == "<!--" { "-->" } else { "</details>" };
3090        match after.find(close) {
3091            Some(end) => rest = &after[end + close.len()..],
3092            // Unterminated: the rest of the body is inside the block.
3093            None => return out,
3094        }
3095    }
3096}
3097
3098/// Strip blockquote markers, which both bots wrap their callouts in.
3099fn unquote(line: &str) -> &str {
3100    let mut s = line.trim();
3101    while let Some(rest) = s.strip_prefix('>') {
3102        s = rest.trim_start();
3103    }
3104    s.trim()
3105}
3106
3107/// `- [ ]` / `- [x]`, in any of the bullet styles GitHub renders.
3108fn is_checklist(line: &str) -> bool {
3109    let rest = line
3110        .strip_prefix("- ")
3111        .or_else(|| line.strip_prefix("* "))
3112        .unwrap_or("");
3113    let rest = rest.trim_start();
3114    matches!(
3115        rest.get(..3),
3116        Some("[ ]") | Some("[x]") | Some("[X]") | Some("[*]")
3117    )
3118}
3119
3120/// A heading, a horizontal rule, or a callout tag - shape, never content.
3121fn is_decoration(line: &str) -> bool {
3122    line.starts_with('#')
3123        || line.starts_with("[!")
3124        || (line.len() >= 3 && line.chars().all(|c| matches!(c, '-' | '=' | '*' | '_')))
3125}
3126
3127/// A line that is nothing but emphasis and links.
3128///
3129/// Both review jobs open with a status banner
3130/// (`**Claude finished ... in 4m 14s** —— [View job](url)`). It reads as prose
3131/// to a line-based test and asks for nothing, so it is measured the same way a
3132/// heading is: strip the markup, and if no word survives, it was decoration.
3133fn is_banner(line: &str) -> bool {
3134    let plain = drop_spans(line, "**", "**");
3135    let plain = if plain.contains("](") {
3136        drop_spans(&plain, "[", ")")
3137    } else {
3138        plain
3139    };
3140    !plain.chars().any(char::is_alphanumeric)
3141}
3142
3143/// Remove every `open` .. `close` span, including the delimiters. An
3144/// unterminated span swallows the rest of the input, which is what a reader
3145/// sees too.
3146fn drop_spans(s: &str, open: &str, close: &str) -> String {
3147    let mut out = String::with_capacity(s.len());
3148    let mut rest = s;
3149    while let Some(at) = rest.find(open) {
3150        out.push_str(&rest[..at]);
3151        let after = &rest[at + open.len()..];
3152        match after.find(close) {
3153            Some(end) => rest = &after[end + close.len()..],
3154            None => return out,
3155        }
3156    }
3157    out.push_str(rest);
3158    out
3159}
3160
3161/// The lock that keeps at most one run per repository actually moving the
3162/// base branch at a time: a rebase push, or `gh pr merge`.
3163///
3164/// Deliberately narrow. Everything else in [`land`]'s loop - watching CI,
3165/// running a fix round in the winner's own worktree, waiting on the owner's
3166/// approval - touches nothing a *different* run in the same repository could
3167/// collide with, and holding a lock across any of that would serialise one
3168/// run's CI wait (up to [`WAIT_CEILING`]) against another run's land-approval
3169/// resume, which is precisely the "must not wait on another task" property
3170/// the daemon's slot-freeing exists to give a resume. Only the two moments
3171/// that actually write to the shared base branch need mutual exclusion, and
3172/// both are brief.
3173///
3174/// One entry per repository, each its own `tokio::sync::Mutex`, so two
3175/// different repositories' runs never wait on each other. The outer
3176/// `std::sync::Mutex` guards only the map itself, held long enough to find or
3177/// insert an entry and clone its `Arc`, never across an `.await`.
3178fn repo_merge_lock(repo: &Path) -> Arc<tokio::sync::Mutex<()>> {
3179    static LOCKS: std::sync::LazyLock<
3180        std::sync::Mutex<BTreeMap<PathBuf, Arc<tokio::sync::Mutex<()>>>>,
3181    > = std::sync::LazyLock::new(|| std::sync::Mutex::new(BTreeMap::new()));
3182    LOCKS
3183        .lock()
3184        .unwrap_or_else(std::sync::PoisonError::into_inner)
3185        .entry(repo.to_path_buf())
3186        .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
3187        .clone()
3188}
3189
3190/// `owner/repo` out of a pull request url, falling back to the checkout's
3191/// directory name when the url is not the usual `host/owner/repo/pull/N`.
3192fn repo_label(repo: &Path, pr_url: &str) -> String {
3193    let parts: Vec<&str> = pr_url.split('/').collect();
3194    if let Some(at) = parts.iter().rposition(|p| *p == "pull")
3195        && at >= 2
3196        && !parts[at - 1].is_empty()
3197        && !parts[at - 2].is_empty()
3198    {
3199        return format!("{}/{}", parts[at - 2], parts[at - 1]);
3200    }
3201    repo.file_name()
3202        .map(|n| n.to_string_lossy().into_owned())
3203        .unwrap_or_default()
3204}
3205
3206/// The operator-facing sentence for a merge that went ahead with red checks,
3207/// or `None` when the checks were not red. Judged on `checks`, not on
3208/// `failing`, which can be non-empty on a green observation.
3209fn red_merge_summary(repo_name: &str, pr: &PrState) -> Option<String> {
3210    (pr.checks == Checks::Red).then(|| {
3211        let details = crate::notices::format_list(&pr.failing)
3212            .map(|names| format!(": {names}"))
3213            .unwrap_or_default();
3214        format!(
3215            "Merged {repo_name} PR #{} with red checks{details} ({})",
3216            pr.number, pr.url
3217        )
3218    })
3219}
3220
3221/// After a merge that succeeded: record which checks were red and tell the
3222/// operator. The decision to merge is already made; this only makes it audible.
3223/// Best-effort - a broken notifier never fails the run.
3224async fn announce_red_merge(state: &mut RunState, pr: &PrState) {
3225    let repo_name = repo_label(&state.repo, &pr.url);
3226    let Some(summary) = red_merge_summary(&repo_name, pr) else {
3227        return;
3228    };
3229    if let Some(rec) = state.pr.as_mut() {
3230        rec.red_at_merge = pr.failing.clone();
3231    }
3232    state.event("land", summary.clone());
3233    // The notice pages through `[notify]` itself, once, unless a question
3234    // already carries the cause.
3235    crate::notices::raise_with(
3236        crate::notices::merged_red(&state.id, &summary),
3237        &state.config.notify,
3238    );
3239}
3240
3241/// Run the loop against a real pull request until it merges or the budget runs
3242/// out.
3243///
3244/// The caller decides whether landing happens at all: this is only reached when
3245/// `graph.land` is on. Returns the last observation, so the caller can report
3246/// what magi was looking at when it stopped.
3247pub async fn land(state: &mut RunState, pr_url: &str) -> Result<PrState> {
3248    land_with(state, pr_url, &GhForge).await
3249}
3250
3251/// The forge calls whose timing the loop's decisions depend on, behind a seam
3252/// so a test can script what the pull request looks like from one observation
3253/// to the next. Comments, logs and rebases stay on `gh` and `git` directly.
3254trait Forge {
3255    async fn close(&self, repo: &Path, pr_url: &str, comment: &str) -> Result<()> {
3256        let (ok, out) = gh(
3257            repo,
3258            &[
3259                "pr".into(),
3260                "close".into(),
3261                pr_url.into(),
3262                "--comment".into(),
3263                comment.into(),
3264            ],
3265        )
3266        .await?;
3267        if !ok {
3268            bail!("PR closure failed: {out}");
3269        }
3270        Ok(())
3271    }
3272    async fn attribution(&self, _state: &RunState, _seen: &Seen) -> Option<CiEvidence> {
3273        None
3274    }
3275    async fn view(&self, repo: &Path, pr_url: &str) -> Result<Seen>;
3276    async fn merge(&self, repo: &Path, argv: &[String]) -> Result<(bool, String)>;
3277    async fn poll(&self);
3278    /// Rerun the failed jobs of one workflow run.
3279    async fn rerun(&self, repo: &Path, run: &str) -> Result<()>;
3280    /// Unix seconds, behind the seam so a test owns the clock.
3281    fn now(&self) -> i64;
3282    /// The check contexts the base branch requires, for a stop reason only.
3283    /// `None` when they could not be read, which is not the same as none.
3284    async fn required_contexts(&self, repo: &Path, base: &str) -> Option<BTreeSet<String>>;
3285    #[allow(clippy::too_many_arguments)]
3286    async fn fix(
3287        &self,
3288        state: &mut RunState,
3289        pr: &PrState,
3290        round: usize,
3291        budget: usize,
3292        reason: &str,
3293        logs: &str,
3294    ) -> Result<Fixed>;
3295}
3296
3297struct GhForge;
3298
3299impl Forge for GhForge {
3300    async fn attribution(&self, state: &RunState, seen: &Seen) -> Option<CiEvidence> {
3301        collect_ci_evidence(state, seen).await
3302    }
3303    async fn view(&self, repo: &Path, pr_url: &str) -> Result<Seen> {
3304        observe(repo, pr_url).await
3305    }
3306    async fn merge(&self, repo: &Path, argv: &[String]) -> Result<(bool, String)> {
3307        gh(repo, argv).await
3308    }
3309    async fn poll(&self) {
3310        tokio::time::sleep(POLL).await;
3311    }
3312    async fn rerun(&self, repo: &Path, run: &str) -> Result<()> {
3313        let args = [
3314            "run".to_owned(),
3315            "rerun".to_owned(),
3316            run.to_owned(),
3317            "--failed".to_owned(),
3318        ];
3319        let (ok, out) = gh(repo, &args).await?;
3320        if !ok {
3321            bail!("gh run rerun {run}: {out}");
3322        }
3323        Ok(())
3324    }
3325    fn now(&self) -> i64 {
3326        jiff::Timestamp::now().as_second()
3327    }
3328    async fn required_contexts(&self, repo: &Path, base: &str) -> Option<BTreeSet<String>> {
3329        required_contexts_of(repo, base).await
3330    }
3331    async fn fix(
3332        &self,
3333        state: &mut RunState,
3334        pr: &PrState,
3335        round: usize,
3336        budget: usize,
3337        reason: &str,
3338        logs: &str,
3339    ) -> Result<Fixed> {
3340        fix_round(state, pr, round, budget, reason, logs).await
3341    }
3342}
3343
3344/// Percent-encode a branch name for a URL path segment (`/` included).
3345fn encode_path_segment(s: &str) -> String {
3346    let mut out = String::new();
3347    for b in s.bytes() {
3348        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
3349            out.push(b as char);
3350        } else {
3351            let _ = write!(out, "%{b:02X}");
3352        }
3353    }
3354    out
3355}
3356
3357/// Read the required contexts of `base` from classic branch protection and
3358/// from rulesets, once, for a stop reason. Organisation-level rulesets that
3359/// these two endpoints do not list are missed. Any unreadable source makes the
3360/// whole answer `None`: a partial set would read as a complete one.
3361async fn required_contexts_of(repo: &Path, base: &str) -> Option<BTreeSet<String>> {
3362    let enc = encode_path_segment(base);
3363    let mut all = BTreeSet::new();
3364    // Classic protection answers 404 for an unprotected branch, which is
3365    // "nothing required here", not a failure to read.
3366    let classic = gh(
3367        repo,
3368        &[
3369            "api".to_owned(),
3370            format!("repos/{{owner}}/{{repo}}/branches/{enc}/protection/required_status_checks"),
3371        ],
3372    )
3373    .await
3374    .ok()?;
3375    if classic.0 {
3376        all.extend(parse_classic_required(&classic.1)?);
3377    } else if !classic.1.contains("404") {
3378        return None;
3379    }
3380    let rules = gh(
3381        repo,
3382        &[
3383            "api".to_owned(),
3384            format!("repos/{{owner}}/{{repo}}/rules/branches/{enc}"),
3385        ],
3386    )
3387    .await
3388    .ok()?;
3389    if !rules.0 {
3390        return None;
3391    }
3392    all.extend(parse_ruleset_required(&rules.1)?);
3393    Some(all)
3394}
3395
3396/// `required_status_checks` of classic protection: `contexts` plus the
3397/// `checks[].context` form.
3398fn parse_classic_required(json: &str) -> Option<BTreeSet<String>> {
3399    let v: serde_json::Value = serde_json::from_str(json).ok()?;
3400    let mut out = BTreeSet::new();
3401    for c in v.get("contexts")?.as_array()? {
3402        out.insert(c.as_str()?.to_owned());
3403    }
3404    for c in v
3405        .get("checks")
3406        .and_then(|c| c.as_array())
3407        .into_iter()
3408        .flatten()
3409    {
3410        if let Some(name) = c.get("context").and_then(|n| n.as_str()) {
3411            out.insert(name.to_owned());
3412        }
3413    }
3414    Some(out)
3415}
3416
3417/// `rules/branches/<base>`: every `required_status_checks` rule's contexts.
3418fn parse_ruleset_required(json: &str) -> Option<BTreeSet<String>> {
3419    let v: serde_json::Value = serde_json::from_str(json).ok()?;
3420    let mut out = BTreeSet::new();
3421    for rule in v.as_array()? {
3422        if rule.get("type").and_then(|t| t.as_str()) != Some("required_status_checks") {
3423            continue;
3424        }
3425        let checks = rule
3426            .pointer("/parameters/required_status_checks")?
3427            .as_array()?;
3428        for c in checks {
3429            out.insert(c.get("context")?.as_str()?.to_owned());
3430        }
3431    }
3432    Some(out)
3433}
3434
3435/// Is the observation older than the commit a fix round pushed?
3436///
3437/// The forge takes a few seconds to move the pull request to a new head and
3438/// attach that head's check runs, and until it has, the rollup is the previous
3439/// head's - all green, which is exactly what a merge decision must not read.
3440/// An absent or different head counts as not yet: guessing "close enough"
3441/// would reopen the hole.
3442fn awaiting_new_head(awaiting: Option<&str>, observed: &str) -> bool {
3443    awaiting.is_some_and(|want| !observed.eq_ignore_ascii_case(want))
3444}
3445
3446/// The commit an observation may be decided on, or `None` while it cannot be
3447/// trusted to describe one.
3448///
3449/// `None` when a pushed commit is awaited and the pull request is not on it,
3450/// when the head is unreadable, or when the rollup (`statusCheckRollup` is the
3451/// last commit's) is not the head's: that is the previous commit's checks. The
3452/// caller re-polls on `None`. A rollup that cannot be read (including one
3453/// longer than a page) leaves `rollup_head` empty, so the wait runs to
3454/// [`WAIT_CEILING`] and stops - a safe failure, never a merge.
3455fn bound_head<'a>(
3456    seen_head: &'a str,
3457    rollup_head: &str,
3458    awaiting: Option<&str>,
3459) -> Option<&'a str> {
3460    if seen_head.is_empty()
3461        || awaiting_new_head(awaiting, seen_head)
3462        || !rollup_head.eq_ignore_ascii_case(seen_head)
3463    {
3464        return None;
3465    }
3466    Some(seen_head)
3467}
3468
3469/// What a refused `gh pr merge` means.
3470#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3471enum Refused {
3472    /// An open PR on the observed head has a proven stale base.
3473    Behind,
3474    /// The branch policy is not satisfied *yet*: go back to waiting.
3475    Pending,
3476    /// Checks have settled and the merge state still says no, seen for the
3477    /// first time. The forge updates `mergeStateStatus` a moment after the last
3478    /// check finishes, so one more look is allowed before believing it.
3479    Recheck,
3480    /// Nothing is in flight and the policy still refuses: a person has to
3481    /// supply what it asks for (a review, say).
3482    Final,
3483}
3484
3485/// Judged from the pull request's state after the refusal, never from the
3486/// refusal's wording, which belongs to the forge and changes.
3487fn classify_refusal(
3488    after: Option<&Seen>,
3489    rechecked: bool,
3490    observed_head: &str,
3491    ci: CiExpectation,
3492) -> Refused {
3493    let Some(after) = after else {
3494        // Unreadable is not evidence of anything; the next loop reads again.
3495        return Refused::Pending;
3496    };
3497    if after.pr.state != PrLifecycle::Open {
3498        return Refused::Final;
3499    }
3500    // The branch moved after it was observed (the forge refuses a merge pinned
3501    // to the old commit): not a verdict on anything, look again.
3502    if !after.head.eq_ignore_ascii_case(observed_head) {
3503        return Refused::Pending;
3504    }
3505    if Blocking::of(&after.merge_state) == Blocking::Behind {
3506        return Refused::Behind;
3507    }
3508    // The same binding the loop applies: checks of another commit say nothing.
3509    if bound_head(&after.head, &after.rollup_head, None).is_none() {
3510        return Refused::Pending;
3511    }
3512    let state = after.merge_state.to_ascii_uppercase();
3513    if (ci == CiExpectation::Expected
3514        && matches!(after.pr.checks, Checks::Pending | Checks::Unknown))
3515        || state.is_empty()
3516        || state == "UNKNOWN"
3517    {
3518        return Refused::Pending;
3519    }
3520    if rechecked {
3521        Refused::Final
3522    } else {
3523        Refused::Recheck
3524    }
3525}
3526
3527/// Take auto-merge back from the forge and forget that it was armed.
3528///
3529/// `Err` carries the forge's message: the caller must not push or move on, as
3530/// an armed merge left behind could still fire for a commit nobody approved.
3531async fn disarm<F: Forge>(
3532    forge: &F,
3533    state: &mut RunState,
3534    repo: &Path,
3535    number: u64,
3536) -> std::result::Result<(), String> {
3537    let argv = disable_automerge_argv(number);
3538    let out = {
3539        let merge_lock = repo_merge_lock(repo);
3540        let _merge_slot = merge_lock.lock().await;
3541        forge.merge(repo, &argv).await
3542    };
3543    match out {
3544        Ok((true, _)) => {
3545            state.land_armed_head = None;
3546            state.event("land", "auto-merge disabled");
3547            state.save().map_err(|e| format!("{e:#}"))?;
3548            Ok(())
3549        }
3550        Ok((false, msg)) => Err(msg),
3551        Err(e) => Err(format!("{e:#}")),
3552    }
3553}
3554
3555/// [`stop`], first taking back an armed auto-merge so a pull request magi
3556/// gave up on does not merge on its own later. A failure to disarm is added
3557/// to the reason rather than hiding it.
3558async fn stop_disarmed<F: Forge>(
3559    forge: &F,
3560    state: &mut RunState,
3561    repo: &Path,
3562    pr: &PrState,
3563    why: &str,
3564) -> Result<()> {
3565    if state.land_armed_head.is_none() {
3566        return stop(state, repo, pr, why).await;
3567    }
3568    match disarm(forge, state, repo, pr.number).await {
3569        Ok(()) => stop(state, repo, pr, why).await,
3570        Err(e) => {
3571            let why = format!("{why} (auto-merge could not be disabled and may still fire: {e})");
3572            stop(state, repo, pr, &why).await
3573        }
3574    }
3575}
3576
3577/// Check the persisted card again around awaits that can outlive an owner tap.
3578fn owner_requested_stop(state: &RunState) -> Result<bool> {
3579    let Some(binding) = &state.land_approval else {
3580        return Ok(false);
3581    };
3582    let q = ask::Questions::open().get(&binding.question)?;
3583    Ok(q.run == state.id
3584        && q.node == APPROVAL_NODE
3585        && q.resolution()
3586            .as_deref()
3587            .is_some_and(crate::merge_decision::stops))
3588}
3589
3590/// Read stop choices before checks, repair or rebase. These are about stopping
3591/// ownership, so a changed head never cancels them as it cancels merge consent.
3592async fn owner_stop<F: Forge>(state: &mut RunState, pr: &mut PrState, forge: &F) -> Result<bool> {
3593    use crate::merge_decision as md;
3594    let Some(binding) = &state.land_approval else {
3595        return Ok(false);
3596    };
3597    let q = ask::Questions::open().get(&binding.question)?;
3598    let Some(choice) = q.resolution().filter(|c| md::stops(c)) else {
3599        return Ok(false);
3600    };
3601    if q.run != state.id || q.node != APPROVAL_NODE {
3602        bail!("stop decision names another run");
3603    }
3604    let target = q.merge_target.clone().unwrap_or_else(|| md::Target {
3605        pr: pr.url.clone(),
3606        head: binding.head.clone(),
3607        language: state.config.graph.language.clone(),
3608    });
3609    if target.pr != pr.url {
3610        bail!("stop decision names another PR");
3611    }
3612    if state.merge_decision.is_none() {
3613        state.merge_decision = Some(md::Decision {
3614            question: q.id.clone(),
3615            target,
3616            choice: choice.clone(),
3617            closed: false,
3618            replacement_run: None,
3619            replacement_pr: None,
3620        });
3621        state.save()?;
3622    }
3623    let repo = state.repo.clone();
3624    // Always disable, including arms left by an older driver.
3625    if let Err(e) = disarm(forge, state, &repo, pr.number).await {
3626        stop(state, &repo, pr, &format!("owner stop requested, but auto-merge could not be disabled: {e}; no repair or replacement started")).await?;
3627        return Ok(true);
3628    }
3629    if choice.eq_ignore_ascii_case(HOLD) {
3630        stop(
3631            state,
3632            &repo,
3633            pr,
3634            "owner held the decision: PR left open; no further repair or merge work",
3635        )
3636        .await?;
3637        return Ok(true);
3638    }
3639    if md::selected_agent(&choice).is_some()
3640        || state
3641            .origin
3642            .as_ref()
3643            .and_then(|o| o.task.as_ref())
3644            .is_some()
3645    {
3646        let owners: Vec<_> = crate::queue::Queue::open()
3647            .list()
3648            .into_iter()
3649            .filter(|task| task.execution_runs().last() == Some(&state.id))
3650            .collect();
3651        let owner = (owners.len() == 1).then(|| &owners[0]);
3652        if !owner.is_some_and(|task| {
3653            task.execution_runs().last() == Some(&state.id)
3654                && (!task
3655                    .operator_decided_at
3656                    .is_some_and(|at| at > q.answered_at.unwrap_or(q.asked_at))
3657                    || task.resumption.as_ref().is_some_and(|release| {
3658                        release.question_id.as_deref() == Some(q.id.as_str())
3659                            && task.operator_decided_at == Some(release.at)
3660                    }))
3661        }) {
3662            stop(state, &repo, pr, "replacement requires the current original queue task owner and an unsuperseded answer; PR left open").await?;
3663            return Ok(true);
3664        }
3665    }
3666    if pr.state == PrLifecycle::Merged {
3667        stop(
3668            state,
3669            &repo,
3670            pr,
3671            "PR already merged; withdrawal/replacement cannot be applied",
3672        )
3673        .await?;
3674        return Ok(true);
3675    }
3676    let comment = format!(
3677        "{MARKER}\nOwner decision on question {}: {}. Previous attempt: `{}`. Original instruction and review history remain in the task record.",
3678        q.id, choice, state.id
3679    );
3680    if pr.state == PrLifecycle::Open {
3681        if let Err(e) = forge.close(&repo, &pr.url, &comment).await {
3682            stop(
3683                state,
3684                &repo,
3685                pr,
3686                &format!(
3687                    "owner requested closure but it failed: {e}; task held, no replacement started"
3688                ),
3689            )
3690            .await?;
3691            return Ok(true);
3692        }
3693    }
3694    let confirmed = forge.view(&repo, &pr.url).await?;
3695    if confirmed.pr.state != PrLifecycle::Closed {
3696        stop(
3697            state,
3698            &repo,
3699            pr,
3700            "PR closure was not confirmed; task held, no replacement started",
3701        )
3702        .await?;
3703        return Ok(true);
3704    }
3705    *pr = confirmed.pr;
3706    state.merge_decision.as_mut().unwrap().closed = true;
3707    if let Some(record) = &mut state.pr {
3708        record.state = "closed".into();
3709    }
3710    state.status = RunStatus::Superseded;
3711    state.merge = Some(MergeOutcome {
3712        mode: MergeMode::Pr,
3713        ok: false,
3714        detail: format!("owner decision: {choice}; PR closure confirmed"),
3715        empty: false,
3716    });
3717    state.event(
3718        "land",
3719        format!(
3720            "{} applied: PR closure confirmed; old execution retired",
3721            choice
3722        ),
3723    );
3724    state.save()?;
3725    Ok(true)
3726}
3727
3728/// Keep an unstarted verification resumable without charging a task attempt.
3729fn check_landing_resources(
3730    state: &mut RunState,
3731    node: &str,
3732    outcomes: &[crate::run::CommandOutcome],
3733) -> Result<()> {
3734    if let Some(blocked) = outcomes.iter().find(|outcome| outcome.resource_blocked) {
3735        let detail = format!("{}: {}", blocked.command, blocked.output_tail);
3736        state
3737            .resource_block
3738            .get_or_insert_with(|| crate::run::ResourceBlock {
3739                cause: crate::run::ResourceBlockCause::Other,
3740                node: node.into(),
3741                kind: "shared build cache".into(),
3742                detail: detail.clone(),
3743                at: jiff::Timestamp::now(),
3744            });
3745        state.event("resource", &detail);
3746        state.save()?;
3747        bail!("landing verification could not start: {detail}");
3748    }
3749    Ok(())
3750}
3751
3752/// Gate the local winner and publish that exact SHA, retaining the saved lease.
3753/// A push completed before a crash is recoverable only when its SHA was gated.
3754async fn publish_landing_head<F: Forge>(
3755    state: &mut RunState,
3756    observed: &str,
3757    pr_url: &str,
3758    forge: &F,
3759) -> Result<String> {
3760    crate::pr_head::ensure_owner(state)?;
3761    let winner = state.winner().cloned().context("landing has no winner")?;
3762    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
3763    let expected = state.pr_pushed_head.as_deref().unwrap_or(observed);
3764    anyhow::ensure!(
3765        observed == expected
3766            || (observed == head
3767                && state.gate_head.as_deref() == Some(&head)
3768                && state.gate_allows_progress()),
3769        "public head moved outside this run; refusing to overwrite it"
3770    );
3771    anyhow::ensure!(
3772        git::is_clean(&winner.worktree).await?,
3773        "landing worktree is dirty"
3774    );
3775    if state.gate_head.as_deref() != Some(&head)
3776        || !state.gate_ran
3777        || !state.gate_commands_allow_progress()
3778    {
3779        state.reconcile_verification_head(&head);
3780        state.gate.clear();
3781        state.gate_head = None;
3782        state.gate_ran = false;
3783        state.pre_gate.clear();
3784        state.pre_gate_commit = None;
3785        state.save()?;
3786        let inherited = crate::repo_lock::WaitPolicy::current();
3787        let wait = crate::repo_lock::WaitPolicy::new(
3788            Duration::from_secs(state.config.graph.timeout_resource_wait),
3789            move || inherited.cancelled(),
3790        );
3791        let mut outcomes = crate::graph::run_landing_gate(state, &winner, &wait).await?;
3792        loop {
3793            if outcomes.iter().any(|outcome| outcome.resource_blocked) {
3794                state.gate = outcomes.clone();
3795                check_landing_resources(state, "gate", &outcomes)?;
3796            }
3797            if outcomes.iter().all(|o| o.ok()) {
3798                break;
3799            }
3800            match Box::pin(crate::graph::repair_landing_gate(state, &winner, &outcomes)).await? {
3801                crate::graph::GateFix::Retry => {
3802                    outcomes = crate::graph::run_landing_gate(state, &winner, &wait).await?;
3803                }
3804                crate::graph::GateFix::Stop => break,
3805                crate::graph::GateFix::Defer => {
3806                    // The repair checks e2e immediately, before the next gate.
3807                    // Preserve a cache wait here as well as below; otherwise
3808                    // the daemon charges an attempt for unstarted verification.
3809                    if let Some(e2e) = &state.gate_repair_e2e {
3810                        let outcomes = e2e.outcomes.clone();
3811                        check_landing_resources(state, "e2e", &outcomes)?;
3812                    }
3813                    bail!("landing gate repair deferred");
3814                }
3815            }
3816        }
3817        state.gate = outcomes;
3818        state.gate_ran = true;
3819        state.save()?;
3820    }
3821    let inherited = crate::repo_lock::WaitPolicy::current();
3822    let wait = crate::repo_lock::WaitPolicy::new(
3823        Duration::from_secs(state.config.graph.timeout_resource_wait),
3824        move || inherited.cancelled(),
3825    );
3826    let checked = state
3827        .gate_head
3828        .clone()
3829        .context("landing gate has no checked SHA")?;
3830    anyhow::ensure!(
3831        git::rev_parse(&winner.worktree, "HEAD").await? == checked
3832            && git::is_clean(&winner.worktree).await?,
3833        "landing tree changed after gate"
3834    );
3835    let e2e = crate::graph::check_gate_repair_e2e(state, &winner, &wait).await?;
3836    if matches!(e2e, crate::graph::GateFix::Defer) {
3837        let outcomes = state
3838            .gate_repair_e2e
3839            .as_ref()
3840            .context("deferred landing e2e has no outcomes")?
3841            .outcomes
3842            .clone();
3843        check_landing_resources(state, "e2e", &outcomes)?;
3844    }
3845    anyhow::ensure!(
3846        matches!(e2e, crate::graph::GateFix::Retry),
3847        "post-repair e2e has not passed on the landing head; nothing published"
3848    );
3849    anyhow::ensure!(
3850        git::rev_parse(&winner.worktree, "HEAD").await? == checked
3851            && git::is_clean(&winner.worktree).await?,
3852        "landing tree changed during post-repair e2e"
3853    );
3854    anyhow::ensure!(
3855        crate::graph::verify_current_head(state, &winner, &wait).await?,
3856        "current head e2e has not passed; nothing published"
3857    );
3858    anyhow::ensure!(
3859        state.gate_allows_progress(),
3860        "landing gate failed; nothing published"
3861    );
3862    crate::pr_head::ensure_owner(state)?;
3863    if owner_requested_stop(state)? {
3864        bail!("owner requested stop before publication");
3865    }
3866    let current = forge.view(&state.repo, pr_url).await?;
3867    anyhow::ensure!(
3868        current.pr.state == PrLifecycle::Open,
3869        "PR closed or merged while gating; nothing published"
3870    );
3871    anyhow::ensure!(
3872        current.head == observed || current.head == checked,
3873        "PR head changed while gating; nothing published"
3874    );
3875    anyhow::ensure!(
3876        crate::foreign_checkout::write_back(state, &checked).await?,
3877        "foreign checkout delivery is blocked; see the run events"
3878    );
3879    let public = state.pr_branch().unwrap_or(&winner.branch).to_owned();
3880    let lease = format!("--force-with-lease=refs/heads/{public}:{observed}");
3881    let refspec = format!("{checked}:refs/heads/{public}");
3882    let lock = repo_merge_lock(&state.repo);
3883    let _slot = lock.lock().await;
3884    let pushed = git::git_raw(
3885        &winner.worktree,
3886        &["push", &lease, &state.config.merge.remote, &refspec],
3887    )
3888    .await?;
3889    anyhow::ensure!(
3890        pushed.ok(),
3891        "publishing gated landing head failed: {}",
3892        pushed.stderr
3893    );
3894    state.pr_pushed_head = Some(checked.clone());
3895    state.land_sync_pending = false;
3896    state.save()?;
3897    Ok(checked)
3898}
3899
3900/// A scratch rebase moves the winner ref before its index and files. Recover
3901/// only a tree proven unchanged since the saved start; never discard edits.
3902async fn restore_landing_worktree(state: &mut RunState) -> Result<()> {
3903    let winner = state.winner().cloned().context("landing has no winner")?;
3904    let inherited = crate::repo_lock::WaitPolicy::current();
3905    let wait = crate::repo_lock::WaitPolicy::new(
3906        Duration::from_secs(state.config.graph.timeout_resource_wait),
3907        move || inherited.cancelled(),
3908    );
3909    let _coordination = crate::repo_lock::SeatLease::operation_with(
3910        &winner.worktree,
3911        state.config.coordination.as_ref(),
3912        &wait,
3913    )
3914    .await?;
3915    if !git::is_clean(&winner.worktree).await? {
3916        let from = state
3917            .land_rebase_from
3918            .as_deref()
3919            .context("landing worktree is dirty")?;
3920        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
3921        anyhow::ensure!(head != from, "landing worktree is dirty");
3922        for args in [
3923            vec!["diff", "--cached", "--quiet", from],
3924            vec!["diff", "--quiet"],
3925        ] {
3926            anyhow::ensure!(
3927                git::git_raw(&winner.worktree, &args).await?.ok(),
3928                "landing worktree has edits beyond the interrupted rebase"
3929            );
3930        }
3931        // Preserve build artifacts and local files, including ignored ones.
3932        // read-tree can overwrite ignored paths, so reject collisions with
3933        // the new tree (including file/directory conflicts) before updating.
3934        let untracked = git::git(&winner.worktree, &["ls-files", "--others", "-z"]).await?;
3935        let tracked = git::git(
3936            &winner.worktree,
3937            &["ls-tree", "-r", "--name-only", "-z", "HEAD"],
3938        )
3939        .await?;
3940        for local in untracked.split('\0').filter(|p| !p.is_empty()) {
3941            anyhow::ensure!(
3942                !tracked.split('\0').filter(|p| !p.is_empty()).any(|path| {
3943                    path == local
3944                        || path
3945                            .strip_prefix(local)
3946                            .is_some_and(|rest| rest.starts_with('/'))
3947                        || local
3948                            .strip_prefix(path)
3949                            .is_some_and(|rest| rest.starts_with('/'))
3950                }),
3951                "landing worktree has an untracked or ignored path conflicting with HEAD: {local}"
3952            );
3953        }
3954        git::git(&winner.worktree, &["read-tree", "-m", "-u", "HEAD"]).await?;
3955    }
3956    if let (Some(checkout), Some(from)) = (&state.foreign_checkout, &state.land_rebase_from) {
3957        anyhow::ensure!(
3958            git::is_ancestor(&winner.worktree, &checkout.synced_head, from).await,
3959            "landing synchronization started outside the foreign checkout history"
3960        );
3961        if !git::is_ancestor(&winner.worktree, from, "HEAD").await {
3962            // The rebase's tree already includes the base and the fixer's
3963            // resolutions. Retain that exact tree, but join the pre-sync
3964            // history so delivery remains fast-forward. Keep the checkpoint
3965            // until this succeeds: a crash after rebase (or after this merge)
3966            // must recover through this same idempotent path before gating.
3967            git::git(
3968                &winner.worktree,
3969                &[
3970                    "-c",
3971                    "core.hooksPath=/dev/null",
3972                    "merge",
3973                    "--strategy=ours",
3974                    "--no-ff",
3975                    "--no-autostash",
3976                    "--no-edit",
3977                    "-m",
3978                    "Merge pre-sync history into the repaired landing tree",
3979                    from,
3980                ],
3981            )
3982            .await?;
3983        }
3984    }
3985    crate::worktree_setup::prepare(&state.config, &state.repo, &winner.worktree).await?;
3986    state.land_rebase_from = None;
3987    state.save()?;
3988    Ok(())
3989}
3990
3991async fn rebase_landing_worktree(
3992    state: &mut RunState,
3993    onto: &str,
3994) -> Result<crate::rebase::Rebased> {
3995    restore_landing_worktree(state).await?;
3996    let winner = state.winner().cloned().context("landing has no winner")?;
3997    let scratch = state.dir().join("rebase");
3998    let target = match state.land_sync_target.clone() {
3999        Some(target) => target,
4000        // Older records lack the target checkpoint, but Git retains the
4001        // exact target of an interrupted operation. It is a continuation too.
4002        None if git::rebase_in_progress(&scratch).await => {
4003            crate::rebase::rebase_target(&scratch).await?
4004        }
4005        None => {
4006            anyhow::ensure!(
4007                state.land_sync_attempts < state.config.graph.land_rounds,
4008                "landing base synchronization budget exhausted"
4009            );
4010            let target = git::rev_parse(&state.repo, onto).await?;
4011            state.land_sync_attempts += 1;
4012            state.land_sync_target = Some(target.clone());
4013            target
4014        }
4015    };
4016    state.land_sync_target = Some(target.clone());
4017    state.land_sync_pending = true;
4018    state.land_rebase_from = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
4019    state.save()?;
4020    // A continuation owns the attempt already charged above, including a
4021    // crash before the scratch rebase started. Finish its pinned base first;
4022    // a newer base must use another attempt on the next observation.
4023    let result = crate::rebase::rebase_with_fixer(state, &scratch, &winner.branch, &target).await?;
4024    state.land_sync_target = None;
4025    state.save()?;
4026    if result == crate::rebase::Rebased::Applied {
4027        restore_landing_worktree(state).await?;
4028    }
4029    Ok(result)
4030}
4031
4032/// Reconcile a stopped landing before changing its branch. This also handles
4033/// old records whose graph status or merge detail no longer identifies land.
4034async fn resume_landing_head<F: Forge>(
4035    state: &mut RunState,
4036    observed: &str,
4037    pr_url: &str,
4038    forge: &F,
4039    reason: Option<Blocking>,
4040) -> Result<String> {
4041    crate::pr_head::ensure_owner(state)?;
4042    let winner = state.winner().cloned().context("landing has no winner")?;
4043    let local = git::rev_parse(&winner.worktree, "HEAD").await?;
4044    let expected = state
4045        .pr_pushed_head
4046        .as_deref()
4047        .or(state.gate_head.as_deref())
4048        .context("missing public head lease")?;
4049    anyhow::ensure!(
4050        observed == expected
4051            || (observed == local
4052                && ((state.gate_head.as_deref() == Some(&local) && state.gate_allows_progress())
4053                    || git::is_ancestor(&winner.worktree, expected, &local).await)),
4054        "public head moved outside this run; refusing to sync"
4055    );
4056    // An operator may have extended and published the winner while approval
4057    // was pending. Matching local/public history can be adopted as the lease,
4058    // but publish_landing_head must gate its new SHA before proceeding. A
4059    // remote-only or divergent update still cannot be overwritten.
4060    // Save reconciliation before rebasing again; a prior push may have reached
4061    // the remote immediately before the previous driver's last save.
4062    state.pr_pushed_head = Some(observed.to_owned());
4063    state.save()?;
4064    restore_landing_worktree(state).await?;
4065    // Recover a rebase that finished before its completion checkpoint was
4066    // saved. Restoration above has already reconciled its files and ancestry.
4067    if let Some(target) = &state.land_sync_target
4068        && !git::rebase_in_progress(&state.dir().join("rebase")).await
4069        && git::ancestry(&winner.worktree, target, &local).await?
4070    {
4071        state.land_sync_target = None;
4072        state.save()?;
4073    }
4074    let remote = state.config.merge.remote.clone();
4075    let base = state.base_branch.clone();
4076    let fetched = git::fetch(&state.repo, &remote, &base).await?;
4077    anyhow::ensure!(
4078        fetched.ok(),
4079        "cannot fetch landing base: {}",
4080        fetched.stderr
4081    );
4082    anyhow::ensure!(
4083        !owner_requested_stop(state)?,
4084        "owner requested stop before base synchronization"
4085    );
4086    let onto = format!("{remote}/{base}");
4087    let tip = git::rev_parse(&state.repo, &onto).await?;
4088    let contains_base = git::ancestry(&state.repo, &tip, &local)
4089        .await
4090        .context("could not determine whether the landing head contains the fetched base")?;
4091    anyhow::ensure!(
4092        reason != Some(Blocking::Behind) || !contains_base,
4093        "BEHIND reported but the fetched base is already included; synchronization made no progress"
4094    );
4095    if !contains_base || reason == Some(Blocking::Conflict) {
4096        match rebase_landing_worktree(state, &onto).await? {
4097            crate::rebase::Rebased::Applied => {}
4098            crate::rebase::Rebased::Stopped(why) => bail!("landing rebase stopped: {why}"),
4099        }
4100    }
4101    if reason == Some(Blocking::Behind) {
4102        anyhow::ensure!(
4103            git::rev_parse(&winner.worktree, "HEAD").await? != local,
4104            "BEHIND synchronization left the head unchanged"
4105        );
4106    }
4107    publish_landing_head(state, observed, pr_url, forge).await
4108}
4109
4110/// Share the synchronization path with structured evidence retained after a refusal.
4111async fn synchronize_landing<F: Forge>(
4112    state: &mut RunState,
4113    pr: &mut PrState,
4114    observed: &str,
4115    pr_url: &str,
4116    forge: &F,
4117) -> Result<Option<String>> {
4118    if owner_stop(state, pr, forge).await? {
4119        return Ok(None);
4120    }
4121    state.event(
4122        "land",
4123        format!("{} base synchronization: {:?}", pr.url, pr.blocking),
4124    );
4125    state.save()?;
4126    let synced = resume_landing_head(state, observed, pr_url, forge, Some(pr.blocking)).await;
4127    if owner_stop(state, pr, forge).await? {
4128        return Ok(None);
4129    }
4130    match synced {
4131        Ok(head) => {
4132            if let Some(branch) = state.winner().map(|w| w.branch.clone()) {
4133                crate::graph::refresh_reviewed_commits(state, &branch).await;
4134            }
4135            Ok(Some(head))
4136        }
4137        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => Err(e),
4138        Err(e) => {
4139            let repo = state.repo.clone();
4140            stop(
4141                state,
4142                &repo,
4143                pr,
4144                &format!("could not synchronize landing base: {e:#}"),
4145            )
4146            .await?;
4147            Ok(None)
4148        }
4149    }
4150}
4151
4152async fn land_with<F: Forge>(state: &mut RunState, pr_url: &str, forge: &F) -> Result<PrState> {
4153    crate::pr_head::ensure_owner(state)?;
4154    state.land_unrelated = None;
4155    let reopening_hold = crate::merge_decision::resumable_hold(state);
4156    let repo = state.repo.clone();
4157    let budget = state.config.graph.land_rounds;
4158    let mut round = 0usize;
4159    let ci = state.config.merge.ci.expectation();
4160    if ci == CiExpectation::Absent {
4161        state.event(
4162            "land",
4163            "CI not expected ([merge] ci = \"none\"); check status ignored",
4164        );
4165    }
4166    let mut waited = Duration::ZERO;
4167    // Comment bodies the fixer has already been shown. A comment is
4168    // outstanding until it has been handed over once; after that it is a
4169    // recorded decision, not an open question, and re-feeding it would loop the
4170    // budget away on a comment the fixer already declined with an argument.
4171    let mut shown: BTreeSet<String> = BTreeSet::new();
4172    // Await the last successfully published head, including across resumes.
4173    let mut awaiting_head: Option<String> = state.pr_pushed_head.clone();
4174    // Whether a settled-checks refusal has already been given its one re-look.
4175    let mut rechecked = false;
4176
4177    // Marks the run resumable through exactly this function, not through a
4178    // fresh competition: `RunStatus::resumable` excludes only `Merged`,
4179    // `Ready` and `Failed`, and `merge`'s own re-entry guard looks for this
4180    // status specifically to know a resumed run belongs back in `land`
4181    // rather than at a second `gh pr create`. Set on every entry - fresh or
4182    // resumed - because a resume that parked here again must keep reading
4183    // `Landing`, not whatever a first pass through `merge` left behind.
4184    state.status = RunStatus::Landing;
4185    state.event("land", format!("watching {pr_url}"));
4186    state.save()?;
4187
4188    // An armed merge recorded by an earlier pass may or may not have reached
4189    // the forge (the record is written before the call). It is taken back on
4190    // the first observation, where a pull request is known to stop with.
4191    let mut resumed_armed = state.land_armed_head.is_some();
4192
4193    'landing: loop {
4194        let seen = forge.view(&repo, pr_url).await?;
4195        let mut pr = seen.pr.clone();
4196        pr.review_comments.retain(|c| !shown.contains(&c.body));
4197        state.pr = Some(crate::run::PrRecord {
4198            url: pr.url.clone(),
4199            number: pr.number,
4200            state: pr.state.as_str().to_owned(),
4201            checks: pr.checks.as_str().to_owned(),
4202            round,
4203            rounds: budget,
4204            red_at_merge: Vec::new(),
4205        });
4206        state.save()?;
4207
4208        if pr.state == PrLifecycle::Open {
4209            state.observe_branch_owner_holds(&seen.head).await;
4210            state.save()?;
4211        }
4212        crate::pr_head::ensure_owner(state)?;
4213        if reopening_hold {
4214            anyhow::ensure!(
4215                pr.state == PrLifecycle::Open,
4216                "held PR is no longer open; cannot request a fresh decision"
4217            );
4218            // An explicit resume authorizes a fresh question only. Preserve the
4219            // answered card, and never enter repair/rebase/merge on this pass.
4220            disarm(forge, state, &repo, pr.number)
4221                .await
4222                .map_err(anyhow::Error::msg)?;
4223            let previous = state.merge_decision.take();
4224            let binding = state.land_approval.take();
4225            state.config.graph.land_approval = true;
4226            let subject = merge_subject(
4227                crate::graph::landing_title(state, &seen.title),
4228                &crate::graph::landing_subject_source(state),
4229            );
4230            let contested = contested_to_ask(state);
4231            if let Err(error) =
4232                approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head).await
4233            {
4234                state.merge_decision = previous;
4235                state.land_approval = binding;
4236                return Err(error);
4237            }
4238            state.end_pass_parked(crate::run::ParkCause::Question);
4239            state.parked = true;
4240            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()));
4241            state.save()?;
4242            return Ok(pr);
4243        }
4244        if owner_stop(state, &mut pr, forge).await? {
4245            return Ok(pr);
4246        }
4247
4248        if std::mem::take(&mut resumed_armed) && pr.state == PrLifecycle::Open {
4249            // An approval already given for the same head is reused, so
4250            // nothing is asked twice. A failed disable
4251            // stops the run with the record kept: pushing on could change the
4252            // head under an arm that is still live.
4253            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4254                let why = format!(
4255                    "a previous pass may have armed auto-merge and it could not be disabled \
4256                     on resume: {e}"
4257                );
4258                stop(state, &repo, &pr, &why).await?;
4259                return Ok(pr);
4260            }
4261        }
4262
4263        // The head moved away from the one auto-merge was armed on, by
4264        // someone other than this loop. The arm is pinned and would refuse to
4265        // merge the new commit, but the approval was for the old one: take it
4266        // back and go through the normal path again.
4267        if pr.state == PrLifecycle::Open
4268            && !seen.head.is_empty()
4269            && state
4270                .land_armed_head
4271                .as_deref()
4272                .is_some_and(|armed| !armed.eq_ignore_ascii_case(&seen.head))
4273        {
4274            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4275                let why = format!(
4276                    "the head moved while auto-merge was armed and it could not be disabled: {e}"
4277                );
4278                stop(state, &repo, &pr, &why).await?;
4279                return Ok(pr);
4280            }
4281        }
4282
4283        if state.land_sync_pending && pr.state == PrLifecycle::Open {
4284            // Disarming can outlive an owner answer. Consume it before our
4285            // own rebase invalidates the head shown on the decision card.
4286            if owner_stop(state, &mut pr, forge).await? {
4287                return Ok(pr);
4288            }
4289            let repair_answer = state.land_approval.as_ref().is_some_and(|binding| {
4290                binding.head.eq_ignore_ascii_case(&seen.head)
4291                    && ask::Questions::open()
4292                        .get(&binding.question)
4293                        .is_ok_and(|q| {
4294                            q.run == state.id
4295                                && q.node == APPROVAL_NODE
4296                                && q.status == ask::QuestionStatus::Answered
4297                                && matches!(approval(q.resolution().as_deref()), Approval::Repair)
4298                        })
4299            });
4300            if repair_answer {
4301                let subject = merge_subject(
4302                    crate::graph::landing_title(state, &seen.title),
4303                    &crate::graph::landing_subject_source(state),
4304                );
4305                let contested = contested_to_ask(state);
4306                if matches!(
4307                    approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head).await?,
4308                    ApprovalGate::Repair
4309                ) {
4310                    if let Err(why) = disarm(forge, state, &repo, pr.number).await {
4311                        state.event("repair", format!("auto-merge could not be disabled: {why}; repair preflight will retry"));
4312                        state.save()?;
4313                    }
4314                    return Ok(pr);
4315                }
4316            }
4317            let synced = resume_landing_head(state, &seen.head, pr_url, forge, None).await;
4318            // A stop detected before publication must apply its durable
4319            // decision, even when verification returned an error meanwhile.
4320            if owner_stop(state, &mut pr, forge).await? {
4321                return Ok(pr);
4322            }
4323            let head = synced?;
4324            awaiting_head = Some(head);
4325            waited = Duration::ZERO;
4326            rechecked = false;
4327            // Read CI and approvals afresh, never from the pre-push observation.
4328            continue;
4329        }
4330
4331        // A stale base is independent of the CI rollup. Keep the public-head
4332        // lease, but synchronize before waiting for checks on the old tree.
4333        if pr.state == PrLifecycle::Open
4334            && pr.blocking == Blocking::Behind
4335            && bound_head(&seen.head, &seen.head, awaiting_head.as_deref()).is_some()
4336        {
4337            let synced = synchronize_landing(state, &mut pr, &seen.head, pr_url, forge).await?;
4338            let Some(head) = synced else {
4339                return Ok(pr);
4340            };
4341            awaiting_head = Some(head);
4342            rechecked = false;
4343            waited = Duration::ZERO;
4344            continue;
4345        }
4346
4347        if pr.state == PrLifecycle::Open {
4348            if bound_head(&seen.head, &seen.rollup_head, awaiting_head.as_deref()).is_none() {
4349                if waited >= WAIT_CEILING {
4350                    let want = awaiting_head.as_deref().unwrap_or_default();
4351                    let why = format!(
4352                        "the pull request's checks were still not about one readable head after \
4353                         {} minutes (expected {}, pull request points at {}, checks are for {}); \
4354                         someone may have pushed over it",
4355                        WAIT_CEILING.as_secs() / 60,
4356                        if want.is_empty() { "any" } else { want },
4357                        if seen.head.is_empty() {
4358                            "nothing readable"
4359                        } else {
4360                            &seen.head
4361                        },
4362                        if seen.rollup_head.is_empty() {
4363                            "nothing readable"
4364                        } else {
4365                            &seen.rollup_head
4366                        },
4367                    );
4368                    stop_disarmed(forge, state, &repo, &pr, &why).await?;
4369                    return Ok(pr);
4370                }
4371                waited += POLL;
4372                forge.poll().await;
4373                continue;
4374            }
4375            // Reset once, when the awaited head first shows up; resetting on
4376            // every re-observation would let a standing refusal wait forever.
4377            if awaiting_head.take().is_some() {
4378                // The checks now being read belong to the new head; give them
4379                // the same grace a fresh pull request gets.
4380                waited = Duration::ZERO;
4381            }
4382        }
4383
4384        // The merge-state grace is head-bound and durable. Reruns reset the
4385        // checks clock, but must not extend this deadline across resumes.
4386        let decision_wait = if pr.checks == Checks::Red && pr.blocking == Blocking::Unsaid {
4387            let first = state
4388                .land_unsaid
4389                .get_or_insert_with(|| (seen.head.clone(), forge.now()));
4390            if !first.0.eq_ignore_ascii_case(&seen.head) {
4391                *first = (seen.head.clone(), forge.now());
4392            }
4393            let elapsed = Duration::from_secs(forge.now().saturating_sub(first.1).max(0) as u64);
4394            state.save()?;
4395            elapsed
4396        } else {
4397            waited
4398        };
4399        let proposed = decide_with(&pr, round, budget, decision_wait, ci);
4400        if pr.checks == Checks::Red && pr.blocking == Blocking::Unsaid && proposed == Step::Wait {
4401            if waited >= WAIT_CEILING {
4402                stop_disarmed(
4403                    forge,
4404                    state,
4405                    &repo,
4406                    &pr,
4407                    "merge state remained unreadable; refusing to merge on a guess",
4408                )
4409                .await?;
4410                return Ok(pr);
4411            }
4412            waited += POLL;
4413            forge.poll().await;
4414            continue;
4415        }
4416
4417        // A failed workflow run is rerun once, judged by its own run rather
4418        // than by the rollup's aggregate: another run still pending, or a fix
4419        // budget already spent, must not keep a flaky failure from its one
4420        // rerun. It spends no round and no attempt.
4421        if ci == CiExpectation::Expected
4422            && pr.state == PrLifecycle::Open
4423            && state.config.graph.rerun_flaky_checks
4424        {
4425            let include_optional = pr.checks == Checks::Red
4426                && matches!(proposed, Step::Fix { .. } | Step::GiveUp { .. });
4427            let failing = rerunnable_with(&seen.contexts, include_optional);
4428            let now = forge.now();
4429            match rerun_step(&failing, state.land_reruns.as_ref(), &seen.head, now) {
4430                RerunStep::Rerun(runs) => {
4431                    let rec = state.land_reruns.get_or_insert_with(Default::default);
4432                    if !rec.head.eq_ignore_ascii_case(&seen.head) {
4433                        *rec = LandReruns {
4434                            head: seen.head.clone(),
4435                            runs: BTreeMap::new(),
4436                        };
4437                    }
4438                    for run in &runs {
4439                        rec.runs.insert(run.clone(), now);
4440                    }
4441                    // Durable before the call: a restart must not
4442                    // rerun the same run twice. A save that fails
4443                    // means no rerun.
4444                    state.save()?;
4445                    let mut any = false;
4446                    for run in &runs {
4447                        let names = failing
4448                            .iter()
4449                            .filter(|(_, r)| r.as_deref() == Some(run))
4450                            .map(|(l, _)| l.as_str())
4451                            .collect::<Vec<_>>()
4452                            .join(", ");
4453                        match forge.rerun(&repo, run).await {
4454                            Ok(()) => {
4455                                any = true;
4456                                state.event(
4457                                    "land",
4458                                    format!("reran failed check(s) {names} (run {run})"),
4459                                );
4460                            }
4461                            // Stays recorded: never a retry loop.
4462                            Err(e) => state.event(
4463                                "land",
4464                                format!("could not rerun check(s) {names} (run {run}): {e:#}"),
4465                            ),
4466                        }
4467                    }
4468                    state.save()?;
4469                    if any {
4470                        waited = Duration::ZERO;
4471                        forge.poll().await;
4472                        continue;
4473                    }
4474                }
4475                RerunStep::Grace => {
4476                    if waited >= WAIT_CEILING {
4477                        let why = format!(
4478                            "checks were still failing after a rerun and {} minutes",
4479                            WAIT_CEILING.as_secs() / 60
4480                        );
4481                        stop(state, &repo, &pr, &why).await?;
4482                        return Ok(pr);
4483                    }
4484                    waited += POLL;
4485                    forge.poll().await;
4486                    continue;
4487                }
4488                RerunStep::Fix => {}
4489            }
4490        }
4491
4492        let step = proposed;
4493        // Armed on exactly this head: the forge is doing the waiting. A
4494        // decision to merge (or keep waiting) is only watched, never re-armed
4495        // and never re-approved; anything else - a red check, a comment, a
4496        // conflict - falls through to its own arm, which disarms first.
4497        let armed_here = state
4498            .land_armed_head
4499            .as_deref()
4500            .is_some_and(|armed| armed.eq_ignore_ascii_case(&seen.head));
4501        if armed_here && matches!(step, Step::Merge | Step::Wait) {
4502            if waited >= WAIT_CEILING {
4503                let required = if seen.base.is_empty() {
4504                    None
4505                } else {
4506                    forge.required_contexts(&repo, &seen.base).await
4507                };
4508                let why = format!(
4509                    "auto-merge was armed on {} but the pull request did not merge within {} \
4510                     minutes ({})",
4511                    seen.head,
4512                    WAIT_CEILING.as_secs() / 60,
4513                    waiting_on(&seen.merge_state, &seen.contexts, required.as_ref())
4514                );
4515                stop_disarmed(forge, state, &repo, &pr, &why).await?;
4516                return Ok(pr);
4517            }
4518            waited += POLL;
4519            forge.poll().await;
4520            continue;
4521        }
4522        if armed_here && !matches!(step, Step::Done { .. }) {
4523            // Not merging or waiting any more: whatever is next may change the
4524            // head or give up, and neither may leave the arm standing.
4525            if let Err(e) = disarm(forge, state, &repo, pr.number).await {
4526                let why = format!("auto-merge could not be disabled: {e}");
4527                stop(state, &repo, &pr, &why).await?;
4528                return Ok(pr);
4529            }
4530        }
4531        if pr.checks == Checks::Red
4532            && matches!(step, Step::Fix { .. } | Step::GiveUp { .. })
4533            && pr.review_comments.is_empty()
4534            && let Some(evidence) = forge.attribution(state, &seen).await
4535            && evidence.unrelated(&seen.head, &pr.failing)
4536        {
4537            if owner_stop(state, &mut pr, forge).await? {
4538                return Ok(pr);
4539            }
4540            // Attribution does not authorize action against an unseen push.
4541            let fresh = forge.view(&repo, pr_url).await?;
4542            if fresh.head != seen.head
4543                || fresh.rollup_head != seen.rollup_head
4544                || fresh.pr.state != PrLifecycle::Open
4545                || fresh.pr.checks != Checks::Red
4546                || fresh.pr.failing != pr.failing
4547                || fresh
4548                    .pr
4549                    .review_comments
4550                    .iter()
4551                    .any(|c| !shown.contains(&c.body))
4552            {
4553                continue;
4554            }
4555            hold_unrelated(state, &pr, evidence).await?;
4556            return Ok(pr);
4557        }
4558        match step {
4559            Step::Wait => {
4560                if waited >= WAIT_CEILING {
4561                    let why = format!(
4562                        "checks were still running after {} minutes",
4563                        WAIT_CEILING.as_secs() / 60
4564                    );
4565                    stop(state, &repo, &pr, &why).await?;
4566                    return Ok(pr);
4567                }
4568                waited += POLL;
4569                forge.poll().await;
4570            }
4571            Step::Done { merged } => {
4572                if merged {
4573                    state.pr_merged_head = (!seen.head.is_empty()).then(|| seen.head.clone());
4574                }
4575                // Auto-merge is pinned to the approved head, but the forge's
4576                // own handling of a later push is not something magi can
4577                // see: if the pull request merged on another commit, say so
4578                // loudly rather than record a clean landing.
4579                if let Some(armed) = state.land_armed_head.take() {
4580                    if merged && !seen.head.is_empty() && !armed.eq_ignore_ascii_case(&seen.head) {
4581                        let msg = format!(
4582                            "{} merged on {} but the owner approved {armed}; review what landed",
4583                            pr.url, seen.head
4584                        );
4585                        tracing::warn!("{msg}");
4586                        state.event("land", msg);
4587                        // Only an arm left by an older build can get here.
4588                        // The wording is fixed so a repeat does not relight
4589                        // the notice.
4590                        crate::notices::raise_with(
4591                            crate::notices::Notice::warn(
4592                                &format!("merged-unapproved-head:{}", state.id),
4593                                "A pull request merged on a commit the owner did not approve; \
4594                                 review what landed",
4595                            )
4596                            .link(crate::notices::Link::Run {
4597                                id: state.id.clone(),
4598                            }),
4599                            &state.config.notify,
4600                        );
4601                    }
4602                }
4603                state.status = if merged {
4604                    RunStatus::Merged
4605                } else {
4606                    RunStatus::Ready
4607                };
4608                let detail = if merged {
4609                    format!("{} was merged", pr.url)
4610                } else {
4611                    format!("{} was closed without merging", pr.url)
4612                };
4613                state.merge = Some(MergeOutcome {
4614                    mode: MergeMode::Pr,
4615                    ok: merged,
4616                    detail: detail.clone(),
4617                    empty: false,
4618                });
4619                state.event("land", detail);
4620                state.save()?;
4621                write_pr_state_through(state, pr.state);
4622                return Ok(pr);
4623            }
4624            Step::Merge => {
4625                state.check_delivery_evidence(&seen.head)?;
4626                let subject = merge_subject(
4627                    crate::graph::landing_title(state, &seen.title),
4628                    &crate::graph::landing_subject_source(state),
4629                );
4630                // The owner sees the panel before the one irreversible step,
4631                // and an unanswered question is a hold: silence never merges.
4632                //
4633                // The dedicated policy includes existing consent and post-repair
4634                // decisions; repair choice availability never grants merge authority.
4635                let contested = contested_to_ask(state);
4636                if !approval_reasons(state).is_empty() {
4637                    match approval_gate(state, &pr, &subject, contested.as_ref(), &seen.head)
4638                        .await?
4639                    {
4640                        ApprovalGate::Approved => {}
4641                        ApprovalGate::Repair => {
4642                            // The driver consumes the saved request under the existing
4643                            // run/task claim. No merge, no second run or task.
4644                            if let Err(why) = disarm(forge, state, &repo, pr.number).await {
4645                                state.event("repair", format!("auto-merge could not be disabled: {why}; repair preflight will retry"));
4646                                state.save()?;
4647                            }
4648                            return Ok(pr);
4649                        }
4650                        ApprovalGate::Held => {
4651                            // Another entry point may have saved a stop after
4652                            // the first read above. Apply its durable action.
4653                            if owner_stop(state, &mut pr, forge).await? {
4654                                return Ok(pr);
4655                            }
4656                            stop(
4657                                state,
4658                                &repo,
4659                                &pr,
4660                                "the owner did not approve the merge (held or unanswered)",
4661                            )
4662                            .await?;
4663                            return Ok(pr);
4664                        }
4665                        // Filed (or still standing from an earlier visit) and
4666                        // not yet answered. Park here rather than wait: the
4667                        // question survives on disk, the daemon hands this
4668                        // run's slot to something else, and a later resume
4669                        // re-enters `land`, finds the same question, and
4670                        // either merges or stops depending on what it says
4671                        // by then.
4672                        ApprovalGate::Pending => {
4673                            state.end_pass_parked(crate::run::ParkCause::Question);
4674                            state.parked = true;
4675                            state.event(
4676                                "land",
4677                                "parked awaiting merge approval - resumes once answered",
4678                            );
4679                            state.save()?;
4680                            return Ok(pr);
4681                        }
4682                    }
4683                }
4684                // Open and past the gate above, so `seen.head` is the commit
4685                // the checks were bound to and the owner approved.
4686                //
4687                // Merge directly, bound to that commit. Auto-merge is not
4688                // armed any more: the forge checks `--match-head-commit` only
4689                // when the request is made, so an arm outlives the head it
4690                // was made for, and a push of another commit whose
4691                // requirements are met first would merge without approval.
4692                // A direct merge is checked by the forge at the moment it
4693                // happens, so only the approved head can land.
4694                let observed_head = seen.head.clone();
4695                // Read the pull request again just before: the state seen
4696                // above can be a moment old.
4697                {
4698                    let fresh = forge.view(&repo, pr_url).await.ok();
4699                    if fresh.as_ref().is_some_and(|current| {
4700                        current.pr.state == PrLifecycle::Open
4701                            && current.head.eq_ignore_ascii_case(&observed_head)
4702                            && Blocking::of(&current.merge_state) == Blocking::Behind
4703                    }) {
4704                        pr.blocking = Blocking::Behind;
4705                        let synced =
4706                            synchronize_landing(state, &mut pr, &observed_head, pr_url, forge)
4707                                .await?;
4708                        let Some(head) = synced else {
4709                            return Ok(pr);
4710                        };
4711                        awaiting_head = Some(head);
4712                        rechecked = false;
4713                        waited = Duration::ZERO;
4714                        continue 'landing;
4715                    }
4716                    if !direct_merge_is_safe(
4717                        fresh.as_ref(),
4718                        &observed_head,
4719                        &shown,
4720                        round,
4721                        budget,
4722                        waited,
4723                        ci,
4724                    ) {
4725                        if waited >= WAIT_CEILING {
4726                            let why = "the pull request did not settle on the approved head \
4727                                       before it could be merged";
4728                            stop(state, &repo, &pr, why).await?;
4729                            return Ok(pr);
4730                        }
4731                        state.event(
4732                            "land",
4733                            "the pull request changed before merging; looking again",
4734                        );
4735                        waited += POLL;
4736                        forge.poll().await;
4737                        continue;
4738                    }
4739                }
4740                let argv = merge_argv_at(pr.number, &subject, &observed_head);
4741                let out = {
4742                    let merge_lock = repo_merge_lock(&repo);
4743                    let _merge_slot = merge_lock.lock().await;
4744                    crate::pr_head::ensure_owner(state)?;
4745                    if let Some(task_id) = state
4746                        .origin
4747                        .as_ref()
4748                        .and_then(|origin| origin.task.as_ref())
4749                    {
4750                        let task = crate::queue::Queue::open()
4751                            .get(task_id)
4752                            .context("cannot verify the task owner immediately before merge")?;
4753                        if task.execution_runs().last() != Some(&state.id)
4754                            || task.operator_held()
4755                            || task.status == crate::queue::TaskStatus::Done
4756                        {
4757                            bail!(
4758                                "task ownership or an operator hold superseded this merge approval"
4759                            );
4760                        }
4761                    }
4762                    if let Some(binding) = &state.land_approval {
4763                        let current = ask::Questions::open().get(&binding.question)?;
4764                        if merge_consent_superseded(state, &current)?
4765                            || current.run != state.id
4766                            || !binding.head.eq_ignore_ascii_case(&observed_head)
4767                            || approval(current.resolution().as_deref()) != Approval::Merge
4768                            || current.merge_target.as_ref().is_some_and(|t| {
4769                                t.pr != pr.url || !t.head.eq_ignore_ascii_case(&observed_head)
4770                            })
4771                        {
4772                            bail!(
4773                                "merge decision is stale or no longer authorizes the reviewed head"
4774                            );
4775                        }
4776                    }
4777                    forge.merge(&repo, &argv).await?
4778                };
4779                if out.0 {
4780                    // Exit 0 is not proof of a merge: with a merge queue `gh`
4781                    // enqueues (or reports the pull request already queued)
4782                    // and succeeds while it is still open. Ask the forge; an
4783                    // unreadable answer is not a confirmation either, so it
4784                    // is looked at again rather than recorded as merged.
4785                    let confirmed = forge.view(&repo, pr_url).await.is_ok_and(|c| {
4786                        if c.pr.state == PrLifecycle::Merged {
4787                            state.pr_merged_head = (!c.head.is_empty()).then_some(c.head);
4788                            true
4789                        } else {
4790                            false
4791                        }
4792                    });
4793                    if !confirmed {
4794                        if waited >= WAIT_CEILING {
4795                            let why = "the merge request succeeded but the pull request \
4796                                       could not be confirmed merged after waiting";
4797                            stop(state, &repo, &pr, why).await?;
4798                            return Ok(pr);
4799                        }
4800                        state.event(
4801                            "land",
4802                            "merge accepted but the pull request is not confirmed merged yet; waiting",
4803                        );
4804                        state.save()?;
4805                        waited += POLL;
4806                        forge.poll().await;
4807                        continue;
4808                    }
4809                    pr.state = PrLifecycle::Merged;
4810                    state.status = RunStatus::Merged;
4811                    state.merge = Some(MergeOutcome {
4812                        mode: MergeMode::Pr,
4813                        ok: true,
4814                        detail: format!("gh {}", argv.join(" ")),
4815                        empty: false,
4816                    });
4817                    // The last `state.pr` snapshot is whatever the poll before
4818                    // this merge observed - still `open` - and nothing below
4819                    // refreshes it from GitHub again, so the UI's round rail
4820                    // would otherwise keep animating a merged run forever.
4821                    if let Some(pr_record) = state.pr.as_mut() {
4822                        pr_record.state = pr.state.as_str().to_owned();
4823                    }
4824                    state.event("land", format!("merged {} as `{subject}`", pr.url));
4825                    announce_red_merge(state, &pr).await;
4826                    state.save()?;
4827                    write_pr_state_through(state, pr.state);
4828                    return Ok(pr);
4829                }
4830                let after_seen = forge.view(&repo, pr_url).await.ok();
4831                let after = after_seen.as_ref().map(|s| s.pr.state);
4832                if let Some(outcome) = merged_after_all(&argv, &out.1, after) {
4833                    state.pr_merged_head = after_seen
4834                        .as_ref()
4835                        .map(|s| s.head.clone())
4836                        .filter(|h| !h.is_empty());
4837                    pr.state = PrLifecycle::Merged;
4838                    state.status = RunStatus::Merged;
4839                    state.merge = Some(outcome);
4840                    if let Some(pr_record) = state.pr.as_mut() {
4841                        pr_record.state = pr.state.as_str().to_owned();
4842                    }
4843                    state.event("land", format!("merged {} as `{subject}`", pr.url));
4844                    announce_red_merge(state, &pr).await;
4845                    state.save()?;
4846                    write_pr_state_through(state, pr.state);
4847                    return Ok(pr);
4848                }
4849                let verdict = classify_refusal(after_seen.as_ref(), rechecked, &observed_head, ci);
4850                match verdict {
4851                    Refused::Behind => {
4852                        pr.blocking = Blocking::Behind;
4853                        let synced =
4854                            synchronize_landing(state, &mut pr, &observed_head, pr_url, forge)
4855                                .await?;
4856                        let Some(head) = synced else {
4857                            return Ok(pr);
4858                        };
4859                        awaiting_head = Some(head);
4860                        rechecked = false;
4861                        waited = Duration::ZERO;
4862                        continue 'landing;
4863                    }
4864                    Refused::Final => {
4865                        let merge_state = after_seen
4866                            .as_ref()
4867                            .map(|s| s.merge_state.as_str())
4868                            .filter(|m| !m.is_empty())
4869                            .unwrap_or("unknown");
4870                        // Which refusal this was decides what a person has to
4871                        // do about it, so the two are worded apart; both carry
4872                        // the forge's own message.
4873                        let why = format!(
4874                            "the merge was refused: {} (merge state: {merge_state})",
4875                            out.1
4876                        );
4877                        stop(state, &repo, &pr, &why).await?;
4878                        return Ok(pr);
4879                    }
4880                    verdict => {
4881                        // Back to the top, which re-decides and passes the
4882                        // approval gate again, a poll later. `waited` is not
4883                        // reset here: only a pushed fix restarts it, or a
4884                        // standing refusal would wait forever.
4885                        if waited >= WAIT_CEILING {
4886                            let why = format!(
4887                                "the merge was still refused after {} minutes: {}",
4888                                WAIT_CEILING.as_secs() / 60,
4889                                out.1
4890                            );
4891                            stop(state, &repo, &pr, &why).await?;
4892                            return Ok(pr);
4893                        }
4894                        if verdict == Refused::Recheck {
4895                            rechecked = true;
4896                        }
4897                        state.event(
4898                            "land",
4899                            "merge refused while the branch policy is not satisfied yet; waiting",
4900                        );
4901                        state.save()?;
4902                        waited += POLL;
4903                        forge.poll().await;
4904                    }
4905                }
4906            }
4907            Step::Rebase => {
4908                let synced = synchronize_landing(state, &mut pr, &seen.head, pr_url, forge).await?;
4909                let Some(head) = synced else {
4910                    return Ok(pr);
4911                };
4912                awaiting_head = Some(head);
4913                rechecked = false;
4914                waited = Duration::ZERO;
4915                continue 'landing;
4916            }
4917            Step::GiveUp { reason } => {
4918                stop(state, &repo, &pr, &reason).await?;
4919                return Ok(pr);
4920            }
4921            Step::Fix { reason } => {
4922                round += 1;
4923                waited = Duration::ZERO;
4924                for c in &pr.review_comments {
4925                    shown.insert(c.body.clone());
4926                }
4927                state.event("land", format!("round {round}: {reason}"));
4928                state.save()?;
4929
4930                let logs = failing_logs(&repo, &seen.failing_urls).await;
4931                let was_red = pr.checks == Checks::Red;
4932                if owner_stop(state, &mut pr, forge).await? {
4933                    return Ok(pr);
4934                }
4935                let fixed = forge.fix(state, &pr, round, budget, &reason, &logs).await?;
4936                if owner_stop(state, &mut pr, forge).await? {
4937                    return Ok(pr);
4938                }
4939                match fixed {
4940                    Fixed::Committed { head } => {
4941                        // Whatever the next look shows may still be the
4942                        // previous head; see `awaiting_new_head`.
4943                        state.pr_pushed_head = Some(head.clone());
4944                        awaiting_head = Some(head);
4945                        rechecked = false;
4946                        waited = Duration::ZERO;
4947                        forge.poll().await;
4948                    }
4949                    Fixed::Declined if was_red => {
4950                        // Review comments may have required this round even
4951                        // when CI was unrelated. Once the fixer has read them,
4952                        // use the same structural attribution before charging
4953                        // a no-commit stop to the task.
4954                        if let Some(evidence) = forge.attribution(state, &seen).await
4955                            && evidence.unrelated(&seen.head, &pr.failing)
4956                        {
4957                            let fresh = forge.view(&repo, pr_url).await?;
4958                            if fresh.head != seen.head
4959                                || fresh.rollup_head != seen.rollup_head
4960                                || fresh.pr.state != PrLifecycle::Open
4961                                || fresh.pr.checks != Checks::Red
4962                                || fresh.pr.failing != pr.failing
4963                                || fresh
4964                                    .pr
4965                                    .review_comments
4966                                    .iter()
4967                                    .any(|c| !shown.contains(&c.body))
4968                            {
4969                                continue;
4970                            }
4971                            if owner_stop(state, &mut pr, forge).await? {
4972                                return Ok(pr);
4973                            }
4974                            hold_unrelated(state, &pr, evidence).await?;
4975                            return Ok(pr);
4976                        }
4977                        let why = format!(
4978                            "the fixer produced no commit while {} check(s) were failing \
4979                             ({}); stopping instead of looping on an unchanged tree",
4980                            pr.failing.len(),
4981                            pr.failing.join(", ")
4982                        );
4983                        stop(state, &repo, &pr, &why).await?;
4984                        return Ok(pr);
4985                    }
4986                    // Comment-driven round with no commit: the fixer read the
4987                    // comments and changed nothing, which is a decision it is
4988                    // allowed to make. The comments are recorded as shown, so
4989                    // the next observation sees a clean pull request.
4990                    Fixed::Declined => state.event(
4991                        "land",
4992                        format!("round {round}: fixer declined the comments, nothing committed"),
4993                    ),
4994                    Fixed::Deferred => {
4995                        // No fixer was available to judge these comments or
4996                        // checks. Keep the previous completed-round count and
4997                        // return without handing the PR off as a task failure.
4998                        state.status = RunStatus::Blocked;
4999                        state.save()?;
5000                        return Ok(pr);
5001                    }
5002                    Fixed::Failed(why) => {
5003                        stop(state, &repo, &pr, &format!("the fix round failed: {why}")).await?;
5004                        return Ok(pr);
5005                    }
5006                }
5007                state.save()?;
5008            }
5009        }
5010    }
5011}
5012
5013/// Owner decision for a CI failure independently reproduced on the base.
5014pub const CI_HOLD_NODE: &str = "land-ci-unrelated";
5015
5016/// Durable machine-hold evidence, bound to one observed PR head.
5017#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5018pub struct CiHold {
5019    /// Head that exhibited the independently reproduced failures.
5020    pub head: String,
5021    /// Typed owner question controlling resumption.
5022    pub question: String,
5023    /// Complete structured facts used to attribute the failures.
5024    pub evidence: CiEvidence,
5025}
5026
5027/// Only structured forge annotations are compared, never log prose.
5028#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
5029struct CiFailure {
5030    path: String,
5031    start_line: u64,
5032    end_line: u64,
5033    title: String,
5034    message: String,
5035}
5036
5037#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5038struct CiCheckEvidence {
5039    label: String,
5040    head_check: u64,
5041    base_check: u64,
5042    app: u64,
5043    run: String,
5044    base_run: String,
5045    head_failures: Vec<CiFailure>,
5046    base_failures: Vec<CiFailure>,
5047    rerun_exhausted: bool,
5048}
5049
5050/// Pinned Git diff and forge failure annotations used for CI attribution.
5051#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5052pub struct CiEvidence {
5053    head: String,
5054    base: String,
5055    changed: Vec<String>,
5056    checks: Vec<CiCheckEvidence>,
5057}
5058
5059impl CiEvidence {
5060    /// Every red check must have the same located failure on the base, outside
5061    /// the diff. Changes to CI/build configuration invalidate this inference.
5062    fn unrelated(&self, head: &str, failing: &[String]) -> bool {
5063        if self.head != head
5064            || self.base.is_empty()
5065            || failing.is_empty()
5066            || self.changed.iter().any(|p| {
5067                p.starts_with(".github/")
5068                    || p.starts_with(".config/")
5069                    || p.starts_with(".cargo/")
5070                    || matches!(
5071                        p.rsplit('/').next().unwrap_or(p),
5072                        "Cargo.toml"
5073                            | "Cargo.lock"
5074                            | "Makefile.toml"
5075                            | "build.rs"
5076                            | "rust-toolchain.toml"
5077                    )
5078            })
5079        {
5080            return false;
5081        }
5082        failing.iter().all(|label| {
5083            let matches: Vec<_> = self.checks.iter().filter(|c| &c.label == label).collect();
5084            matches.len() == 1
5085                && matches[0].rerun_exhausted
5086                && !matches[0].head_failures.is_empty()
5087                && matches[0].head_failures.iter().all(|f| {
5088                    // Workflow-level exit-code annotations do not identify a
5089                    // failing test or source file, and prove nothing here.
5090                    !f.path.is_empty()
5091                        && !f.path.starts_with('.')
5092                        && !f.path.contains("..")
5093                        && !f.path.starts_with('/')
5094                        && !self.changed.contains(&f.path)
5095                        && matches[0].base_failures.contains(f)
5096                })
5097        })
5098    }
5099}
5100
5101async fn ci_json(repo: &Path, endpoint: String) -> Option<serde_json::Value> {
5102    let (ok, body) = gh(repo, &["api".into(), endpoint]).await.ok()?;
5103    if !ok {
5104        return None;
5105    }
5106    serde_json::from_str(&body).ok()
5107}
5108
5109async fn ci_annotations(repo: &Path, check: &serde_json::Value) -> Option<Vec<CiFailure>> {
5110    let count = check.pointer("/output/annotations_count")?.as_u64()?;
5111    if count == 0 || count >= 100 {
5112        return None;
5113    }
5114    let id = check.get("id")?.as_u64()?;
5115    let value = ci_json(
5116        repo,
5117        format!("repos/{{owner}}/{{repo}}/check-runs/{id}/annotations?per_page=100"),
5118    )
5119    .await?;
5120    let annotations = value.as_array()?;
5121    if annotations.len() != count as usize {
5122        return None;
5123    }
5124    annotations
5125        .iter()
5126        .filter(|a| a["annotation_level"] == "failure")
5127        .map(|a| {
5128            Some(CiFailure {
5129                path: a["path"].as_str()?.into(),
5130                start_line: a["start_line"].as_u64()?,
5131                end_line: a["end_line"].as_u64()?,
5132                title: a["title"].as_str()?.into(),
5133                message: a["message"].as_str()?.into(),
5134            })
5135        })
5136        .collect()
5137}
5138
5139async fn ci_runs(repo: &Path, sha: &str) -> Option<Vec<serde_json::Value>> {
5140    let value = ci_json(
5141        repo,
5142        format!("repos/{{owner}}/{{repo}}/commits/{sha}/check-runs?per_page=100&filter=latest"),
5143    )
5144    .await?;
5145    let runs = value["check_runs"].as_array()?;
5146    if value["total_count"].as_u64()? != runs.len() as u64 || runs.len() >= 100 {
5147        return None;
5148    }
5149    Some(runs.clone())
5150}
5151
5152async fn collect_ci_evidence(state: &RunState, seen: &Seen) -> Option<CiEvidence> {
5153    let repo = &state.repo;
5154    let base_ref = format!("refs/remotes/{}/{}", state.config.merge.remote, seen.base);
5155    let base = git::git_raw(repo, &["rev-parse", "--verify", &base_ref])
5156        .await
5157        .ok()?;
5158    if !base.ok() {
5159        return None;
5160    }
5161    let range = format!("{}...{}", base.stdout, seen.head);
5162    // No rename detection: both old and new paths must count as changed.
5163    let diff = git::git_raw(
5164        repo,
5165        &["diff", "--no-renames", "--name-only", "-z", &range, "--"],
5166    )
5167    .await
5168    .ok()?;
5169    if !diff.ok() {
5170        return None;
5171    }
5172    let head_runs = ci_runs(repo, &seen.head).await?;
5173    let base_runs = ci_runs(repo, &base.stdout).await?;
5174    let mut checks = Vec::new();
5175    for label in &seen.pr.failing {
5176        let matching = |runs: &[serde_json::Value]| {
5177            runs.iter()
5178                .filter(|r| r["name"].as_str() == Some(label))
5179                .cloned()
5180                .collect::<Vec<_>>()
5181        };
5182        let heads = matching(&head_runs);
5183        let bases = matching(&base_runs);
5184        if heads.len() != 1 || bases.len() != 1 {
5185            return None;
5186        }
5187        let h = &heads[0];
5188        let b = &bases[0];
5189        if h["conclusion"] != "failure"
5190            || b["conclusion"] != "failure"
5191            || h["status"] != "completed"
5192            || b["status"] != "completed"
5193            || h["head_sha"].as_str()? != seen.head
5194            || b["head_sha"].as_str()? != base.stdout
5195            || h.pointer("/app/id")?.as_u64()? != b.pointer("/app/id")?.as_u64()?
5196        {
5197            return None;
5198        }
5199        let run = run_of(h["details_url"].as_str()?)?;
5200        let contexts: Vec<_> = seen.contexts.iter().filter(|c| &c.label == label).collect();
5201        if contexts.len() != 1
5202            || contexts[0].run.as_ref() != Some(&run)
5203            || contexts[0].verdict != Verdict::Fail
5204        {
5205            return None;
5206        }
5207        // A persisted request alone is not a completed rerun: require the
5208        // workflow's structured attempt number as well.
5209        let workflow =
5210            ci_json(repo, format!("repos/{{owner}}/{{repo}}/actions/runs/{run}")).await?;
5211        let base_run = run_of(b["details_url"].as_str()?)?;
5212        let base_workflow = ci_json(
5213            repo,
5214            format!("repos/{{owner}}/{{repo}}/actions/runs/{base_run}"),
5215        )
5216        .await?;
5217        if base_workflow["head_sha"].as_str()? != base.stdout
5218            || base_workflow["head_branch"].as_str()? != seen.base
5219            || base_workflow["status"] != "completed"
5220            || base_workflow["conclusion"] != "failure"
5221            || base_workflow["workflow_id"].as_u64()? != workflow["workflow_id"].as_u64()?
5222        {
5223            return None;
5224        }
5225        let exhausted = state
5226            .land_reruns
5227            .as_ref()
5228            .is_some_and(|r| r.head == seen.head && r.runs.contains_key(&run))
5229            && workflow["head_sha"].as_str()? == seen.head
5230            && workflow["run_attempt"].as_u64()? > 1
5231            && workflow["status"] == "completed";
5232        checks.push(CiCheckEvidence {
5233            label: label.clone(),
5234            head_check: h["id"].as_u64()?,
5235            base_check: b["id"].as_u64()?,
5236            app: h.pointer("/app/id")?.as_u64()?,
5237            run,
5238            base_run,
5239            head_failures: ci_annotations(repo, h).await?,
5240            base_failures: ci_annotations(repo, b).await?,
5241            rerun_exhausted: exhausted,
5242        });
5243    }
5244    Some(CiEvidence {
5245        head: seen.head.clone(),
5246        base: base.stdout,
5247        changed: diff
5248            .stdout
5249            .split('\0')
5250            .filter(|p| !p.is_empty())
5251            .map(str::to_owned)
5252            .collect(),
5253        checks,
5254    })
5255}
5256
5257async fn hold_unrelated(state: &mut RunState, pr: &PrState, evidence: CiEvidence) -> Result<()> {
5258    let detail = serde_json::to_string(&evidence)?;
5259    let resume = "daemon: CI を確認して同じ run を再開する".to_owned();
5260    let hold = "operator: 保留して後で判断する".to_owned();
5261    let mut q = ask::Question::new(
5262        state.id.clone(),
5263        CI_HOLD_NODE.into(),
5264        "land".into(),
5265        "base でも再現する CI の失敗を検出したため、試行を消費せず保留しました".into(),
5266        format!(
5267            "必須チェックや承認は省略しません。再開時にも同じ workflow run は自動再実行しません。\n構造化された判定根拠:\n{detail}"
5268        ),
5269        vec![resume.clone(), hold.clone()],
5270    );
5271    q.actions.insert(
5272        resume,
5273        ask::ChoiceAction::Resume {
5274            run: state.id.clone(),
5275        },
5276    );
5277    q.actions.insert(hold, ask::ChoiceAction::Hold);
5278    ask::Questions::open().put_executable(&mut q)?;
5279    state.land_unrelated = Some(CiHold {
5280        head: evidence.head.clone(),
5281        question: q.id.clone(),
5282        evidence,
5283    });
5284    state.event("land", format!("[ci-unrelated] base reproduces every located failure after rerun; owner question {}: {detail}", q.id));
5285    state.end_pass_parked(crate::run::ParkCause::Question);
5286    state.parked = true;
5287    state.save()?;
5288    if let Err(e) = ask::notify(&state.config.notify, &q).await {
5289        tracing::warn!("could not notify about CI hold: {e:#}");
5290    }
5291    // A durable question and evidence are sufficient even if commenting fails.
5292    let body = stop_comment(
5293        &state.id,
5294        "CI failures independently reproduced on the base; awaiting an owner decision without charging the task attempt",
5295    );
5296    let (_, body) = crate::github_text::prepare(state, "", &body);
5297    gh(
5298        &state.repo,
5299        &[
5300            "pr".into(),
5301            "comment".into(),
5302            pr.number.to_string(),
5303            "--body".into(),
5304            body,
5305        ],
5306    )
5307    .await
5308    .ok();
5309    Ok(())
5310}
5311
5312/// One observation, plus the two things [`PrState`] deliberately does not carry:
5313/// the title (needed for the squash subject) and where the failing checks'
5314/// logs live.
5315#[derive(Clone)]
5316struct Seen {
5317    pr: PrState,
5318    title: String,
5319    failing_urls: Vec<(String, String)>,
5320    /// `headRefOid`: the commit this observation, checks included, is about.
5321    head: String,
5322    /// The commit the checks belong to, read from the same GraphQL node as
5323    /// the checks themselves. Empty when unreadable.
5324    rollup_head: String,
5325    /// `mergeStateStatus` as the forge spelled it. [`Blocking`] folds BLOCKED
5326    /// and DRAFT together, and a stop reason has to say which.
5327    merge_state: String,
5328    /// Every check of the rollup, for naming what an armed merge waits on.
5329    contexts: Vec<CheckInfo>,
5330    /// `baseRefName`, to look up which contexts the base requires.
5331    base: String,
5332}
5333
5334/// One check of the rollup as far as a stop reason needs it.
5335#[derive(Clone)]
5336struct CheckInfo {
5337    label: String,
5338    verdict: Verdict,
5339    required: Option<bool>,
5340    /// The workflow run the check belongs to; `None` for an external status.
5341    run: Option<String>,
5342}
5343
5344/// What to do with a red head before a fix round is spent on it.
5345#[derive(Debug, Clone, PartialEq, Eq)]
5346enum RerunStep {
5347    /// Rerun these workflow runs (each not yet rerun for this head).
5348    Rerun(Vec<String>),
5349    /// Reran already and the forge may still report the old failure: wait.
5350    Grace,
5351    /// Nothing to rerun, or the rerun did not help: the fixer's turn.
5352    Fix,
5353}
5354
5355/// Failed checks a rerun may help: a failure of a check that blocks (`required`
5356/// unreadable counts), as `(label, run)`. Judged one workflow run at a time;
5357/// pending checks in another run do not delay this run's rerun.
5358#[cfg(test)]
5359fn rerunnable(contexts: &[CheckInfo]) -> Vec<(String, Option<String>)> {
5360    rerunnable_with(contexts, false)
5361}
5362
5363fn rerunnable_with(
5364    contexts: &[CheckInfo],
5365    include_optional: bool,
5366) -> Vec<(String, Option<String>)> {
5367    contexts
5368        .iter()
5369        .filter(|c| c.verdict == Verdict::Fail && (include_optional || c.required != Some(false)))
5370        // `gh run rerun --failed` refuses a run with a job still going.
5371        .filter(|c| {
5372            c.run.as_ref().is_none_or(|r| {
5373                !contexts.iter().any(|o| {
5374                    matches!(o.verdict, Verdict::Pending | Verdict::Unknown)
5375                        && o.run.as_ref() == Some(r)
5376                })
5377            })
5378        })
5379        .map(|c| (c.label.clone(), c.run.clone()))
5380        .collect()
5381}
5382
5383/// Pure: rerun once per run id, wait out the grace, then hand over.
5384fn rerun_step(
5385    failing: &[(String, Option<String>)],
5386    record: Option<&LandReruns>,
5387    head: &str,
5388    now: i64,
5389) -> RerunStep {
5390    // A failure with no workflow run (an external status) cannot be rerun, and
5391    // the fixer's push re-runs everything anyway.
5392    if failing.is_empty() || failing.iter().any(|(_, run)| run.is_none()) {
5393        return RerunStep::Fix;
5394    }
5395    // Reruns belong to the head they were made on.
5396    let record = record.filter(|r| r.head.eq_ignore_ascii_case(head));
5397    let mut fresh: Vec<String> = Vec::new();
5398    let mut recent = false;
5399    for run in failing.iter().filter_map(|(_, run)| run.as_deref()) {
5400        match record.and_then(|r| r.runs.get(run)) {
5401            None => {
5402                if !fresh.iter().any(|f| f == run) {
5403                    fresh.push(run.to_owned());
5404                }
5405            }
5406            Some(&at) if now - at < crate::release_watch::RERUN_GRACE => recent = true,
5407            Some(_) => {}
5408        }
5409    }
5410    if !fresh.is_empty() {
5411        RerunStep::Rerun(fresh)
5412    } else if recent {
5413        RerunStep::Grace
5414    } else {
5415        RerunStep::Fix
5416    }
5417}
5418
5419/// Read the pull request: `gh pr view` for the top-level thread and merge
5420/// state, `gh api graphql` for the last commit and its checks, `gh api` for the
5421/// inline review comments `gh pr view` does not report.
5422async fn observe(repo: &Path, pr_url: &str) -> Result<Seen> {
5423    let view = gh(
5424        repo,
5425        &[
5426            "pr".to_owned(),
5427            "view".to_owned(),
5428            pr_url.to_owned(),
5429            "--json".to_owned(),
5430            "url,number,state,title,reviews,comments,mergeStateStatus,headRefOid,baseRefName"
5431                .to_owned(),
5432        ],
5433    )
5434    .await?;
5435    if !view.0 {
5436        bail!("gh pr view {pr_url}: {}", view.1);
5437    }
5438    let number = parse_pr(&view.1)?.number;
5439    let node = last_commit_node(repo, number).await;
5440    let mut seen = seen_from(&view.1, node.as_deref())?;
5441
5442    let inline = gh(
5443        repo,
5444        &[
5445            "api".to_owned(),
5446            format!("repos/{{owner}}/{{repo}}/pulls/{}/comments", seen.pr.number),
5447        ],
5448    )
5449    .await?;
5450    if inline.0 {
5451        match parse_inline_comments(&inline.1) {
5452            Ok(mut comments) => seen.pr.review_comments.append(&mut comments),
5453            // An unreadable inline thread must not end a landing: the rollup
5454            // and the top-level thread are still real signal.
5455            Err(e) => tracing::warn!("inline review comments unreadable: {e}"),
5456        }
5457    } else {
5458        tracing::warn!("gh api pulls/{}/comments: {}", seen.pr.number, inline.1);
5459    }
5460    Ok(seen)
5461}
5462
5463/// Build a [`Seen`] from the `gh pr view` json and the last-commit node
5464/// response. No I/O.
5465///
5466/// The commit oid and the checks are read from the *same* node, so the rollup
5467/// is bound to the commit it belongs to by construction; two reads that agree
5468/// before and after another response prove nothing about what that response
5469/// held. The view's own rollup is never used. A node that is missing,
5470/// unreadable, carries GraphQL errors, or whose checks run past the page
5471/// leaves `rollup_head` empty and the checks `Unknown`, which the loop treats
5472/// as "look again" and never as a reason to merge.
5473fn seen_from(view_json: &str, node_json: Option<&str>) -> Result<Seen> {
5474    let mut pr = parse_pr(view_json)?;
5475    let raw: GhPr = serde_json::from_str(view_json).context("re-read pull request json")?;
5476
5477    let mut rollup_head = String::new();
5478    let mut failing_urls = Vec::new();
5479    let mut contexts = Vec::new();
5480    let mut checks = Checks::Unknown;
5481    let mut failing = Vec::new();
5482    if let Some((oid, rollup)) = node_json.and_then(parse_last_commit_node) {
5483        (checks, failing) = rollup_verdict(&rollup);
5484        failing_urls = rollup
5485            .iter()
5486            .filter(|c| c.verdict() == Verdict::Fail)
5487            .filter_map(|c| c.url().map(|u| (c.label(), u.to_owned())))
5488            .collect();
5489        contexts = rollup
5490            .iter()
5491            .map(|c| CheckInfo {
5492                label: c.label(),
5493                verdict: c.verdict(),
5494                required: c.is_required,
5495                run: c.url().and_then(run_of),
5496            })
5497            .collect();
5498        rollup_head = oid;
5499    }
5500    pr.checks = checks;
5501    pr.failing = failing;
5502
5503    Ok(Seen {
5504        pr,
5505        title: raw.title,
5506        failing_urls,
5507        head: raw.head_ref_oid,
5508        rollup_head,
5509        merge_state: raw.merge_state_status,
5510        contexts,
5511        base: raw.base_ref_name,
5512    })
5513}
5514
5515/// The last commit's oid and its checks from one GraphQL response, `None`
5516/// when anything about it cannot be trusted.
5517fn parse_last_commit_node(json: &str) -> Option<(String, Vec<GhCheck>)> {
5518    let v: serde_json::Value = serde_json::from_str(json).ok()?;
5519    if v.get("errors").is_some_and(|e| !e.is_null()) {
5520        return None;
5521    }
5522    let commit = v.pointer("/data/repository/pullRequest/commits/nodes/0/commit")?;
5523    let oid = commit.get("oid")?.as_str().filter(|o| !o.is_empty())?;
5524    let contexts = commit.pointer("/statusCheckRollup/contexts");
5525    let Some(contexts) = contexts.filter(|c| !c.is_null()) else {
5526        // No rollup at all: the commit has no checks.
5527        return Some((oid.to_owned(), Vec::new()));
5528    };
5529    if contexts.pointer("/pageInfo/hasNextPage")?.as_bool()? {
5530        return None;
5531    }
5532    let nodes = contexts.get("nodes")?.as_array()?;
5533    let rollup = nodes
5534        .iter()
5535        .map(|n| serde_json::from_value::<GhCheck>(n.clone()))
5536        .collect::<Result<Vec<_>, _>>()
5537        .ok()?;
5538    Some((oid.to_owned(), rollup))
5539}
5540
5541/// The pull request's last commit and its checks, in one response. `None`
5542/// when the forge could not be asked.
5543async fn last_commit_node(repo: &Path, number: u64) -> Option<String> {
5544    let out = gh(
5545        repo,
5546        &[
5547            "api".to_owned(),
5548            "graphql".to_owned(),
5549            "-F".to_owned(),
5550            "owner={owner}".to_owned(),
5551            "-F".to_owned(),
5552            "repo={repo}".to_owned(),
5553            "-F".to_owned(),
5554            format!("number={number}"),
5555            "-f".to_owned(),
5556            "query=query($owner:String!,$repo:String!,$number:Int!){repository(owner:$owner,\
5557             name:$repo){pullRequest(number:$number){commits(last:1){nodes{commit{oid \
5558             statusCheckRollup{contexts(first:100){pageInfo{hasNextPage} nodes{\
5559             ... on CheckRun{name status conclusion detailsUrl \
5560             isRequired(pullRequestNumber:$number)} \
5561             ... on StatusContext{context state targetUrl \
5562             isRequired(pullRequestNumber:$number)}}}}}}}}}}"
5563                .to_owned(),
5564        ],
5565    )
5566    .await
5567    .ok()?;
5568    out.0.then_some(out.1)
5569}
5570
5571/// What a fix round did.
5572#[doc(hidden)]
5573#[derive(Debug, PartialEq)]
5574pub enum Fixed {
5575    /// The fixer committed something, and this is the head that was pushed.
5576    Committed {
5577        /// The commit now at the tip of the pushed branch.
5578        head: String,
5579    },
5580    /// The fixer ran and chose to change nothing.
5581    Declined,
5582    /// Machine availability prevented a result; retry this round on resume.
5583    Deferred,
5584    /// The fixer could not run, or said nothing usable.
5585    Failed(String),
5586}
5587
5588/// Hand the failures and the comments to the fixer, then commit and push.
5589///
5590/// The fixer works in the winner's own worktree so its commits land on the
5591/// branch the pull request is built from, and it runs with `allow_write` for
5592/// the same reason.
5593#[doc(hidden)]
5594pub async fn fix_round(
5595    state: &mut RunState,
5596    pr: &PrState,
5597    round: usize,
5598    budget: usize,
5599    reason: &str,
5600    logs: &str,
5601) -> Result<Fixed> {
5602    let winner = state
5603        .winner()
5604        .cloned()
5605        .context("landing needs a winning candidate; none is recorded on this run")?;
5606    let roles = state
5607        .config
5608        .resolve_roles()
5609        .context("resolve the roster for the fix round")?;
5610    // Same chain as the review loop (see `crate::fixer`): the configured
5611    // fixers in order, otherwise the winner's own author continuing its own
5612    // conversation - the competition is over, so its context is pure benefit.
5613    let attempts = crate::fixer::attempts(state, &roles, &winner);
5614    let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
5615
5616    let prompt = fix_prompt(state, pr, round, budget, reason, logs);
5617    let mut artifacts = agent::artifacts_dir(&state.dir());
5618    if let Some(request) = state
5619        .merge_repairs
5620        .last()
5621        .filter(|r| r.phase == crate::run::MergeRepairPhase::Fixing)
5622    {
5623        artifacts = artifacts.join(format!("merge-repair-{}", request.question));
5624    }
5625    let prompt = if state.config.cache_dir().is_some() {
5626        format!("{prompt}\n\n{}", prompt::build_cache_note("fix", true))
5627    } else {
5628        prompt
5629    };
5630    // Read before the fixer runs: it normally commits for itself, so HEAD has
5631    // already moved by the time it returns and a later read would see no
5632    // progress (run 20261004-041622-5769 stopped on a fix that had landed).
5633    let before = git::rev_parse(&winner.worktree, "HEAD").await?;
5634    // Each id at most once, forward only: the next one is asked only when the
5635    // call advances, and only the last attempt's result is judged below, so an
5636    // exhausted chain ends as a single failed fixer does.
5637    let mut last = None;
5638    for (i, (spec, seat_key)) in attempts.into_iter().enumerate() {
5639        if owner_requested_stop(state)? {
5640            return Ok(Fixed::Declined);
5641        }
5642        let mut seat = seat_of(state, &seat_key, &spec.id);
5643        let stem = if i == 0 {
5644            format!("land-{round}")
5645        } else {
5646            format!("land-{round}-{}", spec.id)
5647        };
5648        let out = agent::invoke(
5649            &spec,
5650            &mut seat,
5651            &Invocation {
5652                coordination: state.config.coordination.as_ref(),
5653                fetched_base: state.fetched_base.as_ref(),
5654                cwd: &winner.worktree,
5655                prompt: &prompt,
5656                timeout: Duration::from_secs(state.config.graph.timeout_fix),
5657                allow_write: true,
5658                sessions: state.config.graph.sessions,
5659                artifacts: &artifacts,
5660                stem: &stem,
5661                run: &state.id,
5662                node: "land",
5663                cache_dir: state.config.cache_dir().as_deref(),
5664                attachments: &[],
5665                writable: &[],
5666            },
5667        )
5668        .await;
5669        state.seats.insert(seat.key.clone(), seat);
5670        if let Some(next) = ids.get(i + 1)
5671            && agent::chain_advances(&out)
5672        {
5673            let (class, why) = crate::fixer::failure_of(&out);
5674            crate::graph::record_handover(state, "land", &seat_key, &spec.id, next, &class, &why);
5675            continue;
5676        }
5677        last = Some((seat_key, out));
5678        break;
5679    }
5680    let (seat_key, out) = last.expect("the fixer chain always has an entry");
5681
5682    match out {
5683        Ok(o) if o.quota_exhausted() => {
5684            let loss = crate::run::QuotaLoss::from_report(seat_key, "land", o.quota.as_ref());
5685            crate::graph::block_machine_outage(state, "land", std::slice::from_ref(&loss));
5686            state.quota.push(loss);
5687            state.status = RunStatus::Blocked;
5688            state.save()?;
5689            // Keep partial edits reachable on the winner branch and leave a
5690            // clean tree for resume_landing_head. The resumed landing gates
5691            // this new commit before it can publish it; no push happens here.
5692            let inherited = crate::repo_lock::WaitPolicy::current();
5693            let wait = crate::repo_lock::WaitPolicy::new(
5694                Duration::from_secs(state.config.graph.timeout_resource_wait),
5695                move || inherited.cancelled(),
5696            );
5697            let _coordination = crate::repo_lock::SeatLease::operation_with(
5698                &winner.worktree,
5699                state.config.coordination.as_ref(),
5700                &wait,
5701            )
5702            .await?;
5703            let rescue = git::rescue_commit(
5704                &winner.worktree,
5705                &format!("magi: deferred land round {round} (uncommitted work)"),
5706            )
5707            .await?;
5708            state.note_withheld("land", &rescue.withheld);
5709            state.save()?;
5710            return Ok(Fixed::Deferred);
5711        }
5712        Ok(o) if !o.usable() => {
5713            return Ok(Fixed::Failed(format!(
5714                "the fixer produced nothing usable ({})",
5715                crate::notices::turn_status(o.exit_code, o.timed_out, o.quota_exhausted())
5716            )));
5717        }
5718        Ok(_) => {}
5719        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => return Err(e),
5720        Err(e) => return Ok(Fixed::Failed(format!("{e:#}"))),
5721    }
5722
5723    if owner_requested_stop(state)? {
5724        return Ok(Fixed::Declined);
5725    }
5726
5727    // An agent that edited files but never committed would otherwise push
5728    // nothing and look like a refusal.
5729    let wait = crate::repo_lock::WaitPolicy::new(
5730        Duration::from_secs(state.config.graph.timeout_resource_wait),
5731        || false,
5732    );
5733    let coordination = crate::repo_lock::SeatLease::operation_with(
5734        &winner.worktree,
5735        state.config.coordination.as_ref(),
5736        &wait,
5737    )
5738    .await?;
5739    match git::rescue_commit(
5740        &winner.worktree,
5741        &format!("magi: land round {round} fixes (uncommitted work)"),
5742    )
5743    .await
5744    {
5745        Ok(r) => state.note_withheld("land", &r.withheld),
5746        Err(e)
5747            if state
5748                .merge_repairs
5749                .last()
5750                .is_some_and(|r| r.phase == crate::run::MergeRepairPhase::Fixing) =>
5751        {
5752            return Ok(Fixed::Failed(format!("saving repair commit failed: {e:#}")));
5753        }
5754        Err(_) => {}
5755    }
5756    let after = git::rev_parse(&winner.worktree, "HEAD").await?;
5757    drop(coordination);
5758    if after == before {
5759        return Ok(Fixed::Declined);
5760    }
5761
5762    if owner_requested_stop(state)? {
5763        return Ok(Fixed::Declined);
5764    }
5765    crate::pr_head::ensure_owner(state)?;
5766    let remote = state.config.merge.remote.clone();
5767    anyhow::ensure!(
5768        crate::foreign_checkout::write_back(state, &after).await?,
5769        "foreign checkout delivery is blocked; see the run events"
5770    );
5771    let public_head = state.pr_branch().unwrap_or(&winner.branch).to_owned();
5772    let push = if state.pr_head.is_some() {
5773        let expected = state
5774            .pr_pushed_head
5775            .as_deref()
5776            .context("missing public head lease")?;
5777        git::push_as(
5778            &winner.worktree,
5779            &remote,
5780            &winner.branch,
5781            &public_head,
5782            expected,
5783        )
5784        .await?
5785    } else {
5786        git::push(&winner.worktree, &remote, &winner.branch).await?
5787    };
5788    if !push.ok() {
5789        return Ok(Fixed::Failed(format!(
5790            "pushing {} to {remote} failed: {}",
5791            public_head, push.stderr
5792        )));
5793    }
5794    state.event(
5795        "land",
5796        format!("round {round}: pushed a fix to {public_head}"),
5797    );
5798    state.pr_pushed_head = Some(after.clone());
5799    state.save()?;
5800    Ok(Fixed::Committed { head: after })
5801}
5802
5803/// Fetch or create a seat, keeping its conversation across nodes.
5804pub(crate) fn seat_of(state: &mut RunState, key: &str, agent: &str) -> SeatState {
5805    crate::fixer::seat_for(state, key, agent)
5806}
5807
5808/// Recheck the live PR and local worktree before spending the requested fix.
5809/// A moved/closed PR is held, never repaired using obsolete evidence.
5810pub(crate) async fn repair_preflight(state: &RunState, url: &str, head: &str) -> Result<PrState> {
5811    let seen = observe(&state.repo, url).await?;
5812    let winner = state.winner().context("no winning branch to repair")?;
5813    if seen.pr.state != PrLifecycle::Open || seen.head != head {
5814        anyhow::bail!(
5815            "PR is closed or its head changed; review the current head before requesting repair again"
5816        );
5817    }
5818    if git::rev_parse(&winner.worktree, "HEAD").await? != head
5819        || !git::is_clean(&winner.worktree).await?
5820    {
5821        anyhow::bail!(
5822            "repair worktree is missing, dirty or at a different head; restore the reviewed branch and resume this run"
5823        );
5824    }
5825    // Always disable any forge-side reservation, including one not recorded
5826    // by this run. A repair request is never merge authorization.
5827    let view = gh(
5828        &state.repo,
5829        &[
5830            "pr".into(),
5831            "view".into(),
5832            url.into(),
5833            "--json".into(),
5834            "autoMergeRequest,headRefOid,state,headRefName,baseRefName,isCrossRepository".into(),
5835        ],
5836    )
5837    .await?;
5838    if !view.0 {
5839        bail!("cannot check auto-merge: {}", view.1);
5840    }
5841    let live: serde_json::Value = serde_json::from_str(&view.1)?;
5842    let public = state.pr_branch().unwrap_or(&winner.branch);
5843    if live["state"] != "OPEN"
5844        || live["headRefOid"] != head
5845        || live["headRefName"] != public
5846        || live["baseRefName"] != state.base_branch
5847        || live["isCrossRepository"] != false
5848    {
5849        bail!("PR changed during repair preflight; review its current head explicitly");
5850    }
5851    let auto_merge = live
5852        .get("autoMergeRequest")
5853        .context("cannot read the PR auto-merge reservation; repair held")?;
5854    if !auto_merge.is_null() {
5855        let out = gh(&state.repo, &disable_automerge_argv(seen.pr.number)).await?;
5856        if !out.0 {
5857            bail!("cannot disable auto-merge; repair held: {}", out.1);
5858        }
5859    }
5860    Ok(seen.pr)
5861}
5862
5863/// What the fixer is told.
5864fn fix_prompt(
5865    state: &RunState,
5866    pr: &PrState,
5867    round: usize,
5868    budget: usize,
5869    reason: &str,
5870    logs: &str,
5871) -> String {
5872    let mut s = format!(
5873        "Your patch is open as a pull request and it is not landing. Land round \
5874         {round} of {budget}.\n\n\
5875         Pull request: {}\n\n\
5876         What is holding it: {reason}\n\n\
5877         # The task\n\n{}\n",
5878        pr.url, state.instruction
5879    );
5880
5881    if pr.failing.is_empty() {
5882        s.push_str("\n# Failing checks\n\n(none)\n");
5883    } else {
5884        let _ = write!(s, "\n# Failing checks\n\n- {}\n", pr.failing.join("\n- "));
5885        if logs.trim().is_empty() {
5886            s.push_str(
5887                "\nNo log could be read; investigate the failure with necessary focused checks.\n",
5888            );
5889        } else {
5890            let _ = write!(s, "\n## Failing log tails\n\n{logs}\n");
5891        }
5892    }
5893
5894    if pr.review_comments.is_empty() {
5895        s.push_str("\n# Review comments\n\n(none)\n");
5896    } else {
5897        s.push_str("\n# Review comments\n");
5898        for c in &pr.review_comments {
5899            let where_ = match (&c.path, c.line) {
5900                (Some(p), Some(l)) => format!(" ({p}:{l})"),
5901                (Some(p), None) => format!(" ({p})"),
5902                _ => String::new(),
5903            };
5904            let _ = write!(s, "\n## {}{where_}\n\n{}\n", c.author, c.body.trim());
5905        }
5906    }
5907
5908    s.push_str(
5909        "\n# Rules\n\n\
5910         1. Fix the cause, never the symptom. Do not delete, skip, or weaken a \
5911            failing test; do not silence a lint with an allow attribute; do not \
5912            stretch a timeout to hide a race. If the check is right, the code is \
5913            wrong.\n\
5914         2. Change nothing the checks and the comments did not raise. A \
5915            drive-by refactor turns a one-line fix into a pull request that \
5916            needs reviewing again.\n\
5917         3. If a comment is wrong, say so with a checkable argument and change \
5918            nothing for it. A declined comment with a reason is a correct \
5919            outcome; a change made to appease a reviewer is not.\n\
5920         4. Commit in this worktree. magi pushes to the pull request's branch \
5921            for you; do not push, merge, or close anything yourself.\n\
5922         5. Never name yourself, your vendor, or your model, anywhere.\n\n\
5923         # Output\n\n\
5924         Say what you changed and why, and what you declined and why.",
5925    );
5926
5927    let language = &state.config.graph.language;
5928    if !(language.trim().is_empty() || language.eq_ignore_ascii_case("en")) {
5929        let _ = write!(s, "\n\nWrite all prose in {language}.");
5930    }
5931    // After the language line, so the exception is the last word on it.
5932    s.push_str(&crate::prompt::github_rule(
5933        language,
5934        &state.config.graph.github_language,
5935    ));
5936    if let Some(overlay) = state.config.prompts.overlay("fix") {
5937        let _ = write!(s, "\n\n{overlay}");
5938    }
5939    s.push('\n');
5940    s.push_str(crate::prompt::child_run_ownership());
5941    s
5942}
5943
5944/// Failing log tails, the way the operator collects them by hand:
5945/// `gh run view --log-failed`.
5946async fn failing_logs(repo: &Path, failing: &[(String, String)]) -> String {
5947    let mut out = String::new();
5948    for (name, url) in failing.iter().take(MAX_LOGS) {
5949        let args = match (job_of(url), run_of(url)) {
5950            (Some(job), _) => vec![
5951                "run".to_owned(),
5952                "view".to_owned(),
5953                "--log-failed".to_owned(),
5954                "--job".to_owned(),
5955                job,
5956            ],
5957            (None, Some(run)) => vec![
5958                "run".to_owned(),
5959                "view".to_owned(),
5960                run,
5961                "--log-failed".to_owned(),
5962            ],
5963            // Not a GitHub Actions check - an external status has no log here.
5964            (None, None) => continue,
5965        };
5966        let (ok, body) = match gh(repo, &args).await {
5967            Ok(v) => v,
5968            Err(e) => (false, format!("{e:#}")),
5969        };
5970        if !ok && body.trim().is_empty() {
5971            continue;
5972        }
5973        let _ = write!(out, "### {name}\n\n```\n{}\n```\n\n", tail(&body, LOG_TAIL));
5974    }
5975    out
5976}
5977
5978/// Job id out of a check's `detailsUrl`
5979/// (`https://github.com/o/r/actions/runs/<run>/job/<job>`).
5980fn job_of(details_url: &str) -> Option<String> {
5981    let after = details_url.split("/job/").nth(1)?;
5982    let id: String = after.chars().take_while(char::is_ascii_digit).collect();
5983    (!id.is_empty()).then_some(id)
5984}
5985
5986/// Workflow run id out of a check's `detailsUrl`.
5987pub(crate) fn run_of(details_url: &str) -> Option<String> {
5988    let after = details_url.split("/actions/runs/").nth(1)?;
5989    let id: String = after.chars().take_while(char::is_ascii_digit).collect();
5990    (!id.is_empty()).then_some(id)
5991}
5992
5993/// The comment `stop` posts. Fixed English, whatever `[graph] language` says:
5994/// it lands on GitHub, not in front of the operator. Pure so a test can hold
5995/// it to that.
5996fn stop_comment(run_id: &str, why: &str) -> String {
5997    format!(
5998        "{MARKER}\nmagi stopped landing this pull request: {why}\n\n\
5999         The branch is untouched and the run is `{run_id}`. Nothing was merged."
6000    )
6001}
6002
6003/// Leave the pull request open, say why on it, and mark the run blocked.
6004///
6005/// The comment is what makes an unattended stop actionable: the operator wakes
6006/// up to a pull request that explains itself rather than to a silent queue.
6007async fn stop(state: &mut RunState, repo: &Path, pr: &PrState, why: &str) -> Result<()> {
6008    let body = stop_comment(&state.id, why);
6009    let (_, mut body) = crate::github_text::prepare(state, "", &body);
6010    if !body.contains(MARKER) {
6011        body = format!("{MARKER}\n{body}");
6012    }
6013    let posted = gh(
6014        repo,
6015        &[
6016            "pr".to_owned(),
6017            "comment".to_owned(),
6018            pr.number.to_string(),
6019            "--body".to_owned(),
6020            body,
6021        ],
6022    )
6023    .await;
6024    match posted {
6025        Ok((true, _)) => {}
6026        Ok((false, out)) => tracing::warn!("could not comment on {}: {out}", pr.url),
6027        Err(e) => tracing::warn!("could not comment on {}: {e:#}", pr.url),
6028    }
6029    state.status = RunStatus::Blocked;
6030    state.merge = Some(MergeOutcome {
6031        mode: MergeMode::Pr,
6032        ok: false,
6033        detail: why.to_owned(),
6034        empty: false,
6035    });
6036    state.event("land", format!("stopped: {why}"));
6037    state.save()?;
6038    Ok(())
6039}
6040
6041/// Run `gh` in `repo`, returning success and the combined output.
6042///
6043/// Combined because `gh` reports a refused merge on stderr and the pull request
6044/// json on stdout, and both are evidence.
6045///
6046/// `GH_REPO` is stripped from the child's environment: every call site here
6047/// passes an explicit `cwd` (or a full pull request URL) meaning to operate
6048/// on *that* checkout's own remote, and `gh` prefers `GH_REPO` over the
6049/// checkout it is sitting in when no `--repo` flag is given. Left unset, a
6050/// `GH_REPO` the operator happens to have exported for an unrelated script
6051/// would silently redirect [`repo_slug`] (and every other cwd-scoped call
6052/// below) to a different repository than the one actually on disk - which
6053/// for the same-repo guard in [`correct_manual_merge`] would mean the check
6054/// could be made to agree with whatever repository a forged `--merged` URL
6055/// claims, defeating it entirely.
6056pub(crate) async fn gh(cwd: &Path, args: &[String]) -> Result<(bool, String)> {
6057    let out = tokio::process::Command::new("gh")
6058        .args(args)
6059        .current_dir(cwd)
6060        .env_remove("GH_REPO")
6061        .quiet()
6062        .stdin(std::process::Stdio::null())
6063        .output()
6064        .await
6065        .with_context(|| format!("spawn gh {}", args.join(" ")))?;
6066    let mut body = String::from_utf8_lossy(&out.stdout).into_owned();
6067    let err = String::from_utf8_lossy(&out.stderr);
6068    if body.trim().is_empty() {
6069        body = err.into_owned();
6070    } else if !err.trim().is_empty() {
6071        body.push_str(&err);
6072    }
6073    Ok((out.status.success(), body.trim().to_owned()))
6074}
6075
6076/// Verdict of one entry in the status rollup.
6077#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6078pub(crate) enum Verdict {
6079    Pass,
6080    Fail,
6081    Pending,
6082    Unknown,
6083}
6084
6085impl Verdict {
6086    /// Short operator-facing check result.
6087    pub(crate) fn label(self) -> &'static str {
6088        match self {
6089            Self::Pass => "passed",
6090            Self::Fail => "failed",
6091            Self::Pending => "pending",
6092            Self::Unknown => "unknown",
6093        }
6094    }
6095}
6096
6097#[derive(Debug, Deserialize)]
6098#[serde(rename_all = "camelCase")]
6099struct GhPr {
6100    #[serde(default)]
6101    url: String,
6102    #[serde(default)]
6103    number: u64,
6104    #[serde(default)]
6105    state: String,
6106    #[serde(default)]
6107    title: String,
6108    #[serde(default)]
6109    status_check_rollup: Vec<GhCheck>,
6110    /// GitHub's own verdict on whether the pull request can be merged.
6111    ///
6112    /// Worth asking for because it is the only place the *required* check set
6113    /// is applied: the rollup lists every check equally, so a repository that
6114    /// deliberately does not require `coverage` still looks red here. See
6115    /// [`Blocking`].
6116    #[serde(default)]
6117    merge_state_status: String,
6118    /// The commit the pull request currently points at. Compared with the
6119    /// commit a fix round pushed, it is how the loop knows the forge has moved
6120    /// on and the rollup belongs to the new head.
6121    #[serde(default)]
6122    head_ref_oid: String,
6123    #[serde(default)]
6124    base_ref_name: String,
6125    #[serde(default)]
6126    reviews: Vec<GhReview>,
6127    #[serde(default)]
6128    comments: Vec<GhComment>,
6129}
6130
6131/// One rollup entry. `gh` mixes two GraphQL types in this array: a `CheckRun`
6132/// has `name`/`status`/`conclusion`, while a `StatusContext` - the old commit
6133/// status API, which is how CodeRabbit reports - has `context`/`state` and no
6134/// conclusion at all.
6135#[derive(Debug, Deserialize)]
6136#[serde(rename_all = "camelCase")]
6137struct GhCheck {
6138    #[serde(default)]
6139    name: Option<String>,
6140    #[serde(default)]
6141    context: Option<String>,
6142    #[serde(default)]
6143    status: Option<String>,
6144    #[serde(default)]
6145    conclusion: Option<String>,
6146    #[serde(default)]
6147    state: Option<String>,
6148    #[serde(default)]
6149    details_url: Option<String>,
6150    #[serde(default)]
6151    target_url: Option<String>,
6152    /// Whether the base branch requires this check. Only the GraphQL node
6153    /// carries it; `None` is "not read", never "not required".
6154    #[serde(default)]
6155    is_required: Option<bool>,
6156}
6157
6158impl GhCheck {
6159    /// Name to show a human and hand to the fixer.
6160    fn label(&self) -> String {
6161        self.name
6162            .clone()
6163            .or_else(|| self.context.clone())
6164            .unwrap_or_else(|| "(unnamed check)".to_owned())
6165    }
6166
6167    /// Where this check's logs live, when it has any.
6168    fn url(&self) -> Option<&str> {
6169        self.details_url
6170            .as_deref()
6171            .or(self.target_url.as_deref())
6172            .filter(|u| !u.is_empty())
6173    }
6174
6175    /// Did it pass?
6176    ///
6177    /// `SKIPPED` and `NEUTRAL` count as passed: the Claude review workflow
6178    /// skips release and bot pull requests by design, and a skip that blocked
6179    /// landing would block exactly the pull requests that need no review.
6180    /// `CANCELLED` counts as failed - a cancelled check did not pass, and
6181    /// merging over one is merging over a check that never ran.
6182    fn verdict(&self) -> Verdict {
6183        if let Some(status) = self.status.as_deref() {
6184            if !status.eq_ignore_ascii_case("COMPLETED") {
6185                return Verdict::Pending;
6186            }
6187        }
6188        let outcome = self
6189            .conclusion
6190            .as_deref()
6191            .or(self.state.as_deref())
6192            .unwrap_or("");
6193        match outcome.to_ascii_uppercase().as_str() {
6194            "SUCCESS" | "SKIPPED" | "NEUTRAL" => Verdict::Pass,
6195            "FAILURE" | "ERROR" | "TIMED_OUT" | "CANCELLED" | "STARTUP_FAILURE"
6196            | "ACTION_REQUIRED" => Verdict::Fail,
6197            "PENDING" | "EXPECTED" | "QUEUED" | "IN_PROGRESS" | "WAITING" | "REQUESTED" => {
6198                Verdict::Pending
6199            }
6200            _ => Verdict::Unknown,
6201        }
6202    }
6203}
6204
6205#[derive(Debug, Deserialize)]
6206struct GhAuthor {
6207    #[serde(default)]
6208    login: String,
6209}
6210
6211#[derive(Debug, Deserialize)]
6212struct GhReview {
6213    #[serde(default)]
6214    author: GhAuthor,
6215    #[serde(default)]
6216    body: String,
6217}
6218
6219#[derive(Debug, Deserialize)]
6220struct GhComment {
6221    #[serde(default)]
6222    author: GhAuthor,
6223    #[serde(default)]
6224    body: String,
6225}
6226
6227#[derive(Debug, Deserialize)]
6228struct GhUser {
6229    #[serde(default)]
6230    login: String,
6231}
6232
6233#[derive(Debug, Deserialize)]
6234struct GhInline {
6235    #[serde(default)]
6236    user: GhUser,
6237    #[serde(default)]
6238    path: Option<String>,
6239    #[serde(default)]
6240    line: Option<u64>,
6241    #[serde(default)]
6242    body: String,
6243}
6244
6245impl Default for GhAuthor {
6246    fn default() -> Self {
6247        Self {
6248            login: "(unknown)".to_owned(),
6249        }
6250    }
6251}
6252
6253impl Default for GhUser {
6254    fn default() -> Self {
6255        Self {
6256            login: "(unknown)".to_owned(),
6257        }
6258    }
6259}
6260
6261#[cfg(test)]
6262pub(crate) mod tests {
6263    use super::*;
6264    use crate::run::{Candidate, ReviewRecord, ReviewRound, Tally};
6265
6266    fn head_json(head: &str, base: &str, state: &str, cross: bool) -> String {
6267        format!(
6268            r#"{{"headRefName":"{head}","headRefOid":"aaa","baseRefName":"{base}","state":"{state}","isCrossRepository":{cross}}}"#
6269        )
6270    }
6271
6272    #[test]
6273    fn a_pull_request_is_closed_only_when_its_head_is_exactly_the_runs_branch() {
6274        let ok = head_json("magi/27b2/A", "main", "OPEN", false);
6275        assert_eq!(
6276            closable(&ok, "magi/27b2/A", "main", &["aaa".to_owned()]),
6277            Ok(())
6278        );
6279        for (json, why) in [
6280            (head_json("magi/27b2/B", "main", "OPEN", false), "head"),
6281            (head_json("magi/27b2/A-2", "main", "OPEN", false), "head"),
6282            (head_json("magi/27b2/A", "main", "OPEN", true), "fork"),
6283            (head_json("magi/27b2/A", "dev", "OPEN", false), "targets"),
6284            (head_json("magi/27b2/A", "main", "MERGED", false), "already"),
6285            (head_json("magi/27b2/A", "main", "CLOSED", false), "already"),
6286        ] {
6287            let err = closable(&json, "magi/27b2/A", "main", &["aaa".to_owned()])
6288                .unwrap_err()
6289                .why;
6290            assert!(err.contains(why), "{json}: {err}");
6291        }
6292        // A head that moved on past what was verified is left alone.
6293        let moved = head_json("magi/27b2/A", "main", "OPEN", false);
6294        let err = closable(&moved, "magi/27b2/A", "main", &["bbb".to_owned()]).unwrap_err();
6295        assert!(err.retry && err.why.contains("not a commit"), "{err:?}");
6296        assert!(
6297            !closable(
6298                &head_json("x", "main", "OPEN", false),
6299                "magi/27b2/A",
6300                "main",
6301                &[]
6302            )
6303            .unwrap_err()
6304            .retry
6305        );
6306        assert!(is_forge_url("https://github.com/o/r.git"));
6307        assert!(is_forge_url("git@github.com:o/r.git"));
6308        assert!(!is_forge_url("/tmp/origin.git"));
6309        assert!(!is_forge_url("C:\\work\\origin.git"));
6310        assert!(!is_forge_url("file:///tmp/origin.git"));
6311        assert!(forge_unavailable(
6312            "gh pr list failed: none of the git remotes configured for this repository point to a known GitHub host."
6313        ));
6314        assert!(!forge_unavailable(
6315            "gh pr list failed: error connecting to api.github.com"
6316        ));
6317        assert!(closable("not json", "magi/27b2/A", "main", &[]).is_err());
6318        // A record that does not say whether it is a fork is not trusted.
6319        assert!(
6320            closable(
6321                r#"{"headRefName":"b","headRefOid":"aaa","baseRefName":"main","state":"OPEN"}"#,
6322                "b",
6323                "main",
6324                &["aaa".to_owned()]
6325            )
6326            .is_err()
6327        );
6328    }
6329
6330    #[test]
6331    fn the_close_comment_names_the_commit_on_the_base() {
6332        let e = crate::already::Evidence {
6333            proof: crate::already::Proof::PatchId,
6334            tip: "1234567890".to_owned(),
6335            commits: vec!["0e368de0000".to_owned()],
6336        };
6337        let c = superseded_comment("main", &e);
6338        assert!(c.contains("0e368de") && c.contains("`main`"), "{c}");
6339    }
6340
6341    /// 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.
6342    const GREEN_OPEN: &str = r####"{
6343  "url": "https://github.com/yukimemi/magi/pull/10",
6344  "number": 10,
6345  "state": "OPEN",
6346  "mergeStateStatus": "CLEAN",
6347  "statusCheckRollup": [
6348    {
6349      "__typename": "CheckRun",
6350      "conclusion": "SKIPPED",
6351      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278334/job/99378963755",
6352      "name": "review",
6353      "status": "COMPLETED",
6354      "workflowName": "claude-review"
6355    },
6356    {
6357      "__typename": "CheckRun",
6358      "conclusion": "SUCCESS",
6359      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278338/job/99378963144",
6360      "name": "check (ubuntu-latest)",
6361      "status": "COMPLETED",
6362      "workflowName": "CI"
6363    },
6364    {
6365      "__typename": "CheckRun",
6366      "conclusion": "SUCCESS",
6367      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33356278338/job/99378963095",
6368      "name": "rustfmt",
6369      "status": "COMPLETED",
6370      "workflowName": "CI"
6371    },
6372    {
6373      "__typename": "StatusContext",
6374      "context": "CodeRabbit",
6375      "state": "SUCCESS",
6376      "targetUrl": ""
6377    }
6378  ],
6379  "reviews": [],
6380  "comments": [
6381    {
6382      "author": {
6383        "login": "coderabbitai"
6384      },
6385      "authorAssociation": "NONE",
6386      "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"
6387    }
6388  ]
6389}"####;
6390
6391    /// Real output for the open pull request #9 (the daily kata-apply), whose `editorconfig` check failed while everything else passed.
6392    const RED_OPEN: &str = r####"{
6393  "url": "https://github.com/yukimemi/magi/pull/9",
6394  "number": 9,
6395  "state": "OPEN",
6396  "mergeStateStatus": "UNSTABLE",
6397  "statusCheckRollup": [
6398    {
6399      "__typename": "CheckRun",
6400      "conclusion": "SUCCESS",
6401      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323744",
6402      "name": "check (ubuntu-latest)",
6403      "status": "COMPLETED",
6404      "workflowName": "CI"
6405    },
6406    {
6407      "__typename": "CheckRun",
6408      "conclusion": "SUCCESS",
6409      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323811",
6410      "name": "rustfmt",
6411      "status": "COMPLETED",
6412      "workflowName": "CI"
6413    },
6414    {
6415      "__typename": "CheckRun",
6416      "conclusion": "FAILURE",
6417      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572",
6418      "name": "editorconfig",
6419      "status": "COMPLETED",
6420      "workflowName": "CI"
6421    },
6422    {
6423      "__typename": "StatusContext",
6424      "context": "CodeRabbit",
6425      "state": "SUCCESS",
6426      "targetUrl": ""
6427    }
6428  ],
6429  "reviews": [],
6430  "comments": [
6431    {
6432      "author": {
6433        "login": "coderabbitai"
6434      },
6435      "authorAssociation": "NONE",
6436      "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"
6437    }
6438  ]
6439}"####;
6440
6441    /// 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.
6442    const PENDING_OPEN: &str = r####"{
6443  "url": "https://github.com/yukimemi/magi/pull/9",
6444  "number": 9,
6445  "state": "OPEN",
6446  "statusCheckRollup": [
6447    {
6448      "__typename": "CheckRun",
6449      "conclusion": "SUCCESS",
6450      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323744",
6451      "name": "check (ubuntu-latest)",
6452      "status": "COMPLETED",
6453      "workflowName": "CI"
6454    },
6455    {
6456      "__typename": "CheckRun",
6457      "conclusion": "SUCCESS",
6458      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323811",
6459      "name": "rustfmt",
6460      "status": "COMPLETED",
6461      "workflowName": "CI"
6462    },
6463    {
6464      "__typename": "CheckRun",
6465      "conclusion": null,
6466      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572",
6467      "name": "editorconfig",
6468      "status": "IN_PROGRESS",
6469      "workflowName": "CI"
6470    },
6471    {
6472      "__typename": "StatusContext",
6473      "context": "CodeRabbit",
6474      "state": "SUCCESS",
6475      "targetUrl": ""
6476    }
6477  ],
6478  "reviews": [],
6479  "comments": []
6480}"####;
6481
6482    /// Real output for pull request #16 after it was merged - the shape landing sees when a person merged underneath it.
6483    const MERGED: &str = r####"{
6484  "url": "https://github.com/yukimemi/magi/pull/16",
6485  "number": 16,
6486  "state": "MERGED",
6487  "statusCheckRollup": [
6488    {
6489      "__typename": "CheckRun",
6490      "conclusion": "SUCCESS",
6491      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33636587933/job/100268878095",
6492      "name": "check (ubuntu-latest)",
6493      "status": "COMPLETED",
6494      "workflowName": "CI"
6495    },
6496    {
6497      "__typename": "CheckRun",
6498      "conclusion": "SUCCESS",
6499      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33636587918/job/100268876427",
6500      "name": "review",
6501      "status": "COMPLETED",
6502      "workflowName": "claude-review"
6503    }
6504  ],
6505  "reviews": [],
6506  "comments": []
6507}"####;
6508
6509    /// 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.
6510    const REVIEWED_OPEN: &str = r####"{
6511  "url": "https://github.com/yukimemi/magi/pull/12",
6512  "number": 12,
6513  "state": "OPEN",
6514  "statusCheckRollup": [
6515    {
6516      "__typename": "CheckRun",
6517      "conclusion": "SUCCESS",
6518      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33571212506/job/100065355258",
6519      "name": "check (ubuntu-latest)",
6520      "status": "COMPLETED",
6521      "workflowName": "CI"
6522    },
6523    {
6524      "__typename": "CheckRun",
6525      "conclusion": "SUCCESS",
6526      "detailsUrl": "https://github.com/yukimemi/magi/actions/runs/33571212566/job/100065355810",
6527      "name": "review",
6528      "status": "COMPLETED",
6529      "workflowName": "claude-review"
6530    }
6531  ],
6532  "reviews": [
6533    {
6534      "author": {
6535        "login": "claude"
6536      },
6537      "state": "COMMENTED",
6538      "body": ""
6539    }
6540  ],
6541  "comments": [
6542    {
6543      "author": {
6544        "login": "coderabbitai"
6545      },
6546      "authorAssociation": "NONE",
6547      "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"
6548    },
6549    {
6550      "author": {
6551        "login": "claude"
6552      },
6553      "authorAssociation": "NONE",
6554      "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"
6555    }
6556  ]
6557}"####;
6558
6559    /// Real `gh api repos/{owner}/{repo}/pulls/12/comments` output: one inline finding with its file and line.
6560    const INLINE: &str = r####"[
6561  {
6562    "user": {
6563      "login": "claude[bot]"
6564    },
6565    "path": "src/graph.rs",
6566    "line": 231,
6567    "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"
6568  }
6569]"####;
6570
6571    /// CodeRabbit's real trigger notice: a checkbox, a `<details>` block, and its own "skip review" marker.
6572    const CODERABBIT_TRIGGER: &str = r####"<!-- This is an auto-generated comment: summarize by coderabbit.ai -->
6573<!-- This is an auto-generated comment: skip review by coderabbit.ai -->
6574
6575> [!IMPORTANT]
6576> - [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> 🔍 Trigger review
6577> 
6578> This repository does not receive automatic reviews because it has fewer than 10 stars.
6579> 
6580> <details>
6581> <summary>⚙️ Run configuration</summary>
6582> 
6583> **Configuration used**: defaults
6584> 
6585> **Review profile**: CHILL
6586> 
6587> **Plan**: Team
6588> 
6589> **Run ID**: `c1e2a68f-87fc-4b35-9ec4-e75c7854966a`
6590> 
6591> </details>
6592
6593<!-- end of auto-generated comment: skip review by coderabbit.ai -->
6594
6595<!-- tips_start -->
6596
6597---
6598
6599Thanks 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.
6600
6601<details>
6602<summary>❤️ Share</summary>
6603
6604- [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"####;
6605
6606    /// 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.
6607    const CLAUDE_CHECKLIST: &str = r####"**Claude finished @yukimemi's task in 4m 14s** —— [View job](https://github.com/yukimemi/magi/actions/runs/33636587918)
6608
6609---
6610### Reviewing PR #16
6611
6612- [x] Read AGENTS.md conventions
6613- [x] Review `src/daemon.rs` changes
6614- [x] Review `src/main.rs` changes (new `doctor` reporting)
6615- [x] Review `src/web.rs` changes (reuse of unreadable-run count)
6616- [x] Check test coverage for new behavior
6617- [x] Run verification commands (blocked — see note)
6618- [x] Post findings"####;
6619
6620    /// The same job's real comment on pull request #12 once it had something to say.
6621    const CLAUDE_FINDING: &str = r####"**Claude finished @yukimemi's task in 3m 52s** —— [View job](https://github.com/yukimemi/magi/actions/runs/33571212566)
6622
6623---
6624### Review: `magi review <branch>` — cheap-half-only graph
6625
6626Read 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.
6627
6628**Correctness**
6629
6630- 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"####;
6631
6632    fn pr(checks: Checks, failing: &[&str], comments: usize) -> PrState {
6633        PrState {
6634            url: "https://github.com/yukimemi/magi/pull/16".to_owned(),
6635            number: 16,
6636            state: PrLifecycle::Open,
6637            checks,
6638            // These tests are about red-means-fix, so a red here is one the
6639            // forge gates on. Without saying so they would assert the new
6640            // "merge past a check nobody requires" path by accident.
6641            blocking: if matches!(checks, Checks::Red) {
6642                Blocking::Yes
6643            } else {
6644                Blocking::No
6645            },
6646            failing: failing.iter().map(|s| (*s).to_owned()).collect(),
6647            review_comments: (0..comments)
6648                .map(|i| ReviewComment {
6649                    author: "coderabbitai".to_owned(),
6650                    path: Some("src/graph.rs".to_owned()),
6651                    line: Some(231),
6652                    body: format!("finding {i}"),
6653                })
6654                .collect(),
6655        }
6656    }
6657
6658    #[test]
6659    fn expected_ci_is_exactly_decide_and_absent_ci_never_waits_for_checks() {
6660        use CiExpectation::{Absent, Expected};
6661        for checks in [Checks::Pending, Checks::Unknown, Checks::Green, Checks::Red] {
6662            let p = pr(checks, &["x"], 0);
6663            for waited in [Duration::ZERO, CHECKS_GRACE] {
6664                assert_eq!(
6665                    decide_with(&p, 0, 4, waited, Expected),
6666                    decide(&p, 0, 4, waited)
6667                );
6668            }
6669        }
6670        // Nothing will ever report: no wait, no give-up, no fix round.
6671        for checks in [Checks::Pending, Checks::Unknown, Checks::Red] {
6672            let p = pr(checks, &["x"], 0);
6673            assert_eq!(decide_with(&p, 0, 4, Duration::ZERO, Absent), Step::Merge);
6674            assert_eq!(decide_with(&p, 4, 4, CHECKS_GRACE, Absent), Step::Merge);
6675        }
6676        // Third-party statuses never change the review decision, even at budget.
6677        for comments in [0, 1] {
6678            for round in [0, 4] {
6679                let absent = decide_with(
6680                    &pr(Checks::Unknown, &[], comments),
6681                    round,
6682                    4,
6683                    CHECKS_GRACE,
6684                    Absent,
6685                );
6686                for checks in [Checks::Green, Checks::Red, Checks::Pending] {
6687                    assert_eq!(
6688                        decide_with(
6689                            &pr(checks, &["third-party"], comments),
6690                            round,
6691                            4,
6692                            Duration::ZERO,
6693                            Absent
6694                        ),
6695                        absent
6696                    );
6697                }
6698                if comments != 0 {
6699                    assert!(matches!(absent, Step::Fix { .. } | Step::GiveUp { .. }));
6700                    assert_eq!(matches!(absent, Step::GiveUp { .. }), round == 4);
6701                }
6702            }
6703        }
6704        let empty = pr(Checks::Unknown, &[], 0);
6705        for waited in [Duration::ZERO, CHECKS_GRACE + POLL] {
6706            assert_eq!(decide_with(&empty, 0, 4, waited, Absent), Step::Merge);
6707        }
6708        assert_eq!(
6709            decide_with(&empty, 0, 4, Duration::ZERO, Expected),
6710            Step::Wait
6711        );
6712        assert_eq!(
6713            decide_with(&empty, 0, 4, CHECKS_GRACE, Expected),
6714            Step::GiveUp { reason: "no check status is readable on the pull request after 3 minute(s); refusing to merge on a guess".to_owned() }
6715        );
6716        // A conflict is not a check: it still wants the rebase.
6717        let mut p = pr(Checks::Unknown, &[], 0);
6718        p.blocking = Blocking::Conflict;
6719        assert_eq!(decide_with(&p, 0, 4, Duration::ZERO, Absent), Step::Rebase);
6720        // And a pull request that left our hands is still done.
6721        p.state = PrLifecycle::Merged;
6722        assert_eq!(
6723            decide_with(&p, 0, 4, Duration::ZERO, Absent),
6724            Step::Done { merged: true }
6725        );
6726    }
6727
6728    #[test]
6729    fn a_green_pull_request_with_nothing_outstanding_parses_as_ready_to_merge() {
6730        let state = parse_pr(GREEN_OPEN).expect("green fixture parses");
6731        assert_eq!(state.number, 10);
6732        assert_eq!(state.state, PrLifecycle::Open);
6733        assert_eq!(state.checks, Checks::Green);
6734        assert!(state.failing.is_empty());
6735        assert!(
6736            state.review_comments.is_empty(),
6737            "the only comment is CodeRabbit's trigger notice: {:?}",
6738            state.review_comments
6739        );
6740        assert_eq!(decide(&state, 0, 4, Duration::ZERO), Step::Merge);
6741    }
6742
6743    #[test]
6744    fn a_failing_check_parses_as_red_and_is_named() {
6745        let state = parse_pr(RED_OPEN).expect("red fixture parses");
6746        assert_eq!(state.checks, Checks::Red);
6747        assert_eq!(state.failing, vec!["editorconfig".to_owned()]);
6748        // The captured payload says `UNSTABLE` - mergeable, with a check
6749        // nobody requires red - which is exactly the shape that had to be
6750        // merged by hand. Asserted separately, in
6751        // `a_red_check_nobody_requires_does_not_buy_a_fix_round`. What this
6752        // test is about is that a red check is *named*, so the reason a fixer
6753        // is handed says which one; so it asks the blocking question here.
6754        let mut blocking = state.clone();
6755        blocking.blocking = Blocking::Yes;
6756        match decide(&blocking, 0, 4, Duration::ZERO) {
6757            Step::Fix { reason } => {
6758                assert!(reason.contains("editorconfig"), "reason: {reason}");
6759                assert!(reason.contains("failing"), "reason: {reason}");
6760            }
6761            other => panic!("expected a fix round, got {other:?}"),
6762        }
6763    }
6764
6765    #[test]
6766    fn a_check_still_running_parses_as_pending_and_is_waited_for() {
6767        let state = parse_pr(PENDING_OPEN).expect("pending fixture parses");
6768        assert_eq!(state.checks, Checks::Pending);
6769        assert_eq!(decide(&state, 0, 4, Duration::ZERO), Step::Wait);
6770    }
6771
6772    #[test]
6773    fn a_pull_request_merged_underneath_us_is_done_rather_than_a_failure() {
6774        let state = parse_pr(MERGED).expect("merged fixture parses");
6775        assert_eq!(state.state, PrLifecycle::Merged);
6776        assert_eq!(
6777            decide(&state, 0, 4, Duration::ZERO),
6778            Step::Done { merged: true }
6779        );
6780    }
6781
6782    #[test]
6783    fn a_review_that_found_something_is_outstanding_and_holds_the_merge() {
6784        let state = parse_pr(REVIEWED_OPEN).expect("reviewed fixture parses");
6785        assert_eq!(state.checks, Checks::Green);
6786        let authors: Vec<&str> = state
6787            .review_comments
6788            .iter()
6789            .map(|c| c.author.as_str())
6790            .collect();
6791        assert_eq!(
6792            authors,
6793            vec!["claude"],
6794            "CodeRabbit's walkthrough is machinery; Claude's review is a finding"
6795        );
6796        match decide(&state, 0, 4, Duration::ZERO) {
6797            Step::Fix { reason } => assert!(reason.contains("unresolved"), "reason: {reason}"),
6798            other => panic!("expected a fix round, got {other:?}"),
6799        }
6800    }
6801
6802    #[test]
6803    fn inline_review_comments_keep_their_file_and_line() {
6804        let comments = parse_inline_comments(INLINE).expect("inline fixture parses");
6805        assert_eq!(comments.len(), 1);
6806        assert_eq!(comments[0].author, "claude[bot]");
6807        assert_eq!(comments[0].path.as_deref(), Some("src/graph.rs"));
6808        assert_eq!(comments[0].line, Some(231));
6809        assert!(comments[0].body.contains("empty"), "{}", comments[0].body);
6810    }
6811
6812    #[test]
6813    fn a_status_only_bot_comment_does_not_trigger_a_fix_round() {
6814        assert!(
6815            is_noise(CODERABBIT_TRIGGER),
6816            "CodeRabbit's trigger notice declares itself not a review"
6817        );
6818        assert!(
6819            is_noise(CLAUDE_CHECKLIST),
6820            "a progress checklist asks for nothing"
6821        );
6822        assert!(
6823            !is_noise(CLAUDE_FINDING),
6824            "a review that names a bug is input, not noise"
6825        );
6826
6827        let mut clean = pr(Checks::Green, &[], 0);
6828        clean.review_comments.push(ReviewComment {
6829            author: "coderabbitai".to_owned(),
6830            path: None,
6831            line: None,
6832            body: CODERABBIT_TRIGGER.to_owned(),
6833        });
6834        clean.review_comments.retain(|c| !is_noise(&c.body));
6835        assert_eq!(decide(&clean, 0, 4, Duration::ZERO), Step::Merge);
6836
6837        let mut found = pr(Checks::Green, &[], 0);
6838        found.review_comments.push(ReviewComment {
6839            author: "claude".to_owned(),
6840            path: None,
6841            line: None,
6842            body: CLAUDE_FINDING.to_owned(),
6843        });
6844        found.review_comments.retain(|c| !is_noise(&c.body));
6845        assert!(matches!(
6846            decide(&found, 0, 4, Duration::ZERO),
6847            Step::Fix { .. }
6848        ));
6849    }
6850
6851    #[test]
6852    fn the_policy_table_holds_for_every_combination_that_matters() {
6853        let cases: Vec<(&str, PrState, usize, usize, Duration, Step)> = vec![
6854            (
6855                "pending checks are waited for, even on the last round",
6856                pr(Checks::Pending, &[], 0),
6857                4,
6858                4,
6859                Duration::ZERO,
6860                Step::Wait,
6861            ),
6862            (
6863                "red checks are fixed",
6864                pr(Checks::Red, &["editorconfig"], 0),
6865                0,
6866                4,
6867                Duration::ZERO,
6868                Step::Fix {
6869                    reason: "1 check(s) failing: editorconfig".to_owned(),
6870                },
6871            ),
6872            (
6873                "green with comments is fixed, not merged",
6874                pr(Checks::Green, &[], 2),
6875                1,
6876                4,
6877                Duration::ZERO,
6878                Step::Fix {
6879                    reason: "checks are green but 2 review comment(s) are unresolved: coderabbitai"
6880                        .to_owned(),
6881                },
6882            ),
6883            (
6884                "green and clean merges",
6885                pr(Checks::Green, &[], 0),
6886                3,
6887                4,
6888                Duration::ZERO,
6889                Step::Merge,
6890            ),
6891            (
6892                "an unreadable rollup is waited on while the grace lasts",
6893                pr(Checks::Unknown, &[], 0),
6894                0,
6895                4,
6896                Duration::ZERO,
6897                Step::Wait,
6898            ),
6899            (
6900                "an unreadable rollup is never merged once the grace is spent",
6901                pr(Checks::Unknown, &[], 0),
6902                0,
6903                4,
6904                CHECKS_GRACE,
6905                Step::GiveUp {
6906                    reason: "no check status is readable on the pull request after 3 minute(s); \
6907                             refusing to merge on a guess"
6908                        .to_owned(),
6909                },
6910            ),
6911        ];
6912        for (what, state, round, budget, waited, want) in cases {
6913            assert_eq!(decide(&state, round, budget, waited), want, "{what}");
6914        }
6915    }
6916
6917    #[test]
6918    fn the_forge_verdict_survives_the_round_trip_from_gh() {
6919        // Read off `gh pr view --json ...,mergeStateStatus`, because a field
6920        // requested but never parsed is the kind of thing that looks wired up
6921        // and answers `Unsaid` forever.
6922        let green = parse_pr(GREEN_OPEN).expect("parse");
6923        assert_eq!(green.blocking, Blocking::No);
6924        let red = parse_pr(RED_OPEN).expect("parse");
6925        assert_eq!(
6926            red.blocking,
6927            Blocking::No,
6928            "`UNSTABLE` is mergeable: the red check is one nobody requires"
6929        );
6930        assert_eq!(red.checks, Checks::Red, "and it is still reported as red");
6931        // A payload from an older `gh` has no such field at all.
6932        let quiet =
6933            parse_pr(&GREEN_OPEN.replace("\"mergeStateStatus\": \"CLEAN\",", "")).expect("parse");
6934        assert_eq!(quiet.blocking, Blocking::Unsaid);
6935    }
6936
6937    #[test]
6938    fn a_red_check_nobody_requires_does_not_buy_a_fix_round() {
6939        // Pull request 37's only red check was `editorconfig`, failing
6940        // because the action could not fetch its own binary after
6941        // editorconfig-checker v4 renamed its release assets. The repository
6942        // does not require it. magi answered by asking a fixer to repair a
6943        // change that was fine, and the pull request had to be merged by hand.
6944        let mut nonblocking = pr(Checks::Red, &["editorconfig", "coverage"], 0);
6945        nonblocking.blocking = Blocking::No;
6946        assert_eq!(
6947            decide(&nonblocking, 0, 4, Duration::ZERO),
6948            Step::Merge,
6949            "the forge says nothing is in the way, so nothing is"
6950        );
6951
6952        // The same red, gated on: that is a fix round, as before.
6953        let mut blocking = pr(Checks::Red, &["test (ubuntu-latest)"], 0);
6954        blocking.blocking = Blocking::Yes;
6955        assert!(matches!(
6956            decide(&blocking, 0, 4, Duration::ZERO),
6957            Step::Fix { .. }
6958        ));
6959
6960        // A review comment still outranks green-enough: a non-required red
6961        // must not become a way to merge past an unanswered reviewer.
6962        let mut commented = pr(Checks::Red, &["coverage"], 1);
6963        commented.blocking = Blocking::No;
6964        assert!(matches!(
6965            decide(&commented, 0, 4, Duration::ZERO),
6966            Step::Fix { .. }
6967        ));
6968
6969        // And silence from the forge is not consent.
6970        let mut unsaid = pr(Checks::Red, &["coverage"], 0);
6971        unsaid.blocking = Blocking::Unsaid;
6972        assert_eq!(decide(&unsaid, 0, 4, Duration::ZERO), Step::Wait);
6973        assert!(matches!(
6974            decide(&unsaid, 0, 4, CHECKS_GRACE),
6975            Step::Fix { .. }
6976        ));
6977    }
6978
6979    #[test]
6980    fn a_red_merge_is_announced_with_every_failing_check_and_a_green_one_is_not() {
6981        let mut red = pr(Checks::Red, &["test (windows-latest)", "coverage"], 0);
6982        red.blocking = Blocking::No;
6983        assert_eq!(
6984            decide(&red, 0, 4, Duration::ZERO),
6985            Step::Merge,
6986            "announcing must not change the decision"
6987        );
6988        let said = red_merge_summary("yukimemi/magi", &red).expect("red merge is announced");
6989        assert!(said.contains("yukimemi/magi"), "{said}");
6990        assert!(said.contains("#16"), "{said}");
6991        assert!(
6992            said.contains("https://github.com/yukimemi/magi/pull/16"),
6993            "{said}"
6994        );
6995        assert!(
6996            said.contains("test (windows-latest)") && said.contains("coverage"),
6997            "{said}"
6998        );
6999
7000        // `failing` can be left over on a green observation; only `checks` counts.
7001        let green = pr(Checks::Green, &["stale"], 0);
7002        assert_eq!(red_merge_summary("yukimemi/magi", &green), None);
7003    }
7004
7005    #[test]
7006    fn red_merge_notices_omit_empty_check_details() {
7007        for checks in [vec![], vec!["", "  "]] {
7008            let red = pr(Checks::Red, &checks, 0);
7009            let summary = red_merge_summary("owner/repo", &red).unwrap();
7010            let notice = crate::notices::merged_red("run-1", &summary);
7011            assert_eq!(
7012                notice.message,
7013                format!("Merged owner/repo PR #16 with red checks ({})", red.url)
7014            );
7015            assert_eq!(notice.severity, crate::notices::Severity::Warn);
7016        }
7017        let red = pr(Checks::Red, &["", " test ", " "], 0);
7018        let summary = red_merge_summary("owner/repo", &red).unwrap();
7019        assert!(summary.contains("with red checks: test ("), "{summary}");
7020    }
7021
7022    #[test]
7023    fn the_repo_label_comes_from_the_pull_request_url() {
7024        let p = Path::new("/tmp/checkout");
7025        assert_eq!(
7026            repo_label(p, "https://github.com/yukimemi/magi/pull/16"),
7027            "yukimemi/magi"
7028        );
7029        assert_eq!(repo_label(p, "not a url"), "checkout");
7030    }
7031
7032    #[test]
7033    fn a_branch_the_base_moved_under_is_rebased_not_fixed() {
7034        // Pull requests 35 and 37 were both rebased by hand: a competition
7035        // that runs for two hours against a repository merging pull requests
7036        // all day conflicts on the way in, and that is arithmetic rather
7037        // than a defect in the change.
7038        let mut conflicted = pr(Checks::Green, &[], 0);
7039        conflicted.blocking = Blocking::Conflict;
7040        assert_eq!(decide(&conflicted, 0, 4, Duration::ZERO), Step::Rebase);
7041
7042        // Decided before the checks, and even with the rounds spent: every
7043        // check on a branch that cannot land is an answer about a state that
7044        // cannot land, and a conflict is not the change's fault.
7045        let mut red = pr(Checks::Red, &["test (ubuntu-latest)"], 2);
7046        red.blocking = Blocking::Conflict;
7047        assert_eq!(decide(&red, 4, 4, Duration::ZERO), Step::Rebase);
7048
7049        // The lifecycle still wins over everything, conflict included.
7050        let mut merged = pr(Checks::Red, &[], 0);
7051        merged.blocking = Blocking::Conflict;
7052        merged.state = PrLifecycle::Merged;
7053        assert_eq!(
7054            decide(&merged, 0, 4, Duration::ZERO),
7055            Step::Done { merged: true }
7056        );
7057    }
7058
7059    #[test]
7060    fn the_forge_verdict_is_read_off_merge_state_status() {
7061        // The spellings that mean "mergeable". `UNSTABLE` is the one that
7062        // matters: mergeable, with a non-required check red or still running.
7063        for ok in ["CLEAN", "UNSTABLE", "unstable", "HAS_HOOKS"] {
7064            assert_eq!(Blocking::of(ok), Blocking::No, "{ok}");
7065            assert!(!Blocking::of(ok).stops_a_merge(), "{ok}");
7066        }
7067        assert_eq!(Blocking::of("DIRTY"), Blocking::Conflict);
7068        assert_eq!(Blocking::of("BLOCKED"), Blocking::Yes);
7069        assert_eq!(Blocking::of("BEHIND"), Blocking::Behind);
7070        // An older `gh`, or a token without the scope, says nothing - and
7071        // refusing to guess is the rule everywhere else in this module.
7072        for quiet in ["", "UNKNOWN"] {
7073            assert_eq!(Blocking::of(quiet), Blocking::Unsaid);
7074            assert!(Blocking::of(quiet).stops_a_merge());
7075        }
7076    }
7077
7078    #[test]
7079    fn a_merge_command_that_failed_after_merging_is_still_a_merge() {
7080        let argv = merge_argv(28, "fix: retry uploads on transient network errors");
7081        // The exact stderr from run ec12, in a jj-colocated repository.
7082        let jj = "could not determine current branch: failed to run git: not on any branch";
7083
7084        let landed = merged_after_all(&argv, jj, Some(PrLifecycle::Merged))
7085            .expect("the forge says merged, so it merged");
7086        assert!(landed.ok);
7087        assert!(
7088            landed.detail.contains("but the pull request is merged"),
7089            "the record must not read as a clean success: {}",
7090            landed.detail
7091        );
7092        assert!(
7093            landed.detail.contains("not on any branch"),
7094            "and it must keep what the command actually said: {}",
7095            landed.detail
7096        );
7097
7098        // A pull request still open means the merge really failed.
7099        assert!(merged_after_all(&argv, jj, Some(PrLifecycle::Open)).is_none());
7100        assert!(merged_after_all(&argv, jj, Some(PrLifecycle::Closed)).is_none());
7101        // And an unreadable answer is not evidence of success.
7102        assert!(merged_after_all(&argv, jj, None).is_none());
7103    }
7104
7105    #[test]
7106    fn a_pull_request_closed_underneath_us_is_done_and_not_merged() {
7107        let mut state = pr(Checks::Red, &["editorconfig"], 3);
7108        state.state = PrLifecycle::Closed;
7109        assert_eq!(
7110            decide(&state, 0, 4, Duration::ZERO),
7111            Step::Done { merged: false },
7112            "a human closing the pull request ends the loop, whatever CI says"
7113        );
7114    }
7115
7116    #[test]
7117    fn the_last_round_gives_up_with_a_reason_naming_what_is_still_failing() {
7118        let red = decide(
7119            &pr(Checks::Red, &["editorconfig", "test (macos)"], 0),
7120            4,
7121            4,
7122            Duration::ZERO,
7123        );
7124        match red {
7125            Step::GiveUp { reason } => {
7126                assert!(reason.contains("editorconfig"), "reason: {reason}");
7127                assert!(reason.contains("test (macos)"), "reason: {reason}");
7128                assert!(reason.contains("4 fix round(s)"), "reason: {reason}");
7129            }
7130            other => panic!("expected a give-up, got {other:?}"),
7131        }
7132
7133        let commented = decide(&pr(Checks::Green, &[], 1), 2, 2, Duration::ZERO);
7134        match commented {
7135            Step::GiveUp { reason } => {
7136                assert!(reason.contains("unresolved"), "reason: {reason}");
7137                assert!(reason.contains("2 fix round(s)"), "reason: {reason}");
7138            }
7139            other => panic!("expected a give-up, got {other:?}"),
7140        }
7141    }
7142
7143    #[test]
7144    fn the_merge_command_squashes_deletes_the_branch_and_sets_its_own_subject() {
7145        let candidate_commit = "magi: candidate A (uncommitted work)";
7146        let subject = merge_subject(candidate_commit, "add retries to the uploader");
7147        let argv = merge_argv(16, &subject);
7148
7149        assert!(argv.contains(&"--squash".to_owned()));
7150        assert!(argv.contains(&"--delete-branch".to_owned()));
7151        assert!(argv.contains(&"--subject".to_owned()));
7152        assert_eq!(
7153            argv.last().map(String::as_str),
7154            Some("add retries to the uploader"),
7155            "the subject must not be the candidate commit message"
7156        );
7157        assert_ne!(subject, candidate_commit);
7158    }
7159
7160    #[test]
7161    fn a_real_pull_request_title_is_used_as_the_squash_subject_verbatim() {
7162        assert_eq!(
7163            merge_subject("feat: a queue, an unattended loop, and a phone UI", "task"),
7164            "feat: a queue, an unattended loop, and a phone UI"
7165        );
7166        assert_eq!(
7167            merge_subject("", "# port the retry logic\n\ndetails"),
7168            "port the retry logic",
7169            "an empty title falls back to the task's first line, heading marks stripped"
7170        );
7171    }
7172
7173    #[test]
7174    fn a_failing_checks_details_url_yields_the_job_to_read_logs_from() {
7175        let url = "https://github.com/yukimemi/magi/actions/runs/33587406996/job/100114323572";
7176        assert_eq!(job_of(url).as_deref(), Some("100114323572"));
7177        assert_eq!(run_of(url).as_deref(), Some("33587406996"));
7178        assert_eq!(job_of("https://coderabbit.ai/status"), None);
7179        assert_eq!(run_of(""), None);
7180    }
7181
7182    #[test]
7183    fn magis_own_stop_comment_is_never_read_back_as_a_finding() {
7184        let mut out = Vec::new();
7185        push_if_outstanding(
7186            &mut out,
7187            ReviewComment {
7188                author: "yukimemi".to_owned(),
7189                path: None,
7190                line: None,
7191                body: format!("{MARKER}\nmagi stopped landing this pull request: 1 check failing"),
7192            },
7193        );
7194        assert!(out.is_empty());
7195    }
7196
7197    /// A run with no tally, so [`RunState::winner`] is `None` and the panel
7198    /// falls back to the repository - which keeps these tests free of a
7199    /// worktree, a `git` invocation and a network.
7200    fn run_state() -> RunState {
7201        let mut state = RunState::new(
7202            std::path::PathBuf::from("/repo/magi"),
7203            "main".to_owned(),
7204            "abcdef1234".to_owned(),
7205            "add retries to the uploader".to_owned(),
7206            crate::config::Config::default(),
7207        );
7208        // These fixtures test execution flow, independent of host disk capacity.
7209        state.config.disk.min_free_bytes = 0;
7210        // Tests run in parallel against one persistent home and the ids
7211        // `RunState::new` draws from the clock can repeat, so two tests would
7212        // share a run's questions. The home also outlives the process, so the
7213        // counter alone would reuse an earlier run's ids.
7214        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
7215        let nanos = std::time::SystemTime::now()
7216            .duration_since(std::time::UNIX_EPOCH)
7217            .map_or(0, |d| d.subsec_nanos() % 1_000_000);
7218        state.id = format!(
7219            "20261004-{nanos:06}-{:04x}",
7220            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
7221        );
7222        state
7223    }
7224
7225    fn green_pr() -> PrState {
7226        PrState {
7227            url: "https://github.com/yukimemi/magi/pull/42".to_owned(),
7228            number: 42,
7229            state: PrLifecycle::Open,
7230            checks: Checks::Green,
7231            // The forge sees nothing in the way unless a test says otherwise.
7232            blocking: Blocking::No,
7233            failing: Vec::new(),
7234            review_comments: vec![ReviewComment {
7235                author: "coderabbitai".to_owned(),
7236                path: Some("src/land.rs".to_owned()),
7237                line: Some(212),
7238                body: "this branch never checks the exit code".to_owned(),
7239            }],
7240        }
7241    }
7242
7243    #[test]
7244    fn land_fixer_defers_review_and_verification_without_a_cache() {
7245        let state = run_state();
7246        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7247        assert!(p.contains(crate::prompt::child_run_ownership()), "{p}");
7248        assert!(p.contains("Commit in this worktree"), "{p}");
7249    }
7250
7251    #[test]
7252    fn github_facing_land_text_is_english_whatever_the_language() {
7253        let mut state = run_state();
7254        state.config.graph.language = "ja".to_owned();
7255        let comment = stop_comment(&state.id, "checks are still red");
7256        assert!(crate::github_text::check("", &comment).is_empty());
7257        assert!(comment.is_ascii(), "{comment}");
7258        assert!(comment.starts_with(MARKER));
7259
7260        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7261        let ja_at = p.find("Write all prose in ja").unwrap();
7262        let rule_at = p.find(crate::prompt::GITHUB_ENGLISH_HEADING).unwrap();
7263        assert!(ja_at < rule_at, "{p}");
7264        assert!(p.contains("stays in Japanese"), "{p}");
7265
7266        state.config.graph.language = "en".to_owned();
7267        let p = fix_prompt(&state, &green_pr(), 1, 2, "red", "");
7268        assert!(p.contains(crate::prompt::GITHUB_ENGLISH_HEADING), "{p}");
7269        assert!(!p.contains("does not apply"), "{p}");
7270    }
7271
7272    const NUMSTAT: &str = "12\t3\tsrc/land.rs\n40\t1\tsrc/web.rs\n-\t-\tassets/logo.png";
7273
7274    fn panel() -> String {
7275        approval_panel(
7276            &run_state(),
7277            &green_pr(),
7278            NUMSTAT,
7279            "diff --git a/src/land.rs b/src/land.rs\n@@ -1,2 +1,2 @@\n-old line\n+new line\n context",
7280            &[
7281                "land: ask before merging".to_owned(),
7282                "land: colour the diff".to_owned(),
7283            ],
7284            "feat: merge approval from the phone",
7285        )
7286    }
7287
7288    #[test]
7289    fn the_approval_panel_carries_the_whole_case_for_the_merge() {
7290        let html = panel();
7291        for needle in [
7292            "42",
7293            "main",
7294            "src/land.rs",
7295            "src/web.rs",
7296            "assets/logo.png",
7297            "feat: merge approval from the phone",
7298            "land: ask before merging",
7299            "land: colour the diff",
7300            "coderabbitai",
7301            "this branch never checks the exit code",
7302            "green",
7303        ] {
7304            assert!(html.contains(needle), "the panel must state `{needle}`");
7305        }
7306    }
7307
7308    async fn landing_git_fixture() -> (tempfile::TempDir, RunState, String) {
7309        crate::run::pin_test_home();
7310        let tmp = tempfile::tempdir().unwrap();
7311        let repo = tmp.path().join("repo");
7312        let remote = tmp.path().join("remote.git");
7313        std::fs::create_dir(&repo).unwrap();
7314        git::git(tmp.path(), &["init", "--bare", remote.to_str().unwrap()])
7315            .await
7316            .unwrap();
7317        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
7318        git::git(&repo, &["config", "user.name", "Test"])
7319            .await
7320            .unwrap();
7321        git::git(&repo, &["config", "user.email", "test@example.test"])
7322            .await
7323            .unwrap();
7324        std::fs::write(repo.join("base"), "base").unwrap();
7325        git::git(&repo, &["add", "."]).await.unwrap();
7326        git::git(&repo, &["commit", "-m", "base"]).await.unwrap();
7327        git::git(
7328            &repo,
7329            &["remote", "add", "origin", remote.to_str().unwrap()],
7330        )
7331        .await
7332        .unwrap();
7333        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
7334        git::git(&repo, &["checkout", "-b", "winner"])
7335            .await
7336            .unwrap();
7337        std::fs::write(repo.join("change"), "change").unwrap();
7338        git::git(&repo, &["add", "."]).await.unwrap();
7339        git::git(&repo, &["commit", "-m", "change"]).await.unwrap();
7340        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
7341        git::git(&repo, &["push", "origin", "HEAD:refs/heads/task-head"])
7342            .await
7343            .unwrap();
7344        let mut state = run_state();
7345        state.repo = repo.clone();
7346        state.base_commit = git::rev_parse(&repo, "origin/main").await.unwrap();
7347        state.config.graph.land = true;
7348        state.config.graph.land_approval = true;
7349        state.pr_head = Some("task-head".into());
7350        state.pr_pushed_head = Some(head.clone());
7351        state.candidates = vec![winning_candidate("change")];
7352        state.candidates[0].worktree = repo;
7353        state.candidates[0].branch = "winner".into();
7354        state.tally = Some(uncontested_tally());
7355        state.gate_ran = true;
7356        state.gate_head = Some(head.clone());
7357        state.land_sync_pending = true;
7358        state.save().unwrap();
7359        (tmp, state, head)
7360    }
7361
7362    async fn resume_observed_head(state: &mut RunState, head: &str) -> Result<String> {
7363        let forge = Scripted::new(vec![seen(head, Checks::Green, "CLEAN", false)], vec![]);
7364        resume_landing_head(state, head, &green_pr().url, &forge, None).await
7365    }
7366
7367    async fn advance_landing_base(state: &RunState) {
7368        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7369        std::fs::write(state.repo.join("advance"), "advance").unwrap();
7370        git::git(&state.repo, &["add", "."]).await.unwrap();
7371        git::git(&state.repo, &["commit", "-m", "advance base"])
7372            .await
7373            .unwrap();
7374        git::git(&state.repo, &["push", "origin", "main"])
7375            .await
7376            .unwrap();
7377        git::git(&state.repo, &["checkout", "winner"])
7378            .await
7379            .unwrap();
7380    }
7381
7382    async fn foreign_landing_fixture() -> (tempfile::TempDir, RunState, String, std::path::PathBuf)
7383    {
7384        let (tmp, mut state, old) = landing_git_fixture().await;
7385        let path = tmp.path().join("foreign");
7386        git::worktree_add_branch(&state.repo, &path, "task-head", &old)
7387            .await
7388            .unwrap();
7389        state.foreign_checkout = Some(
7390            crate::foreign_checkout::inspect(&state.repo, "task-head", &path)
7391                .await
7392                .unwrap(),
7393        );
7394        state.config.merge.mode = crate::config::MergeMode::Pr;
7395        state.save().unwrap();
7396        (tmp, state, old, path)
7397    }
7398
7399    #[tokio::test]
7400    async fn foreign_landing_sync_and_interrupted_resumes_preserve_delivery_ancestry() {
7401        for phase in 0..4 {
7402            let (_tmp, mut state, old, path) = foreign_landing_fixture().await;
7403            advance_landing_base(&state).await;
7404            state.config.verify.gate = vec!["test -f advance && test -f change".into()];
7405            if phase == 0 {
7406                // The live Step::Rebase path uses this same synchronization
7407                // and publication pair, without going through resume.
7408                assert_eq!(
7409                    rebase_landing_worktree(&mut state, "origin/main")
7410                        .await
7411                        .unwrap(),
7412                    crate::rebase::Rebased::Applied
7413                );
7414            } else {
7415                interrupt_landing_rebase(&mut state).await;
7416                let repaired_tree = git::tree_of(&state.repo, "HEAD").await.unwrap();
7417                if phase == 2 {
7418                    git::sync_to_head(&state.repo).await.unwrap();
7419                } else if phase == 3 {
7420                    // Crash after joining history, before clearing its saved
7421                    // start. Repeating restoration must not add another merge.
7422                    restore_landing_worktree(&mut state).await.unwrap();
7423                    let joined = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7424                    state.land_rebase_from = Some(old.clone());
7425                    state.save().unwrap();
7426                    restore_landing_worktree(&mut state).await.unwrap();
7427                    assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), joined);
7428                }
7429                state.save().unwrap();
7430                state = RunState::load(&state.id).unwrap();
7431                restore_landing_worktree(&mut state).await.unwrap();
7432                assert_eq!(
7433                    git::tree_of(&state.repo, "HEAD").await.unwrap(),
7434                    repaired_tree
7435                );
7436            }
7437            let head = if phase == 0 {
7438                let forge = Scripted::new(vec![seen(&old, Checks::Green, "CLEAN", false)], vec![]);
7439                publish_landing_head(&mut state, &old, &green_pr().url, &forge)
7440                    .await
7441                    .unwrap()
7442            } else {
7443                resume_observed_head(&mut state, &old).await.unwrap()
7444            };
7445            assert!(git::is_ancestor(&state.repo, &old, &head).await);
7446            assert!(git::is_ancestor(&state.repo, "origin/main", &head).await);
7447            assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
7448            assert_eq!(
7449                git::remote_head(&state.repo, "origin", "task-head")
7450                    .await
7451                    .unwrap(),
7452                Some(head.clone())
7453            );
7454            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7455            assert_eq!(state.foreign_checkout.as_ref().unwrap().synced_head, head);
7456            assert!(state.gate_allows_progress());
7457            assert!(state.land_rebase_from.is_none());
7458            assert!(!state.land_sync_pending);
7459            assert!(git::is_clean(&path).await.unwrap());
7460        }
7461    }
7462
7463    #[tokio::test]
7464    async fn foreign_landing_conflict_repair_can_resume_and_publish_without_losing_ancestry() {
7465        let (_tmp, mut state, old, path) = foreign_landing_fixture().await;
7466        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7467        std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
7468        git::commit_all(&state.repo, "conflicting base")
7469            .await
7470            .unwrap();
7471        git::git(&state.repo, &["push", "origin", "main"])
7472            .await
7473            .unwrap();
7474        git::git(&state.repo, &["checkout", "winner"])
7475            .await
7476            .unwrap();
7477        landing_gate_fixer(
7478            &mut state,
7479            "cat >/dev/null; printf resolved > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"resolved\"}'",
7480        );
7481        state.config.graph.gate_fix_rounds = 0;
7482        state.config.verify.gate = vec!["exit 1".into()];
7483        assert!(resume_observed_head(&mut state, &old).await.is_err());
7484        assert!(state.rebase_fixes.iter().any(|fix| fix.finished));
7485        let repaired = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7486        assert!(git::is_ancestor(&state.repo, &old, &repaired).await);
7487        assert_eq!(
7488            std::fs::read_to_string(state.repo.join("change")).unwrap(),
7489            "resolved"
7490        );
7491        // A red gate must neither deliver nor publish the repaired tree.
7492        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), old);
7493        assert_eq!(
7494            git::remote_head(&state.repo, "origin", "task-head")
7495                .await
7496                .unwrap(),
7497            Some(old.clone())
7498        );
7499        state = RunState::load(&state.id).unwrap();
7500        state.config.verify.gate = vec!["grep -q resolved change".into()];
7501        let head = resume_observed_head(&mut state, &old).await.unwrap();
7502        assert_eq!(head, repaired);
7503        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
7504        assert_eq!(
7505            std::fs::read_to_string(path.join("change")).unwrap(),
7506            "resolved"
7507        );
7508        assert_eq!(
7509            git::remote_head(&state.repo, "origin", "task-head")
7510                .await
7511                .unwrap(),
7512            Some(head.clone())
7513        );
7514        assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7515        assert!(git::is_ancestor(&state.repo, "origin/main", &head).await);
7516        assert!(git::is_clean(&path).await.unwrap());
7517    }
7518
7519    #[tokio::test]
7520    async fn landing_resume_completes_the_last_charged_sync_attempt() {
7521        for (scratch_started, saved_target) in [(false, true), (true, true), (true, false)] {
7522            let (_tmp, mut state, old) = landing_git_fixture().await;
7523            git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7524            std::fs::write(state.repo.join("change"), "conflicting base change").unwrap();
7525            git::commit_all(&state.repo, "conflicting base")
7526                .await
7527                .unwrap();
7528            git::git(&state.repo, &["push", "origin", "main"])
7529                .await
7530                .unwrap();
7531            git::git(&state.repo, &["checkout", "winner"])
7532                .await
7533                .unwrap();
7534            let target = git::rev_parse(&state.repo, "origin/main").await.unwrap();
7535            state.config.graph.land_rounds = 1;
7536            state.land_sync_attempts = 1;
7537            state.land_sync_target = saved_target.then(|| target.clone());
7538            state.land_rebase_from = Some(old.clone());
7539            landing_gate_fixer(
7540                &mut state,
7541                "cat >/dev/null; printf resolved > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"resolved\"}'",
7542            );
7543            state.config.verify.gate = vec!["grep -q resolved change".into()];
7544            state.save().unwrap();
7545            // Simulate interruption before the scratch start and at a conflict.
7546            if scratch_started {
7547                assert!(matches!(
7548                    git::rebase_start(&state.repo, &state.dir().join("rebase"), "winner", &target)
7549                        .await
7550                        .unwrap(),
7551                    git::RebaseStart::Conflicted(_)
7552                ));
7553            }
7554            state = RunState::load(&state.id).unwrap();
7555            let head = resume_observed_head(&mut state, &old).await.unwrap();
7556            assert_ne!(head, old);
7557            assert_eq!(state.land_sync_attempts, 1);
7558            assert!(state.land_sync_target.is_none());
7559            assert!(state.land_rebase_from.is_none());
7560            assert!(!state.land_sync_pending);
7561            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7562            assert!(state.gate_allows_progress());
7563            assert_eq!(
7564                git::remote_head(&state.repo, "origin", "task-head")
7565                    .await
7566                    .unwrap(),
7567                Some(head)
7568            );
7569            assert!(
7570                rebase_landing_worktree(&mut state, "origin/main")
7571                    .await
7572                    .unwrap_err()
7573                    .to_string()
7574                    .contains("budget exhausted")
7575            );
7576        }
7577    }
7578
7579    #[tokio::test]
7580    async fn landing_resume_gates_rebased_sha_and_publishes_it_to_the_existing_head() {
7581        let (_tmp, mut state, old) = landing_git_fixture().await;
7582        advance_landing_base(&state).await;
7583        state.config.verify.gate = vec!["test -f advance".into()];
7584        let head = resume_observed_head(&mut state, &old).await.unwrap();
7585        assert_ne!(head, old);
7586        assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
7587        assert!(state.gate_allows_progress());
7588        assert_eq!(
7589            git::remote_head(&state.repo, "origin", "task-head")
7590                .await
7591                .unwrap(),
7592            Some(head.clone())
7593        );
7594        assert_eq!(state.pr_pushed_head, Some(head));
7595        assert!(!state.land_sync_pending);
7596        assert!(state.config.graph.land_approval);
7597    }
7598
7599    fn landing_gate_fixer(state: &mut RunState, script: &str) {
7600        state.config.disk.min_free_bytes = 0;
7601        state.config.graph.gate_fix_rounds = 1;
7602        state.config.agents = vec![crate::config::AgentSpec {
7603            id: "mock".into(),
7604            kind: crate::config::AgentKind::Command,
7605            model: None,
7606            command: vec!["sh".into(), "-c".into(), script.into()],
7607            extra_args: Vec::new(),
7608            env: Default::default(),
7609            prompt_delivery: None,
7610            max_turn_secs: None,
7611        }];
7612        state.candidates[0].agent = "mock".into();
7613    }
7614
7615    #[tokio::test]
7616    async fn landing_resume_revalidates_an_operator_published_winner_extension() {
7617        let (_tmp, mut state, old) = landing_git_fixture().await;
7618        std::fs::write(state.repo.join("change"), "operator update").unwrap();
7619        git::commit_all(&state.repo, "extend winner").await.unwrap();
7620        let updated = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7621        git::git(
7622            &state.repo,
7623            &["push", "origin", "HEAD:refs/heads/task-head"],
7624        )
7625        .await
7626        .unwrap();
7627        state.config.verify.gate = vec!["exit 1".into()];
7628        state.config.graph.gate_fix_rounds = 0;
7629        assert!(resume_observed_head(&mut state, &updated).await.is_err());
7630        assert_ne!(old, updated);
7631        assert_eq!(state.gate_head.as_ref(), Some(&updated));
7632        assert!(!state.gate_allows_progress());
7633        assert!(state.land_sync_pending);
7634        state.config.verify.gate = vec!["grep -q 'operator update' change".into()];
7635        let head = resume_observed_head(&mut state, &updated).await.unwrap();
7636        assert_eq!(head, updated);
7637        assert!(state.gate_allows_progress());
7638        assert!(!state.land_sync_pending);
7639        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
7640        land_with(&mut state, &green_pr().url, &forge)
7641            .await
7642            .unwrap();
7643        assert!(state.parked);
7644        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
7645        assert!(forge.argvs().is_empty());
7646    }
7647
7648    #[tokio::test]
7649    async fn landing_resume_refuses_remote_only_and_divergent_operator_updates() {
7650        for divergent in [false, true] {
7651            let (_tmp, mut state, old) = landing_git_fixture().await;
7652            if divergent {
7653                git::git(&state.repo, &["reset", "--hard", "origin/main"])
7654                    .await
7655                    .unwrap();
7656            }
7657            std::fs::write(state.repo.join("external"), "external").unwrap();
7658            git::commit_all(&state.repo, "external update")
7659                .await
7660                .unwrap();
7661            let external = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7662            git::git(
7663                &state.repo,
7664                &["push", "--force", "origin", "HEAD:refs/heads/task-head"],
7665            )
7666            .await
7667            .unwrap();
7668            if !divergent {
7669                git::git(&state.repo, &["reset", "--hard", &old])
7670                    .await
7671                    .unwrap();
7672            }
7673            let error = resume_observed_head(&mut state, &external)
7674                .await
7675                .unwrap_err();
7676            assert!(
7677                error
7678                    .to_string()
7679                    .contains("public head moved outside this run")
7680            );
7681            assert_eq!(state.pr_pushed_head.as_ref(), Some(&old));
7682            assert_eq!(
7683                git::remote_head(&state.repo, "origin", "task-head")
7684                    .await
7685                    .unwrap(),
7686                Some(external)
7687            );
7688        }
7689    }
7690
7691    #[tokio::test]
7692    async fn landing_resume_repairs_a_failed_rebased_gate_before_publication() {
7693        let (_tmp, mut state, old) = landing_git_fixture().await;
7694        advance_landing_base(&state).await;
7695        landing_gate_fixer(
7696            &mut state,
7697            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
7698        );
7699        state.config.verify.gate =
7700            vec!["grep -q fixed change || { echo 'change needs repair'; exit 1; }".into()];
7701        state.config.verify.e2e = vec!["test -f advance".into()];
7702        // First save a red gate without spending a fixer round. Resume must
7703        // still offer the remaining budget for this exact same failed head.
7704        state.config.graph.gate_fix_rounds = 0;
7705        assert!(resume_observed_head(&mut state, &old).await.is_err());
7706        assert_eq!(
7707            git::remote_head(&state.repo, "origin", "task-head")
7708                .await
7709                .unwrap(),
7710            Some(old.clone())
7711        );
7712        state.config.graph.gate_fix_rounds = 1;
7713        let head = resume_observed_head(&mut state, &old).await.unwrap();
7714        assert_eq!(state.gate_fixes.len(), 1);
7715        assert!(state.gate_fixes[0].committed);
7716        assert!(state.gate_allows_progress());
7717        assert_eq!(state.gate_head.as_ref(), Some(&head));
7718        assert_eq!(
7719            git::remote_head(&state.repo, "origin", "task-head")
7720                .await
7721                .unwrap(),
7722            Some(head.clone())
7723        );
7724        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
7725        land_with(&mut state, &green_pr().url, &forge)
7726            .await
7727            .unwrap();
7728        assert!(state.parked);
7729        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
7730        assert!(forge.argvs().is_empty());
7731    }
7732
7733    #[tokio::test]
7734    async fn landing_gate_repairs_stop_at_the_saved_budget_without_publishing() {
7735        let (_tmp, mut state, old) = landing_git_fixture().await;
7736        advance_landing_base(&state).await;
7737        landing_gate_fixer(
7738            &mut state,
7739            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
7740        );
7741        state.config.verify.gate = vec!["echo still red; exit 1".into()];
7742        for _ in 0..2 {
7743            assert!(resume_observed_head(&mut state, &old).await.is_err());
7744            assert_eq!(state.gate_fixes.len(), 1);
7745            assert_eq!(
7746                git::remote_head(&state.repo, "origin", "task-head")
7747                    .await
7748                    .unwrap(),
7749                Some(old.clone())
7750            );
7751        }
7752    }
7753
7754    #[tokio::test]
7755    async fn landing_gate_repair_cannot_publish_failed_e2e_on_repeated_resumes() {
7756        let (_tmp, mut state, old) = landing_git_fixture().await;
7757        advance_landing_base(&state).await;
7758        landing_gate_fixer(
7759            &mut state,
7760            "cat >/dev/null; printf fixed > change; printf '{\"addressed\":[],\"rejected\":[],\"notes\":\"fixed\"}'",
7761        );
7762        state.config.verify.gate =
7763            vec!["grep -q fixed change || { echo 'change needs repair'; exit 1; }".into()];
7764        // The repair makes the gate green while breaking an e2e invariant.
7765        state.config.verify.e2e = vec!["grep -q '^change$' change".into()];
7766        for resume in 0..3 {
7767            assert!(resume_observed_head(&mut state, &old).await.is_err());
7768            state = RunState::load(&state.id).unwrap();
7769            let evidence = state.gate_repair_e2e.as_ref().unwrap();
7770            let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
7771            assert_eq!(evidence.head, head);
7772            assert!(!evidence.passed);
7773            assert!(evidence.outcomes.iter().any(|o| !o.ok()));
7774            assert_eq!(state.gate_fixes.len(), 1);
7775            assert_eq!(
7776                git::remote_head(&state.repo, "origin", "task-head")
7777                    .await
7778                    .unwrap(),
7779                Some(old.clone())
7780            );
7781            if resume > 0 {
7782                assert!(
7783                    state.gate_allows_progress(),
7784                    "a green gate must not bypass red e2e"
7785                );
7786            }
7787        }
7788        // Once e2e genuinely succeeds on the same SHA, the saved requirement
7789        // can be satisfied without another fixer or approval bypass.
7790        state.config.verify.e2e = vec!["grep -q fixed change".into()];
7791        let head = resume_observed_head(&mut state, &old).await.unwrap();
7792        assert!(state.gate_repair_e2e.as_ref().unwrap().passed);
7793        assert_eq!(state.gate_repair_e2e.as_ref().unwrap().head, head);
7794        assert_eq!(state.gate_fixes.len(), 1);
7795        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
7796        land_with(&mut state, &green_pr().url, &forge)
7797            .await
7798            .unwrap();
7799        assert!(state.parked);
7800        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
7801        assert!(forge.argvs().is_empty());
7802    }
7803
7804    #[tokio::test]
7805    async fn landing_resumes_recheck_pending_deferred_and_stale_repair_e2e() {
7806        for phase in 0..3 {
7807            let (_tmp, mut state, old) = landing_git_fixture().await;
7808            advance_landing_base(&state).await;
7809            let head = resume_observed_head(&mut state, &old).await.unwrap();
7810            // Persist the shapes left by interruption, resource deferral,
7811            // and a successful check for a different (older) SHA.
7812            state.land_sync_pending = true;
7813            state.config.verify.e2e = vec!["echo e2e is red; exit 1".into()];
7814            state.gate_repair_e2e = Some(crate::run::GateRepairE2e {
7815                head: if phase == 2 {
7816                    old.clone()
7817                } else {
7818                    head.clone()
7819                },
7820                passed: phase == 2,
7821                outcomes: if phase == 1 {
7822                    vec![crate::run::CommandOutcome {
7823                        command: state.config.verify.e2e[0].clone(),
7824                        code: None,
7825                        output_tail: "verification resource unavailable".into(),
7826                        duration_ms: 0,
7827                        resource_blocked: true,
7828                    }]
7829                } else {
7830                    Vec::new()
7831                },
7832            });
7833            state.save().unwrap();
7834            for _ in 0..2 {
7835                state = RunState::load(&state.id).unwrap();
7836                assert!(resume_observed_head(&mut state, &head).await.is_err());
7837                let evidence = state.gate_repair_e2e.as_ref().unwrap();
7838                assert_eq!(evidence.head, head);
7839                assert!(!evidence.passed);
7840                assert!(!evidence.outcomes.is_empty());
7841                assert_eq!(
7842                    git::remote_head(&state.repo, "origin", "task-head")
7843                        .await
7844                        .unwrap(),
7845                    Some(head.clone())
7846                );
7847                assert!(state.land_sync_pending);
7848            }
7849        }
7850    }
7851
7852    async fn interrupt_landing_rebase(state: &mut RunState) {
7853        state.land_rebase_from = Some(git::rev_parse(&state.repo, "HEAD").await.unwrap());
7854        state.save().unwrap();
7855        let scratch = state.dir().join("rebase");
7856        assert_eq!(
7857            crate::rebase::rebase_with_fixer(state, &scratch, "winner", "origin/main")
7858                .await
7859                .unwrap(),
7860            crate::rebase::Rebased::Applied
7861        );
7862        assert!(!git::is_clean(&state.repo).await.unwrap());
7863    }
7864
7865    async fn landing_setup(state: &mut RunState) {
7866        git::git(
7867            &state.repo,
7868            &["config", "extensions.worktreeConfig", "true"],
7869        )
7870        .await
7871        .unwrap();
7872        state.config.worktree.setup =
7873            vec![toml::from_str("run = \"printf secret > .env\"").unwrap()];
7874        crate::worktree_setup::prepare(&state.config, &state.repo, &state.repo)
7875            .await
7876            .unwrap();
7877        state.config.verify.gate = vec!["test -f advance && test -f .env".into()];
7878    }
7879
7880    #[tokio::test]
7881    async fn landing_resume_restores_setup_after_both_fresh_and_interrupted_rebases() {
7882        for phase in 0..3 {
7883            let (_tmp, mut state, old) = landing_git_fixture().await;
7884            advance_landing_base(&state).await;
7885            landing_setup(&mut state).await;
7886            if phase > 0 {
7887                interrupt_landing_rebase(&mut state).await;
7888                if phase == 2 {
7889                    // Crash after clean removed setup products, before setup.
7890                    git::sync_to_head(&state.repo).await.unwrap();
7891                    assert!(!state.repo.join(".env").exists());
7892                }
7893                state = RunState::load(&state.id).unwrap();
7894            }
7895            let head = resume_observed_head(&mut state, &old).await.unwrap();
7896            assert_ne!(head, old);
7897            assert!(state.gate_allows_progress());
7898            assert!(state.land_rebase_from.is_none());
7899            assert_eq!(
7900                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
7901                "secret"
7902            );
7903            assert!(git::is_clean(&state.repo).await.unwrap());
7904            assert!(
7905                !git::git(&state.repo, &["ls-tree", "--name-only", "HEAD"])
7906                    .await
7907                    .unwrap()
7908                    .contains(".env")
7909            );
7910        }
7911    }
7912
7913    #[tokio::test]
7914    async fn landing_restoration_protects_ignored_files_outside_setup_products() {
7915        let (_tmp, mut state, _) = landing_git_fixture().await;
7916        advance_landing_base(&state).await;
7917        landing_setup(&mut state).await;
7918        interrupt_landing_rebase(&mut state).await;
7919        // Exercise unusual names without asking Windows to create an invalid
7920        // control-character filename. Unix also covers embedded newlines.
7921        let locals = [
7922            "local notes",
7923            #[cfg(unix)]
7924            "local\nnotes",
7925        ];
7926        let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
7927            .await
7928            .unwrap();
7929        std::fs::write(state.repo.join(excludes), "local*\n").unwrap();
7930        for local in locals {
7931            std::fs::write(state.repo.join(local), "keep these notes").unwrap();
7932            assert!(
7933                git::git_raw(&state.repo, &["check-ignore", "--quiet", local])
7934                    .await
7935                    .unwrap()
7936                    .ok()
7937            );
7938        }
7939        restore_landing_worktree(&mut state).await.unwrap();
7940        for local in locals {
7941            assert_eq!(
7942                std::fs::read_to_string(state.repo.join(local)).unwrap(),
7943                "keep these notes"
7944            );
7945        }
7946        assert_eq!(
7947            std::fs::read_to_string(state.repo.join(".env")).unwrap(),
7948            "secret"
7949        );
7950        assert!(git::is_clean(&state.repo).await.unwrap());
7951        assert!(state.land_rebase_from.is_none());
7952    }
7953
7954    #[tokio::test]
7955    async fn landing_restoration_rejects_ignored_paths_conflicting_with_the_new_tree() {
7956        for local in ["advance", "advance/notes", "new-directory"] {
7957            let (_tmp, mut state, _) = landing_git_fixture().await;
7958            advance_landing_base(&state).await;
7959            // Also cover a local file blocking a new tracked directory.
7960            git::git(&state.repo, &["checkout", "main"]).await.unwrap();
7961            std::fs::create_dir(state.repo.join("new-directory")).unwrap();
7962            std::fs::write(state.repo.join("new-directory/tracked"), "new").unwrap();
7963            git::git(&state.repo, &["add", "."]).await.unwrap();
7964            git::git(&state.repo, &["commit", "-m", "add directory"])
7965                .await
7966                .unwrap();
7967            git::git(&state.repo, &["push", "origin", "main"])
7968                .await
7969                .unwrap();
7970            git::git(&state.repo, &["checkout", "winner"])
7971                .await
7972                .unwrap();
7973            let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
7974                .await
7975                .unwrap();
7976            std::fs::write(state.repo.join(excludes), "advance\nnew-directory\n").unwrap();
7977            let path = state.repo.join(local);
7978            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
7979            std::fs::write(&path, "local notes").unwrap();
7980            interrupt_landing_rebase(&mut state).await;
7981            let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
7982            let checkpoint = state.land_rebase_from.clone();
7983            let error = restore_landing_worktree(&mut state).await.unwrap_err();
7984            assert!(
7985                error.to_string().contains("conflicting with HEAD"),
7986                "{error:#}"
7987            );
7988            assert_eq!(std::fs::read_to_string(&path).unwrap(), "local notes");
7989            assert_eq!(
7990                git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
7991                before
7992            );
7993            assert_eq!(state.land_rebase_from, checkpoint);
7994        }
7995    }
7996
7997    #[tokio::test]
7998    async fn landing_resume_preserves_ignored_gate_artifacts_without_setup() {
7999        for interrupted in [false, true] {
8000            let (_tmp, mut state, old) = landing_git_fixture().await;
8001            assert!(state.config.worktree.setup.is_empty());
8002            // A gate product exists before the base moves, without setup metadata.
8003            let excludes = git::git(&state.repo, &["rev-parse", "--git-path", "info/exclude"])
8004                .await
8005                .unwrap();
8006            std::fs::write(state.repo.join(excludes), "target/\n").unwrap();
8007            state.config.verify.gate =
8008                vec!["mkdir -p target && printf artifact > target/probe".into()];
8009            state.gate_ran = false;
8010            resume_observed_head(&mut state, &old).await.unwrap();
8011            assert_eq!(
8012                std::fs::read_to_string(state.repo.join("target/probe")).unwrap(),
8013                "artifact"
8014            );
8015            advance_landing_base(&state).await;
8016            if interrupted {
8017                interrupt_landing_rebase(&mut state).await;
8018                state = RunState::load(&state.id).unwrap();
8019            }
8020            state.config.verify.gate =
8021                vec!["test -f advance && test \"$(cat target/probe)\" = artifact".into()];
8022            let head = resume_observed_head(&mut state, &old).await.unwrap();
8023            assert_ne!(head, old);
8024            assert!(state.gate_allows_progress());
8025            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
8026            assert_eq!(
8027                std::fs::read_to_string(state.repo.join("target/probe")).unwrap(),
8028                "artifact"
8029            );
8030            assert!(state.land_rebase_from.is_none());
8031            assert_eq!(
8032                git::remote_head(&state.repo, "origin", "task-head")
8033                    .await
8034                    .unwrap(),
8035                Some(head.clone())
8036            );
8037            let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8038            land_with(&mut state, &green_pr().url, &forge)
8039                .await
8040                .unwrap();
8041            assert!(state.parked);
8042            assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8043            assert!(forge.argvs().is_empty());
8044        }
8045    }
8046
8047    #[tokio::test]
8048    #[cfg(unix)]
8049    async fn landing_restoration_waits_for_external_coordination_before_changing_files() {
8050        use std::os::fd::AsRawFd as _;
8051
8052        for interrupted in [false, true] {
8053            let (_tmp, mut state, _) = landing_git_fixture().await;
8054            advance_landing_base(&state).await;
8055            landing_setup(&mut state).await;
8056            if interrupted {
8057                interrupt_landing_rebase(&mut state).await;
8058            }
8059            state.config.worktree.setup =
8060                vec![toml::from_str("run = \"printf restored > .env\"").unwrap()];
8061            let common = crate::repo_lock::common_dir(&state.repo)
8062                .await
8063                .unwrap()
8064                .unwrap();
8065            std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
8066            state.config.coordination = crate::config::test_coordination();
8067            state.config.graph.timeout_resource_wait = 0;
8068            let external = std::fs::OpenOptions::new()
8069                .read(true)
8070                .write(true)
8071                .create(true)
8072                .truncate(false)
8073                .open(common.join("updater.lock"))
8074                .unwrap();
8075            // SAFETY: the descriptor belongs to `external` and remains open.
8076            let locked =
8077                unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
8078            assert_eq!(locked, 0);
8079            let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
8080            let checkpoint = state.land_rebase_from.clone();
8081            let error = restore_landing_worktree(&mut state).await.unwrap_err();
8082            assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8083            assert_eq!(
8084                git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
8085                before
8086            );
8087            assert_eq!(state.land_rebase_from, checkpoint);
8088            assert_eq!(
8089                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8090                "secret"
8091            );
8092
8093            drop(external);
8094            state.config.graph.timeout_resource_wait = 2;
8095            restore_landing_worktree(&mut state).await.unwrap();
8096            assert!(git::is_clean(&state.repo).await.unwrap());
8097            assert!(state.land_rebase_from.is_none());
8098            assert_eq!(
8099                std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8100                "restored"
8101            );
8102        }
8103    }
8104
8105    #[tokio::test]
8106    #[cfg(unix)]
8107    async fn landing_restoration_inherits_cancellation_while_waiting_for_a_local_seat() {
8108        use std::sync::atomic::{AtomicBool, Ordering};
8109
8110        let (_tmp, mut state, _) = landing_git_fixture().await;
8111        advance_landing_base(&state).await;
8112        landing_setup(&mut state).await;
8113        interrupt_landing_rebase(&mut state).await;
8114        let common = crate::repo_lock::common_dir(&state.repo)
8115            .await
8116            .unwrap()
8117            .unwrap();
8118        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
8119        state.config.coordination = crate::config::test_coordination();
8120        let holder = crate::repo_lock::SeatLease::for_checkout(
8121            &state.repo,
8122            true,
8123            state.config.coordination.as_ref(),
8124        )
8125        .await
8126        .unwrap();
8127        assert!(holder.is_some());
8128        let cancelled = Arc::new(AtomicBool::new(false));
8129        let signal = cancelled.clone();
8130        let wait = crate::repo_lock::WaitPolicy::new(Duration::from_secs(30), move || {
8131            signal.load(Ordering::SeqCst)
8132        });
8133        let before = git::git(&state.repo, &["diff", "HEAD"]).await.unwrap();
8134        let checkpoint = state.land_rebase_from.clone();
8135        let (result, ()) = tokio::join!(
8136            tokio::time::timeout(
8137                Duration::from_secs(2),
8138                wait.scope(restore_landing_worktree(&mut state)),
8139            ),
8140            async {
8141                tokio::time::sleep(Duration::from_millis(100)).await;
8142                cancelled.store(true, Ordering::SeqCst);
8143            }
8144        );
8145        let error = result
8146            .expect("cancellation must release the waiting driver")
8147            .unwrap_err();
8148        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8149        assert_eq!(
8150            git::git(&state.repo, &["diff", "HEAD"]).await.unwrap(),
8151            before
8152        );
8153        assert_eq!(state.land_rebase_from, checkpoint);
8154        assert_eq!(
8155            std::fs::read_to_string(state.repo.join(".env")).unwrap(),
8156            "secret"
8157        );
8158        drop(holder);
8159        restore_landing_worktree(&mut state).await.unwrap();
8160        assert!(state.land_rebase_from.is_none());
8161        assert!(git::is_clean(&state.repo).await.unwrap());
8162    }
8163
8164    #[tokio::test]
8165    #[cfg(unix)]
8166    async fn landing_verification_inherits_cancellation_while_waiting_for_a_local_seat() {
8167        use std::sync::atomic::{AtomicBool, Ordering};
8168
8169        for e2e in [false, true] {
8170            let (_tmp, mut state, head) = landing_git_fixture().await;
8171            let common = crate::repo_lock::common_dir(&state.repo)
8172                .await
8173                .unwrap()
8174                .unwrap();
8175            std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
8176            state.config.coordination = crate::config::test_coordination();
8177            if e2e {
8178                state.config.verify.e2e = vec!["true".into()];
8179                state.gate_repair_e2e = Some(crate::run::GateRepairE2e {
8180                    head: head.clone(),
8181                    passed: false,
8182                    outcomes: Vec::new(),
8183                });
8184            } else {
8185                state.config.verify.gate = vec!["true".into()];
8186                state.gate_ran = false;
8187            }
8188            let holder = crate::repo_lock::SeatLease::for_checkout(
8189                &state.repo,
8190                true,
8191                state.config.coordination.as_ref(),
8192            )
8193            .await
8194            .unwrap();
8195            assert!(holder.is_some());
8196            let cancelled = Arc::new(AtomicBool::new(false));
8197            let signal = cancelled.clone();
8198            let waiting = Arc::new(tokio::sync::Notify::new());
8199            let observed = waiting.clone();
8200            let wait = crate::repo_lock::WaitPolicy::new(Duration::from_secs(30), move || {
8201                observed.notify_one();
8202                signal.load(Ordering::SeqCst)
8203            });
8204            let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8205            let url = green_pr().url;
8206            let result = {
8207                let mut publishing =
8208                    Box::pin(wait.scope(publish_landing_head(&mut state, &head, &url, &forge)));
8209                // Git and fixture I/O precede local coordination. Start the
8210                // cancellation deadline only once the inherited wait policy
8211                // is polled, rather than timing those unrelated subprocesses.
8212                tokio::time::timeout(Duration::from_secs(30), async {
8213                    tokio::select! {
8214                        result = &mut publishing => panic!(
8215                            "verification must wait behind the held seat: {result:?}"
8216                        ),
8217                        () = waiting.notified() => {}
8218                    }
8219                })
8220                .await
8221                .expect("verification must reach the inherited coordination wait");
8222                cancelled.store(true, Ordering::SeqCst);
8223                tokio::time::timeout(Duration::from_secs(2), publishing).await
8224            };
8225            let error = result
8226                .expect("cancellation must release the verification waiter")
8227                .unwrap_err();
8228            assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
8229            assert!(error.to_string().contains("cancelled"), "{error:#}");
8230            assert!(forge.argvs().is_empty());
8231            assert_eq!(
8232                git::remote_head(&state.repo, "origin", "task-head")
8233                    .await
8234                    .unwrap(),
8235                Some(head.clone())
8236            );
8237            drop(holder);
8238            // Cancellation must release its reservation so another attempt can verify.
8239            assert_eq!(
8240                publish_landing_head(&mut state, &head, &url, &forge)
8241                    .await
8242                    .unwrap(),
8243                head
8244            );
8245        }
8246    }
8247
8248    #[tokio::test]
8249    async fn landing_resume_preserves_user_edits_after_an_interrupted_rebase() {
8250        for staged in [false, true] {
8251            let (_tmp, mut state, old) = landing_git_fixture().await;
8252            advance_landing_base(&state).await;
8253            interrupt_landing_rebase(&mut state).await;
8254            std::fs::write(state.repo.join("change"), "user edit").unwrap();
8255            if staged {
8256                git::git(&state.repo, &["add", "change"]).await.unwrap();
8257            }
8258            assert!(resume_observed_head(&mut state, &old).await.is_err());
8259            assert_eq!(
8260                std::fs::read_to_string(state.repo.join("change")).unwrap(),
8261                "user edit"
8262            );
8263            assert_eq!(
8264                git::remote_head(&state.repo, "origin", "task-head")
8265                    .await
8266                    .unwrap(),
8267                Some(old)
8268            );
8269        }
8270    }
8271
8272    #[tokio::test]
8273    async fn landing_resume_returns_to_approval_wait_and_closed_pr_skips_sync() {
8274        let (_tmp, mut state, head) = landing_git_fixture().await;
8275        let forge = Scripted::new(vec![seen(&head, Checks::Green, "CLEAN", false)], vec![]);
8276        let id = state.id.clone();
8277        let pr = land_with(&mut state, &green_pr().url, &forge)
8278            .await
8279            .unwrap();
8280        assert_eq!(pr.state, PrLifecycle::Open);
8281        assert_eq!(state.id, id);
8282        assert!(state.parked);
8283        assert_eq!(state.status, RunStatus::Landing);
8284        assert_eq!(state.land_approval.as_ref().unwrap().head, head);
8285        assert!(forge.argvs().is_empty());
8286
8287        state.land_sync_pending = true;
8288        std::fs::write(state.repo.join("dirty"), "do not touch").unwrap();
8289        let mut closed = seen("foreign", Checks::Green, "CLEAN", false);
8290        closed.pr.state = PrLifecycle::Closed;
8291        let forge = Scripted::new(vec![closed], vec![]);
8292        assert_eq!(
8293            land_with(&mut state, &green_pr().url, &forge)
8294                .await
8295                .unwrap()
8296                .state,
8297            PrLifecycle::Closed
8298        );
8299        assert_eq!(
8300            std::fs::read_to_string(state.repo.join("dirty")).unwrap(),
8301            "do not touch"
8302        );
8303        assert!(forge.argvs().is_empty());
8304    }
8305
8306    #[tokio::test]
8307    async fn landing_resume_does_not_publish_a_failed_rebased_gate() {
8308        let (_tmp, mut state, old) = landing_git_fixture().await;
8309        advance_landing_base(&state).await;
8310        state.config.verify.gate = vec!["exit 1".into()];
8311        assert!(resume_observed_head(&mut state, &old).await.is_err());
8312        assert_ne!(state.gate_head.as_deref(), Some(old.as_str()));
8313        assert!(!state.gate_allows_progress());
8314        assert_eq!(
8315            git::remote_head(&state.repo, "origin", "task-head")
8316                .await
8317                .unwrap(),
8318            Some(old)
8319        );
8320        assert!(state.land_sync_pending);
8321    }
8322
8323    #[tokio::test]
8324    async fn landing_publication_recovers_a_push_before_save_and_refuses_a_lease_conflict() {
8325        let (_tmp, mut state, old) = landing_git_fixture().await;
8326        advance_landing_base(&state).await;
8327        let pushed = resume_observed_head(&mut state, &old).await.unwrap();
8328        // Model a crash after the push but before saving its published SHA.
8329        state.pr_pushed_head = Some(old.clone());
8330        state.land_sync_pending = true;
8331        assert_eq!(
8332            resume_observed_head(&mut state, &pushed).await.unwrap(),
8333            pushed
8334        );
8335        // A writer races the observed PR snapshot: the explicit remote lease
8336        // must reject the push even though preflight saw our expected head.
8337        git::git(
8338            &state.repo,
8339            &["push", "--force", "origin", "main:refs/heads/task-head"],
8340        )
8341        .await
8342        .unwrap();
8343        assert!(
8344            publish_landing_head(
8345                &mut state,
8346                &pushed,
8347                &green_pr().url,
8348                &Scripted::new(vec![seen(&pushed, Checks::Green, "CLEAN", false)], vec![])
8349            )
8350            .await
8351            .unwrap_err()
8352            .to_string()
8353            .contains("publishing gated")
8354        );
8355        assert!(
8356            resume_observed_head(&mut state, "foreign-head")
8357                .await
8358                .is_err()
8359        );
8360    }
8361    #[tokio::test]
8362    async fn landing_publication_refuses_a_pr_closed_during_gate() {
8363        let (_tmp, mut state, head) = landing_git_fixture().await;
8364        let mut closed = seen(&head, Checks::Green, "CLEAN", false);
8365        closed.pr.state = PrLifecycle::Closed;
8366        let forge = Scripted::new(vec![closed], vec![]);
8367        assert!(
8368            publish_landing_head(&mut state, &head, &green_pr().url, &forge)
8369                .await
8370                .unwrap_err()
8371                .to_string()
8372                .contains("PR closed or merged")
8373        );
8374    }
8375
8376    /// A candidate selected by the uncontested tally.
8377    fn winning_candidate(summary: &str) -> Candidate {
8378        Candidate {
8379            index: 0,
8380            label: 'A',
8381            agent: "opus".to_owned(),
8382            branch: "magi/x/A".to_owned(),
8383            worktree: PathBuf::from("/wt/A"),
8384            summary: summary.to_owned(),
8385            stat: String::new(),
8386            files: 1,
8387            commits: 1,
8388            empty: false,
8389            failed: None,
8390            verified_noop: None,
8391            duration_ms: 0,
8392            folded: false,
8393        }
8394    }
8395
8396    fn uncontested_tally() -> Tally {
8397        Tally {
8398            first_choice: BTreeMap::from([('A', 1)]),
8399            borda: BTreeMap::new(),
8400            winner: 'A',
8401            rankings: 1,
8402            unanimous_initial: true,
8403            deliberated: false,
8404            changed_votes: 0,
8405            unanimous_final: true,
8406            tie_break: None,
8407            judges: 1,
8408            present: 1,
8409            quorum: 1,
8410            met_quorum: true,
8411            uncontested: None,
8412        }
8413    }
8414
8415    fn review_record(reviewer: usize, agent: &str, summary: &str) -> ReviewRecord {
8416        ReviewRecord {
8417            attempts: 0,
8418            reviewer,
8419            agent: agent.to_owned(),
8420            summary: summary.to_owned(),
8421            findings: Vec::new(),
8422            vote: None,
8423            failed: None,
8424            duration_ms: 0,
8425        }
8426    }
8427
8428    fn review_round(round: usize, reviews: Vec<ReviewRecord>) -> ReviewRound {
8429        let answered = reviews.len();
8430        ReviewRound {
8431            round,
8432            head: "abc1234".to_owned(),
8433            verified_head: None,
8434            verified_at: None,
8435            reviews,
8436            e2e: Vec::new(),
8437            verify_retried: false,
8438            e2e_deferred: false,
8439            e2e_defer_reason: None,
8440            fix: None,
8441            blocking: 0,
8442            answered,
8443            expected: answered,
8444            clean: true,
8445            progressed: false,
8446            vote_split: false,
8447            reconsideration: Vec::new(),
8448            verdict: None,
8449        }
8450    }
8451
8452    #[test]
8453    fn the_approval_panel_states_the_task_verbatim_in_either_language() {
8454        let en = panel();
8455        assert!(en.contains("Task"), "{en}");
8456        assert!(en.contains("add retries to the uploader"), "{en}");
8457
8458        let mut state = run_state();
8459        state.config.graph.language = "ja".to_owned();
8460        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8461        assert!(ja.contains("タスク"), "{ja}");
8462        assert!(
8463            ja.contains("add retries to the uploader"),
8464            "the task itself is not translated: {ja}"
8465        );
8466    }
8467
8468    #[test]
8469    fn the_approval_panel_omits_what_changed_and_review_verdict_with_no_data() {
8470        // `run_state()` has no candidates, no tally and no reviews - exactly
8471        // the shape a run has before anything has judged or reviewed it, and
8472        // the panel must not print an empty box for either.
8473        let html = panel();
8474        assert!(!html.contains("What changed"), "{html}");
8475        assert!(!html.contains("Review verdict"), "{html}");
8476    }
8477
8478    #[test]
8479    fn the_approval_panel_omits_what_changed_when_the_winners_summary_is_empty() {
8480        let mut state = run_state();
8481        state.candidates = vec![winning_candidate("")];
8482        state.tally = Some(uncontested_tally());
8483        let html = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8484        assert!(
8485            !html.contains("What changed"),
8486            "an empty summary must not render an empty box: {html}"
8487        );
8488    }
8489
8490    #[test]
8491    fn the_approval_panel_shows_the_winners_own_account_in_either_language() {
8492        let mut state = run_state();
8493        state.candidates = vec![winning_candidate(
8494            "Added a retry loop around the uploader PUT call.",
8495        )];
8496        state.tally = Some(uncontested_tally());
8497        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8498        assert!(en.contains("What changed"), "{en}");
8499        assert!(
8500            en.contains("Added a retry loop around the uploader PUT call."),
8501            "{en}"
8502        );
8503
8504        state.config.graph.language = "ja".to_owned();
8505        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8506        assert!(ja.contains("変更内容"), "{ja}");
8507        assert!(
8508            ja.contains("Added a retry loop around the uploader PUT call."),
8509            "{ja}"
8510        );
8511    }
8512
8513    #[test]
8514    fn the_approval_panel_shows_only_the_last_review_rounds_verdict() {
8515        let mut state = run_state();
8516        state.reviews = vec![
8517            review_round(
8518                1,
8519                vec![review_record(1, "alpha", "found a race, sent back")],
8520            ),
8521            review_round(2, vec![review_record(1, "alpha", "race is fixed, clean")]),
8522        ];
8523        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8524        assert!(en.contains("Review verdict"), "{en}");
8525        assert!(en.contains("race is fixed, clean"), "{en}");
8526        assert!(
8527            !en.contains("found a race, sent back"),
8528            "only the round that actually cleared the merge should show: {en}"
8529        );
8530
8531        state.config.graph.language = "ja".to_owned();
8532        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8533        assert!(ja.contains("レビューの結論"), "{ja}");
8534        assert!(ja.contains("レビュアー"), "{ja}");
8535        assert!(ja.contains("race is fixed, clean"), "{ja}");
8536    }
8537
8538    /// The `incomplete_review = "warn"` policy (see
8539    /// `graph::Runner::review_loop`) can push a `clean` round to
8540    /// `state.reviews` while one seat's own record still has `failed: Some`
8541    /// and an empty `summary` - a seat that never answered, not one that
8542    /// answered with nothing to say.
8543    fn unanswered_review_record(reviewer: usize, agent: &str, reason: &str) -> ReviewRecord {
8544        ReviewRecord {
8545            attempts: 0,
8546            reviewer,
8547            agent: agent.to_owned(),
8548            summary: String::new(),
8549            findings: Vec::new(),
8550            vote: None,
8551            failed: Some(reason.to_owned()),
8552            duration_ms: 0,
8553        }
8554    }
8555
8556    #[test]
8557    fn the_approval_panel_never_shows_an_unanswered_seat_as_a_blank_verdict() {
8558        let mut state = run_state();
8559        state.reviews = vec![review_round(
8560            1,
8561            vec![
8562                review_record(1, "alpha", "clean, nothing to add"),
8563                unanswered_review_record(2, "beta", "timed out"),
8564            ],
8565        )];
8566        let en = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8567        assert!(en.contains("clean, nothing to add"), "{en}");
8568        assert!(
8569            en.contains("produced no answer: timed out"),
8570            "a seat that never answered must say so, not render a blank box: {en}"
8571        );
8572        assert!(
8573            !en.contains("<div style=\"white-space:pre-wrap;font-size:13px\"></div>"),
8574            "no reviewer box may be left empty: {en}"
8575        );
8576
8577        state.config.graph.language = "ja".to_owned();
8578        let ja = approval_panel(&state, &green_pr(), NUMSTAT, "", &[], "feat: x");
8579        assert!(ja.contains("回答なし: timed out"), "{ja}");
8580    }
8581
8582    #[test]
8583    fn the_approval_panel_contains_nothing_the_frames_policy_would_block() {
8584        let html = panel();
8585        assert!(!html.contains("<script"), "no script survives the csp");
8586        assert!(!html.contains("<form"), "form-action is 'none'");
8587        let pr = green_pr();
8588        assert_eq!(
8589            html.matches("http").count(),
8590            html.matches(pr.url.as_str()).count(),
8591            "the only http url in the panel is the pull request's own link"
8592        );
8593        assert!(
8594            html.contains("target=\"_blank\""),
8595            "the PR link must open in a new tab so it escapes the iframe"
8596        );
8597        assert!(
8598            html.contains("rel=\"noopener noreferrer\""),
8599            "external links opening in new tabs must carry noopener noreferrer"
8600        );
8601    }
8602
8603    #[test]
8604    fn added_and_removed_diff_lines_are_distinguishable_without_colour() {
8605        let html = panel();
8606        assert!(
8607            html.contains(">+</span>"),
8608            "an added line carries a `+` in the gutter, not only a background"
8609        );
8610        assert!(
8611            html.contains(">-</span>"),
8612            "a removed line carries a `-` in the gutter, not only a background"
8613        );
8614        assert!(
8615            html.contains(">new line</span>"),
8616            "the marker is moved to the gutter, so the body is printed once without it"
8617        );
8618    }
8619
8620    #[test]
8621    fn a_diff_past_the_threshold_is_cut_with_an_honest_count() {
8622        let total = DIFF_MAX_LINES + 100;
8623        let diff: String = (0..total).map(|i| format!("+line {i}\n")).collect();
8624        let html = approval_panel(
8625            &run_state(),
8626            &green_pr(),
8627            NUMSTAT,
8628            &diff,
8629            &[],
8630            "feat: something long",
8631        );
8632        assert!(
8633            html.contains(&format!("100 of {total} diff lines omitted")),
8634            "the note must say exactly how much was cut"
8635        );
8636        assert!(html.contains(&format!("line {}", DIFF_MAX_LINES - 1)));
8637        assert!(
8638            !html.contains(&format!("line {DIFF_MAX_LINES}")),
8639            "nothing past the threshold is rendered"
8640        );
8641        assert!(
8642            html.contains("/repo/magi"),
8643            "the note says where the rest is"
8644        );
8645    }
8646
8647    #[test]
8648    fn a_path_with_html_metacharacters_is_escaped_rather_than_rendered() {
8649        let html = approval_panel(
8650            &run_state(),
8651            &green_pr(),
8652            "1\t2\tsrc/<b>&\"x\"'.rs",
8653            "",
8654            &[],
8655            "subject",
8656        );
8657        assert!(html.contains("src/&lt;b&gt;&amp;&quot;x&quot;&#39;.rs"));
8658        assert!(
8659            !html.contains("<b>"),
8660            "an agent-influenced path must never become markup"
8661        );
8662    }
8663
8664    #[tokio::test]
8665    async fn the_merge_lock_serialises_one_repository_but_never_a_different_one() {
8666        let a = std::path::PathBuf::from("/repo/a");
8667        let b = std::path::PathBuf::from("/repo/b");
8668
8669        let held = repo_merge_lock(&a).lock_owned().await;
8670
8671        // A second, concurrent land run against the *same* repository must
8672        // wait - `try_lock` fails while `held` is alive.
8673        assert!(
8674            repo_merge_lock(&a).try_lock().is_err(),
8675            "a second merge into the same repository must not proceed concurrently"
8676        );
8677
8678        // A run against a *different* repository must not be blocked by it -
8679        // this is what keeps a slow rebase or `gh pr merge` in one
8680        // repository from also stalling a land-approval resume in another.
8681        assert!(
8682            repo_merge_lock(&b).try_lock().is_ok(),
8683            "a different repository's merge lock must be independent"
8684        );
8685
8686        drop(held);
8687        assert!(
8688            repo_merge_lock(&a).try_lock().is_ok(),
8689            "the lock is released once the holder is done"
8690        );
8691    }
8692
8693    pub(crate) fn repair_state(major: bool, reject: bool) -> RunState {
8694        let mut state = landing_state();
8695        let mut rec = review_record(1, "alpha", "precise rejection reason");
8696        rec.vote = Some(if reject {
8697            crate::verdict::ReviewVote::Reject
8698        } else {
8699            crate::verdict::ReviewVote::Approve
8700        });
8701        if major {
8702            rec.findings = contested().findings;
8703        }
8704        let mut round = review_round(1, vec![rec]);
8705        round.clean = false;
8706        round.blocking = usize::from(major);
8707        state.reviews.push(round);
8708        state.config.graph.review_rounds = 1;
8709        state
8710    }
8711
8712    #[test]
8713    fn approval_policy_controls_are_independent_and_keep_all_reasons() {
8714        for every in [false, true] {
8715            for contested in [false, true] {
8716                for major in [false, true] {
8717                    for reject in [false, true] {
8718                        let mut state = repair_state(major, reject);
8719                        state.config.graph.land_approval = every;
8720                        state.config.graph.hold_contested_merge = contested;
8721                        let reasons = approval_reasons(&state);
8722                        assert_eq!(reasons.contains(&ApprovalReason::EveryMerge), every);
8723                        assert_eq!(
8724                            reasons.contains(&ApprovalReason::OpenBlockingFindings),
8725                            contested && major
8726                        );
8727                        assert_eq!(
8728                            reasons.contains(&ApprovalReason::FinalReject),
8729                            contested && reject
8730                        );
8731                        assert_eq!(
8732                            reasons.len(),
8733                            usize::from(every)
8734                                + usize::from(contested && major)
8735                                + usize::from(contested && reject)
8736                        );
8737                    }
8738                }
8739            }
8740        }
8741    }
8742
8743    #[test]
8744    fn approval_policy_and_rendering_follow_reconsideration_in_both_directions() {
8745        use crate::verdict::ReviewVote::{Approve, Reject};
8746        for (initial_reject, final_vote) in [(true, Approve), (false, Reject)] {
8747            let mut state = repair_state(false, initial_reject);
8748            state.reviews[0]
8749                .reconsideration
8750                .push(crate::run::ReviewRevoteRecord {
8751                    reviewer: 1,
8752                    agent: "alpha".into(),
8753                    vote: Some(final_vote),
8754                    reason: "changed after reading the panel <evidence>".into(),
8755                    failed: None,
8756                });
8757            assert_eq!(
8758                approval_reasons(&state).contains(&ApprovalReason::FinalReject),
8759                final_vote == Reject
8760            );
8761            for language in ["en", "ja"] {
8762                state.config.graph.language = language.into();
8763                let evidence = approval_evidence(&state);
8764                assert!(evidence.contains(&format!("→ {}", final_vote.label())));
8765                assert!(evidence.contains("changed after reading the panel <evidence>"));
8766                let html = approval_panel(&state, &green_pr(), "", "", &[], "subject");
8767                assert!(html.contains("changed after reading the panel &lt;evidence&gt;"));
8768                assert!(!html.contains("<evidence>"));
8769            }
8770            state.reviews[0].reconsideration[0].vote = None;
8771            state.reviews[0].reconsideration[0].failed = Some("timed out".into());
8772            assert_eq!(
8773                approval_reasons(&state).contains(&ApprovalReason::FinalReject),
8774                initial_reject
8775            );
8776            assert!(approval_evidence(&state).contains("timed out"));
8777        }
8778    }
8779
8780    #[tokio::test]
8781    async fn approval_merge_paths_apply_controls_to_major_and_reject_independently() {
8782        for every in [false, true] {
8783            for contested in [false, true] {
8784                for (major, reject) in [(false, false), (false, true), (true, false), (true, true)]
8785                {
8786                    let mut state = repair_state(major, reject);
8787                    state.config.graph.land_approval = every;
8788                    state.config.graph.hold_contested_merge = contested;
8789                    let forge = Scripted::new(
8790                        vec![seen("abc", Checks::Green, "CLEAN", false)],
8791                        vec![(true, "")],
8792                    );
8793                    land_with(&mut state, URL, &forge).await.unwrap();
8794                    let expected = every || (contested && (major || reject));
8795                    assert_eq!(state.land_approval.is_some(), expected);
8796                    assert_eq!(forge.calls().contains(&"merge"), !expected);
8797                    if expected {
8798                        assert!(state.parked);
8799                    }
8800                }
8801            }
8802        }
8803    }
8804
8805    #[tokio::test]
8806    async fn reviewed_branch_hold_is_read_before_landing_decision() {
8807        for (base, control) in [
8808            (false, "land_approval"),
8809            (true, "land_approval"),
8810            (false, "hold_contested_merge"),
8811        ] {
8812            let (_tmp, mut state, _) = landing_git_fixture().await;
8813            state.config.graph.land_approval = base;
8814            state.config.graph.hold_contested_merge = false;
8815            state.reviewed_commits = Some(Vec::new());
8816            if control == "hold_contested_merge" {
8817                state.reviews = repair_state(false, true).reviews;
8818            }
8819            std::fs::write(
8820                state.repo.join("magi.toml"),
8821                format!("[graph]\n{control} = {}\n", !base),
8822            )
8823            .unwrap();
8824            git::git(&state.repo, &["add", "magi.toml"]).await.unwrap();
8825            git::git(&state.repo, &["commit", "-m", "approval policy"])
8826                .await
8827                .unwrap();
8828            let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8829            state.land_sync_pending = false;
8830            state.pr_pushed_head = Some(head.clone());
8831            state.gate_head = Some(head.clone());
8832            let forge = Scripted::new(
8833                vec![seen(&head, Checks::Green, "CLEAN", false)],
8834                vec![(true, "")],
8835            );
8836            land_with(&mut state, URL, &forge).await.unwrap();
8837            assert!(
8838                state.land_approval.is_some(),
8839                "base={base}, control={control}"
8840            );
8841            assert!(!forge.calls().contains(&"merge"));
8842            if !base {
8843                let question = ask::Questions::open()
8844                    .get(&state.land_approval.as_ref().unwrap().question)
8845                    .unwrap();
8846                assert!(question.detail.contains(&format!(
8847                    "{control}=true from the reviewed branch's magi.toml"
8848                )));
8849            }
8850        }
8851    }
8852
8853    #[tokio::test]
8854    async fn reviewed_branch_hold_asks_and_survives_removal_and_resume() {
8855        for file in ["magi.toml", ".magi/config.toml"] {
8856            for control in crate::config::OwnerHold::ALL {
8857                let (_tmp, mut state, _) = landing_git_fixture().await;
8858                state.config.graph.land_approval = false;
8859                state.config.graph.hold_contested_merge = false;
8860                state.reviewed_commits = Some(Vec::new());
8861                if control == crate::config::OwnerHold::HoldContestedMerge {
8862                    state.reviews = repair_state(false, true).reviews;
8863                }
8864                let config = state.repo.join(file);
8865                std::fs::create_dir_all(config.parent().unwrap()).unwrap();
8866                std::fs::write(
8867                    &config,
8868                    format!(
8869                        "[graph]\n{} = true\n[verify]\ngate = ['untrusted']\n",
8870                        control.key()
8871                    ),
8872                )
8873                .unwrap();
8874                git::git(&state.repo, &["add", file]).await.unwrap();
8875                git::git(&state.repo, &["commit", "-m", "require approval"])
8876                    .await
8877                    .unwrap();
8878                let head = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8879                let gate = state.config.verify.gate.clone();
8880                state.observe_branch_owner_holds(&head).await;
8881                assert_eq!(state.config.verify.gate, gate);
8882                assert!(state.owner_hold(control));
8883                let holds = state.branch_owner_holds.clone();
8884                git::git(&state.repo, &["rm", file]).await.unwrap();
8885                git::git(&state.repo, &["commit", "-m", "remove config"])
8886                    .await
8887                    .unwrap();
8888                let later = git::rev_parse(&state.repo, "HEAD").await.unwrap();
8889                state.save().unwrap();
8890                state = RunState::load(&state.id).unwrap();
8891                state.observe_branch_owner_holds(&later).await;
8892                assert_eq!(state.branch_owner_holds, holds);
8893                assert_eq!(state.branch_owner_holds[0].head, head);
8894                state.land_sync_pending = false;
8895                state.pr_pushed_head = Some(later.clone());
8896                state.gate_head = Some(later.clone());
8897                let forge = Scripted::new(
8898                    vec![seen(&later, Checks::Green, "CLEAN", false)],
8899                    vec![(true, "")],
8900                );
8901                land_with(&mut state, URL, &forge).await.unwrap();
8902                assert!(!forge.calls().contains(&"merge"));
8903                assert!(state.parked);
8904                let question = ask::Questions::open()
8905                    .get(&state.land_approval.as_ref().unwrap().question)
8906                    .unwrap();
8907                assert!(question.detail.contains("Approval required because:"));
8908                assert!(question.detail.contains(&format!(
8909                    "{}=true from the reviewed branch's {file}",
8910                    control.key()
8911                )));
8912                assert_eq!(state.branch_owner_holds, holds);
8913                state.save().unwrap();
8914                let resumed = RunState::load(&state.id).unwrap();
8915                assert!(resumed.owner_hold(control));
8916                assert_eq!(resumed.branch_owner_holds, holds);
8917                assert_eq!(
8918                    resumed.land_approval.unwrap().question,
8919                    state.land_approval.unwrap().question
8920                );
8921            }
8922        }
8923    }
8924
8925    #[tokio::test]
8926    async fn approval_snapshot_exposes_minor_findings_and_survives_disabled_controls() {
8927        let mut state = repair_state(false, true);
8928        state.reviews[0].clean = true;
8929        let mut finding = contested().findings.remove(0);
8930        finding.severity = crate::verdict::Severity::Minor;
8931        state.reviews[0].reviews[0].findings.push(finding);
8932        assert!(state.open_findings().is_empty());
8933        let mut pr = green_pr();
8934        pr.review_comments.clear();
8935        for language in ["en", "ja"] {
8936            state.config.graph.language = language.into();
8937            let html = approval_panel(&state, &pr, "", "", &[], "subject");
8938            assert!(html.contains("[R3-1-1] minor"));
8939            assert!(html.contains(if language == "ja" {
8940                "内部指摘の解決を意味するものではありません"
8941            } else {
8942                "This does not mean internal findings are resolved"
8943            }));
8944            assert!(
8945                html.find(if language == "ja" {
8946                    "承認が必要な理由:"
8947                } else {
8948                    "Approval required because:"
8949                })
8950                .unwrap()
8951                    < html.find("[R3-1-1]").unwrap()
8952            );
8953        }
8954        state.config.graph.language = "en".into();
8955        let observed = seen("abc", Checks::Green, "CLEAN", false);
8956        assert_eq!(
8957            approval_gate(&mut state, &observed.pr, "subject", None, "abc")
8958                .await
8959                .unwrap(),
8960            ApprovalGate::Pending
8961        );
8962        let id = state.land_approval.as_ref().unwrap().question.clone();
8963        let q = ask::Questions::open().get(&id).unwrap();
8964        assert!(q.detail.starts_with("Approval required because:"));
8965        assert!(q.detail.contains("final reviewer reject"));
8966        assert!(q.detail.contains("[R3-1-1] minor"));
8967        assert!(
8968            q.detail
8969                .contains("No adoption or resolution evidence recorded")
8970        );
8971        state.config.graph.land_approval = false;
8972        state.config.graph.hold_contested_merge = false;
8973        state.reviews.clear();
8974        assert_eq!(approval_reasons(&state), [ApprovalReason::ExistingDecision]);
8975        assert!(deputy_brief(&q, Some(&state)).contains("final reviewer reject"));
8976        assert!(deputy_brief(&q, None).contains("[R3-1-1] minor"));
8977        let forge = Scripted::new(vec![observed], vec![]);
8978        land_with(&mut state, URL, &forge).await.unwrap();
8979        assert!(!forge.calls().contains(&"merge"));
8980        assert_eq!(state.land_approval.as_ref().unwrap().question, id);
8981        assert_eq!(ask::Questions::open().get(&id).unwrap().detail, q.detail);
8982    }
8983
8984    #[tokio::test]
8985    async fn approval_evidence_keeps_all_findings_and_bounds_unicode_prose() {
8986        let mut state = repair_state(false, true);
8987        state.config.graph.land_approval = false;
8988        let long_reason = format!("{}REASON_TAIL", "拒否🦀".repeat(200));
8989        let long_detail = format!("{}DETAIL_TAIL", "詳細🦀".repeat(200));
8990        let long_title = format!("{}TITLE_TAIL", "題🦀".repeat(100));
8991        state.reviews[0].reviews[0].summary = long_reason.clone();
8992        for i in 1..=10 {
8993            let mut finding = contested().findings.remove(0);
8994            finding.id = format!("R1-1-{i}");
8995            finding.severity = if i == 9 {
8996                crate::verdict::Severity::Major
8997            } else {
8998                crate::verdict::Severity::Minor
8999            };
9000            finding.title = long_title.clone();
9001            finding.detail = long_detail.clone();
9002            state.reviews[0].reviews[0].findings.push(finding);
9003        }
9004        state.reviews[0].fix = Some(crate::run::FixRecord {
9005            agent: "fixer".into(),
9006            addressed: vec!["R1-1-9".into()],
9007            rejected: vec![crate::verdict::Rejection {
9008                id: "R1-1-10".into(),
9009                why: long_reason.clone(),
9010            }],
9011            notes: long_detail.clone(),
9012            committed: false,
9013            failed: None,
9014            duration_ms: 0,
9015            continuation: None,
9016        });
9017        assert_eq!(
9018            approval_reasons(&state),
9019            [
9020                ApprovalReason::OpenBlockingFindings,
9021                ApprovalReason::FinalReject
9022            ]
9023        );
9024        let excerpt = approval_excerpt(&long_reason, 300);
9025        assert_eq!(excerpt.chars().count(), 300);
9026        assert!(excerpt.ends_with('…'));
9027        let boundary = "拒".repeat(300);
9028        assert_eq!(approval_excerpt(&boundary, 300), boundary);
9029        for language in ["en", "ja"] {
9030            state.config.graph.language = language.into();
9031            for revote in [
9032                None,
9033                Some(crate::verdict::ReviewVote::Reject),
9034                Some(crate::verdict::ReviewVote::Approve),
9035            ] {
9036                state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Reject);
9037                state.reviews[0].reconsideration.clear();
9038                if let Some(vote) = revote {
9039                    state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Approve);
9040                    state.reviews[0]
9041                        .reconsideration
9042                        .push(crate::run::ReviewRevoteRecord {
9043                            reviewer: 1,
9044                            agent: "alpha".into(),
9045                            vote: Some(vote),
9046                            reason: long_reason.clone(),
9047                            failed: None,
9048                        });
9049                }
9050                let evidence = approval_evidence(&state);
9051                let final_vote = revote.unwrap_or(crate::verdict::ReviewVote::Reject);
9052                assert!(evidence.contains(&format!("#1 (alpha): {}", final_vote.label())));
9053                assert!(approval_reasons(&state).contains(&ApprovalReason::OpenBlockingFindings));
9054                assert_eq!(
9055                    approval_reasons(&state).contains(&ApprovalReason::FinalReject),
9056                    final_vote == crate::verdict::ReviewVote::Reject
9057                );
9058                assert!(evidence.contains(&excerpt));
9059                assert!(evidence.contains("[R1-1-8] minor"));
9060                assert!(evidence.contains("[R1-1-9] major"));
9061                assert!(evidence.contains("[R1-1-10] minor"));
9062                for tail in ["REASON_TAIL", "DETAIL_TAIL", "TITLE_TAIL"] {
9063                    assert!(!evidence.contains(tail));
9064                }
9065                assert!(evidence.contains(if language == "ja" {
9066                    "採用申告(解決未確認)"
9067                } else {
9068                    "claimed addressed (resolution unconfirmed)"
9069                }));
9070                assert!(evidence.contains(if language == "ja" {
9071                    "不採用理由"
9072                } else {
9073                    "declined"
9074                }));
9075                let major_evidence = evidence
9076                    .split("[R1-1-9] major")
9077                    .nth(1)
9078                    .unwrap()
9079                    .split("[R1-1-10]")
9080                    .next()
9081                    .unwrap();
9082                assert!(major_evidence.contains(if language == "ja" {
9083                    "採用申告(解決未確認)"
9084                } else {
9085                    "claimed addressed (resolution unconfirmed)"
9086                }));
9087                let last_evidence = evidence.split("[R1-1-10] minor").nth(1).unwrap();
9088                assert!(last_evidence.contains(if language == "ja" {
9089                    "不採用理由"
9090                } else {
9091                    "declined"
9092                }));
9093                let html = approval_panel(&state, &green_pr(), "", "", &[], "subject");
9094                assert!(html.contains(&esc(&evidence)));
9095                assert_eq!(
9096                    approval_gate(&mut state, &green_pr(), "subject", None, "abc")
9097                        .await
9098                        .unwrap(),
9099                    ApprovalGate::Pending
9100                );
9101                let id = &state.land_approval.take().unwrap().question;
9102                let q = ask::Questions::open().get(id).unwrap();
9103                assert!(q.detail.starts_with(&evidence));
9104            }
9105            state.reviews[0].reviews[0].vote = Some(crate::verdict::ReviewVote::Reject);
9106        }
9107    }
9108
9109    #[test]
9110    fn merge_repair_choice_covers_major_only_and_reject_only_without_contested_and() {
9111        for (major, reject) in [(true, false), (false, true), (true, true)] {
9112            let state = repair_state(major, reject);
9113            assert!(repair_available(&state));
9114            assert_eq!(&approval_choices(&state)[..3], [APPROVE, HOLD, REPAIR]);
9115        }
9116        assert!(!repair_available(&repair_state(false, false)));
9117        let mut clean = repair_state(true, false);
9118        clean.reviews[0].clean = true;
9119        assert_eq!(&approval_choices(&clean)[..3], [APPROVE, HOLD, REPAIR]);
9120        assert_eq!(approval(Some(REPAIR)), Approval::Repair);
9121    }
9122
9123    #[tokio::test]
9124    async fn merge_repair_upgrades_legacy_questions_and_snapshots_exact_evidence_once() {
9125        let mut state = repair_state(true, false);
9126        let pr = green_pr();
9127        approval_gate(&mut state, &pr, "feat: x", None, "abc")
9128            .await
9129            .unwrap();
9130        let store = ask::Questions::open();
9131        let id = state.land_approval.as_ref().unwrap().question.clone();
9132        // Simulate an unanswered two-choice question created by an older build.
9133        store
9134            .update(&id, |q| {
9135                q.choices = vec![APPROVE.into(), HOLD.into()];
9136                Ok(())
9137            })
9138            .unwrap();
9139        let upgraded = store.get(&id).unwrap();
9140        assert_eq!(upgraded.choices, approval_choices(&state));
9141        assert!(!upgraded.actions.contains_key(HOLD));
9142        assert_eq!(store.get(&id).unwrap().choices, upgraded.choices);
9143        assert!(
9144            store
9145                .list()
9146                .iter()
9147                .any(|q| q.id == id && q.choices == upgraded.choices)
9148        );
9149        assert!(
9150            crate::prompt::chat_consult(&upgraded).contains("--reply 'fix findings and re-review'")
9151        );
9152        assert!(deputy_brief(&upgraded, Some(&state)).contains("never approves a merge"));
9153        store
9154            .update(&id, |q| q.answer(ask::Answer::Choice(REPAIR.into())))
9155            .unwrap();
9156        // An earlier build may have recorded the repair answer and stopped
9157        // before any driver consumed it. Reconcile that durable decision too.
9158        store
9159            .update(&id, |q| {
9160                q.actions.clear();
9161                Ok(())
9162            })
9163            .unwrap();
9164        assert_eq!(
9165            store.get(&id).unwrap().chosen_action(),
9166            Some(&ask::ChoiceAction::Resume {
9167                run: state.id.clone()
9168            })
9169        );
9170        let binding = state.land_approval.clone();
9171        assert_eq!(
9172            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9173                .await
9174                .unwrap(),
9175            ApprovalGate::Repair
9176        );
9177        assert!(state.land_approval.is_none());
9178        assert_eq!(state.merge_repairs.len(), 1);
9179        let request = &state.merge_repairs[0];
9180        assert_eq!(request.question, id);
9181        assert_eq!(request.head, "abc");
9182        assert_eq!(request.pr, pr.url);
9183        assert_eq!(
9184            request.reviews[0].reviews[0].summary,
9185            "precise rejection reason"
9186        );
9187        assert_eq!(request.reviews[0].reviews[0].findings[0].id, "R3-1-1");
9188        assert_eq!(
9189            request.reviews[0].reviews[0].findings[0].detail,
9190            state.reviews[0].reviews[0].findings[0].detail
9191        );
9192        // A repeated consumption of the same answer never dispatches another repair.
9193        state.land_approval = binding;
9194        assert_eq!(
9195            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9196                .await
9197                .unwrap(),
9198            ApprovalGate::Repair
9199        );
9200        assert_eq!(state.merge_repairs.len(), 1);
9201        state.land_approval = None;
9202        state.config.graph.land_approval = false;
9203        state.config.graph.hold_contested_merge = false;
9204        state.reviews.clear();
9205        assert_eq!(approval_reasons(&state), [ApprovalReason::AfterRepair]);
9206        assert_eq!(
9207            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9208                .await
9209                .unwrap(),
9210            ApprovalGate::Pending
9211        );
9212        let fresh_id = &state.land_approval.as_ref().unwrap().question;
9213        assert_ne!(fresh_id, &id);
9214        let fresh = store.get(fresh_id).unwrap();
9215        assert!(
9216            fresh
9217                .detail
9218                .contains("fresh owner approval after merge repair")
9219        );
9220        assert!(fresh.detail.contains("No review recorded"));
9221        assert!(!fresh.detail.contains("precise rejection reason"));
9222    }
9223
9224    #[tokio::test]
9225    async fn merge_repair_answer_never_merges_and_hold_never_requests_repair() {
9226        for choice in [REPAIR, HOLD] {
9227            let mut state = repair_state(false, true);
9228            let observed = seen("abc", Checks::Green, "CLEAN", false);
9229            approval_gate(&mut state, &observed.pr, "feat: x", None, "abc")
9230                .await
9231                .unwrap();
9232            let id = state.land_approval.as_ref().unwrap().question.clone();
9233            ask::Questions::open()
9234                .update(&id, |q| q.answer(ask::Answer::Choice(choice.into())))
9235                .unwrap();
9236            let forge = Scripted::new(vec![observed], vec![(true, "")]);
9237            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
9238                .await
9239                .unwrap();
9240            assert!(
9241                forge
9242                    .argvs()
9243                    .iter()
9244                    .all(|a| a.iter().any(|s| s == "--disable-auto"))
9245            );
9246            assert!(!forge.calls().contains(&"fix"));
9247            assert_eq!(state.merge_repairs.len(), usize::from(choice == REPAIR));
9248            assert_ne!(state.status, RunStatus::Merged);
9249        }
9250    }
9251
9252    #[test]
9253    fn only_the_merge_choice_merges_and_silence_holds() {
9254        let table = [
9255            (None, Approval::Hold),
9256            (Some("merge"), Approval::Merge),
9257            (Some(" merge\n"), Approval::Merge),
9258            (Some("hold"), Approval::Hold),
9259            (Some(""), Approval::Hold),
9260            (Some("yes"), Approval::Hold),
9261        ];
9262        for (answer, want) in table {
9263            assert_eq!(
9264                approval(answer),
9265                want,
9266                "answer {answer:?} must resolve to {want:?}"
9267            );
9268        }
9269    }
9270
9271    #[tokio::test]
9272    async fn a_first_visit_to_the_merge_gate_files_a_question_and_returns_pending_at_once() {
9273        let mut state = landing_state();
9274        state.config.graph.land_approval = true;
9275        let pr = green_pr();
9276
9277        let gate = approval_gate(&mut state, &pr, "feat: x", None, "abc")
9278            .await
9279            .unwrap();
9280        assert_eq!(gate, ApprovalGate::Pending, "nobody has answered yet");
9281        assert!(
9282            !state.parked,
9283            "approval_gate itself never sets `parked`; only its caller does"
9284        );
9285
9286        let store = ask::Questions::open();
9287        let filed: Vec<_> = store
9288            .list()
9289            .into_iter()
9290            .filter(|q| q.run == state.id)
9291            .collect();
9292        assert_eq!(filed.len(), 1, "exactly one question is filed");
9293        assert_eq!(filed[0].node, APPROVAL_NODE);
9294        assert_eq!(filed[0].choices, approval_choices(&state));
9295        assert!(filed[0].status.open());
9296
9297        // A second visit - standing in for a resumed run whose slot the
9298        // daemon handed to something else while nobody had answered - must
9299        // find the same question rather than filing a second one.
9300        let again = approval_gate(&mut state, &pr, "feat: x", None, "abc")
9301            .await
9302            .unwrap();
9303        assert_eq!(again, ApprovalGate::Pending);
9304        let still_one = store
9305            .list()
9306            .into_iter()
9307            .filter(|q| q.run == state.id)
9308            .count();
9309        assert_eq!(
9310            still_one, 1,
9311            "asking twice must not double-file the question"
9312        );
9313    }
9314
9315    #[tokio::test]
9316    async fn approving_the_existing_question_is_read_back_as_approved() {
9317        crate::run::pin_test_home();
9318        let mut state = run_state();
9319        state.config.graph.land_approval = true;
9320        let pr = green_pr();
9321        assert_eq!(
9322            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9323                .await
9324                .unwrap(),
9325            ApprovalGate::Pending
9326        );
9327
9328        let store = ask::Questions::open();
9329        let mut q = store
9330            .list()
9331            .into_iter()
9332            .find(|q| q.run == state.id)
9333            .expect("filed above");
9334        let talks = crate::talk::Talks::open();
9335        let cfg = crate::config::Config {
9336            agents: vec![crate::config::AgentSpec {
9337                id: "mock".into(),
9338                kind: crate::config::AgentKind::Command,
9339                model: None,
9340                command: vec!["true".into()],
9341                extra_args: Vec::new(),
9342                env: Default::default(),
9343                prompt_delivery: None,
9344                max_turn_secs: None,
9345            }],
9346            ..crate::config::Config::default()
9347        };
9348        let mut talk = crate::talk::begin(&talks, &cfg, state.repo.clone(), Some("mock")).unwrap();
9349        crate::consult::begin(&store, &talks, &q, &talk).unwrap();
9350        crate::talk::drain(&mut talk, &talks).unwrap();
9351        assert_eq!(
9352            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9353                .await
9354                .unwrap(),
9355            ApprovalGate::Pending,
9356            "consultation cannot approve or hold the merge"
9357        );
9358        q = store.get(&q.id).unwrap();
9359        assert!(q.answer.is_none());
9360        // The owner's merge answer (from the chat or the card) is the approval.
9361        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
9362        store.put(&mut q).unwrap();
9363
9364        assert_eq!(
9365            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9366                .await
9367                .unwrap(),
9368            ApprovalGate::Approved
9369        );
9370    }
9371
9372    #[tokio::test]
9373    async fn legacy_hold_actions_are_removed_on_get_and_list_before_answering() {
9374        crate::run::pin_test_home();
9375        let store = ask::Questions::open();
9376        for via_list in [false, true] {
9377            let mut state = repair_state(false, true);
9378            let pr = green_pr();
9379            approval_gate(&mut state, &pr, "feat: x", None, "abc")
9380                .await
9381                .unwrap();
9382            let id = state.land_approval.as_ref().unwrap().question.clone();
9383            store
9384                .update(&id, |q| {
9385                    q.actions.insert(
9386                        HOLD.to_owned(),
9387                        ask::ChoiceAction::Resume {
9388                            run: state.id.clone(),
9389                        },
9390                    );
9391                    Ok(())
9392                })
9393                .unwrap();
9394            let q = if via_list {
9395                store.list().into_iter().find(|q| q.id == id).unwrap()
9396            } else {
9397                store.get(&id).unwrap()
9398            };
9399            assert!(!q.actions.contains_key(HOLD));
9400            store
9401                .update(&id, |q| {
9402                    // Check the persisted migration, without another read upgrade.
9403                    assert!(!q.actions.contains_key(HOLD));
9404                    assert!(!upgrade_repair_choice(q, &state));
9405                    q.answer(ask::Answer::Choice(HOLD.to_owned()))
9406                })
9407                .unwrap();
9408            assert!(store.get(&id).unwrap().chosen_action().is_none());
9409            assert_eq!(
9410                approval_gate(&mut state, &pr, "feat: x", None, "abc")
9411                    .await
9412                    .unwrap(),
9413                ApprovalGate::Held
9414            );
9415        }
9416    }
9417
9418    #[tokio::test]
9419    async fn explicit_hold_stays_held_but_expired_approval_is_reasked() {
9420        crate::run::pin_test_home();
9421        let store = ask::Questions::open();
9422
9423        let mut held_state = run_state();
9424        held_state.config.graph.land_approval = true;
9425        let pr = green_pr();
9426        approval_gate(&mut held_state, &pr, "feat: x", None, "abc")
9427            .await
9428            .unwrap();
9429        let mut q = store
9430            .list()
9431            .into_iter()
9432            .find(|q| q.run == held_state.id)
9433            .expect("filed above");
9434        q.answer(ask::Answer::Choice(HOLD.to_owned())).unwrap();
9435        store.put(&mut q).unwrap();
9436        assert_eq!(
9437            approval_gate(&mut held_state, &pr, "feat: x", None, "abc")
9438                .await
9439                .unwrap(),
9440            ApprovalGate::Held
9441        );
9442
9443        let mut abandoned_state = run_state();
9444        abandoned_state.config.graph.land_approval = true;
9445        approval_gate(&mut abandoned_state, &pr, "feat: x", None, "abc")
9446            .await
9447            .unwrap();
9448        let mut q = store
9449            .list()
9450            .into_iter()
9451            .find(|q| q.run == abandoned_state.id)
9452            .expect("filed above");
9453        q.abandon("no answer within the timeout");
9454        store.put(&mut q).unwrap();
9455        assert_eq!(
9456            approval_gate(&mut abandoned_state, &pr, "feat: x", None, "abc")
9457                .await
9458                .unwrap(),
9459            ApprovalGate::Pending,
9460            "an expired approval must ask again without merging"
9461        );
9462        assert_eq!(
9463            store.get(&q.id).unwrap().status,
9464            ask::QuestionStatus::Abandoned
9465        );
9466        assert_ne!(
9467            abandoned_state.land_approval.as_ref().unwrap().question,
9468            q.id
9469        );
9470    }
9471
9472    fn contested() -> ContestedHandoff {
9473        let finding = |id: &str, n: u32| crate::verdict::Finding {
9474            id: id.to_owned(),
9475            severity: crate::verdict::Severity::Major,
9476            file: Some("src/a.rs".to_owned()),
9477            line: Some(n),
9478            title: format!("problem {id}"),
9479            detail: String::new(),
9480        };
9481        ContestedHandoff {
9482            findings: (1..=7).map(|n| finding(&format!("R3-1-{n}"), n)).collect(),
9483            rejecters: vec![(1, "alpha".to_owned())],
9484        }
9485    }
9486
9487    #[test]
9488    fn the_contested_record_is_asked_about_unless_the_switch_is_off() {
9489        let mut state = run_state();
9490        assert!(contested_to_ask(&state).is_none(), "nothing recorded");
9491        state.contested_handoff = Some(contested());
9492        assert!(contested_to_ask(&state).is_some());
9493        state.config.graph.hold_contested_merge = false;
9494        assert!(
9495            contested_to_ask(&state).is_none(),
9496            "the switch restores today"
9497        );
9498    }
9499
9500    #[test]
9501    fn the_deputy_brief_carries_the_pr_the_findings_and_names_what_is_missing() {
9502        let q = ask::Question::new(
9503            "run-1".to_owned(),
9504            APPROVAL_NODE.to_owned(),
9505            "land".to_owned(),
9506            "Merge?".to_owned(),
9507            String::new(),
9508            vec![APPROVE.to_owned(), HOLD.to_owned()],
9509        );
9510        let none = deputy_brief(&q, None);
9511        assert!(none.contains("could not be read"), "{none}");
9512        assert!(none.contains("Silence is a hold"), "{none}");
9513
9514        let mut state = run_state();
9515        state.pr = Some(crate::run::PrRecord {
9516            url: "https://example.test/pull/7".to_owned(),
9517            number: 7,
9518            state: "open".to_owned(),
9519            checks: "green".to_owned(),
9520            round: 0,
9521            rounds: 3,
9522            red_at_merge: Vec::new(),
9523        });
9524        state.contested_handoff = Some(contested());
9525        let b = deputy_brief(&q, Some(&state));
9526        assert!(b.contains("https://example.test/pull/7"), "{b}");
9527        assert!(b.contains("not recorded in this legacy question"), "{b}");
9528        assert!(!b.contains("This question was filed although"));
9529        state.contested_handoff = None;
9530        assert!(deputy_brief(&q, Some(&state)).contains("not recorded in this legacy question"));
9531    }
9532
9533    #[test]
9534    fn the_contested_question_names_the_pr_the_findings_and_the_rejecter() {
9535        for lang in ["en", "ja"] {
9536            let mut cfg = crate::config::Config::default();
9537            cfg.graph.language = lang.to_owned();
9538            let w = words(&cfg.graph.language);
9539            let text = w.approval_detail(
9540                "https://github.com/yukimemi/magi/pull/42",
9541                "main",
9542                "feat: x",
9543                Some(&contested()),
9544            );
9545            assert!(text.contains("pull/42"), "{text}");
9546            assert!(
9547                text.contains("R3-1-1 major src/a.rs:1: problem R3-1-1"),
9548                "{text}"
9549            );
9550            assert!(text.contains("R3-1-5"), "{text}");
9551            assert!(!text.contains("R3-1-6"), "the list is capped: {text}");
9552            assert!(text.contains("2"), "the rest are counted: {text}");
9553            assert!(text.contains("#1 (alpha)"), "{text}");
9554        }
9555        let plain = words("en").approval_detail("u", "main", "s", None);
9556        assert!(!plain.contains("reject"), "{plain}");
9557    }
9558
9559    #[tokio::test]
9560    async fn a_contested_question_is_filed_once_and_a_resume_finds_the_same_one() {
9561        crate::run::pin_test_home();
9562        let mut state = run_state();
9563        state.config.graph.land_approval = false;
9564        state.contested_handoff = Some(contested());
9565        let pr = green_pr();
9566        let c = contested_to_ask(&state);
9567        assert_eq!(
9568            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
9569                .await
9570                .unwrap(),
9571            ApprovalGate::Pending,
9572            "silence is a hold"
9573        );
9574        let store = ask::Questions::open();
9575        let filed: Vec<_> = store
9576            .list()
9577            .into_iter()
9578            .filter(|q| q.run == state.id)
9579            .collect();
9580        assert_eq!(filed.len(), 1);
9581        assert!(filed[0].detail.contains("R3-1-1"), "{}", filed[0].detail);
9582
9583        assert_eq!(
9584            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
9585                .await
9586                .unwrap(),
9587            ApprovalGate::Pending
9588        );
9589        let mut q = store
9590            .list()
9591            .into_iter()
9592            .find(|q| q.run == state.id)
9593            .unwrap();
9594        assert_eq!(q.id, filed[0].id, "the same question after a resume");
9595        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
9596        store.put(&mut q).unwrap();
9597        assert_eq!(
9598            approval_gate(&mut state, &pr, "feat: x", c.as_ref(), "abc")
9599                .await
9600                .unwrap(),
9601            ApprovalGate::Approved
9602        );
9603    }
9604
9605    #[test]
9606    fn the_diffstat_table_is_ordered_by_churn_with_binaries_last() {
9607        let rows = parse_numstat(NUMSTAT);
9608        assert_eq!(
9609            rows.iter().map(|r| r.path.as_str()).collect::<Vec<_>>(),
9610            ["src/web.rs", "src/land.rs", "assets/logo.png"]
9611        );
9612        assert_eq!(rows[2].added, None, "a binary file has no line counts");
9613    }
9614    #[test]
9615    fn the_approval_speaks_the_language_the_repository_is_configured_for() {
9616        // Reported from a real run: the merge question arrived in English on a
9617        // repository with `language = "ja"`. magi's own strings have to follow
9618        // that setting too - "it is a literal in Rust" is not an answer.
9619        let mut state = run_state();
9620        state.config.graph.language = "ja".to_owned();
9621        let pr = green_pr();
9622        let commits = ["c1".to_owned()];
9623
9624        let ja = approval_panel(&state, &pr, "3\t1\tsrc/a.rs", "+ x", &commits, "feat: x");
9625        assert!(ja.contains("lang=\"ja\""), "the document must declare it");
9626        assert!(ja.contains("squash されるコミット"), "{ja}");
9627        assert!(ja.contains("レビューコメント"), "{ja}");
9628        assert!(ja.contains("差分"), "{ja}");
9629        assert!(
9630            !ja.contains("Commits being squashed"),
9631            "no English left over"
9632        );
9633
9634        let w = words("ja");
9635        assert!(w.approval_summary(17, "feat: x").contains("マージ"));
9636        assert!(
9637            w.approval_detail("http://x/1", "main", "feat: x", None)
9638                .contains("パネル")
9639        );
9640
9641        // The evidence itself is language-neutral and must survive either way.
9642        assert!(ja.contains("src/a.rs"), "the diffstat is not prose");
9643        assert!(ja.contains("feat: x"), "nor is the merge subject");
9644
9645        // English stays the default, and a language magi cannot check falls
9646        // back to it rather than shipping a guess.
9647        state.config.graph.language = "en".to_owned();
9648        let en = approval_panel(&state, &pr, "3\t1\tsrc/a.rs", "+ x", &commits, "feat: x");
9649        assert!(en.contains("Commits being squashed"), "{en}");
9650        assert_eq!(words("Klingon").html_lang, "en");
9651    }
9652
9653    /// A `gh pr list` result naming exactly one pull request whose base and
9654    /// merge time both fit the run is exactly the case
9655    /// [`find_external_merge`] exists to act on.
9656    #[test]
9657    fn pick_open_pr_classifies_by_count_and_base() {
9658        let one = r#"[{"number":58,"url":"https://x/pull/58","title":"t","baseRefName":"main"}]"#;
9659        assert_eq!(
9660            pick_open_pr(one, "main").unwrap(),
9661            OpenPr::One {
9662                url: "https://x/pull/58".into(),
9663                title: "t".into()
9664            }
9665        );
9666        assert_eq!(pick_open_pr("[]", "main").unwrap(), OpenPr::None);
9667        assert_eq!(pick_open_pr(one, "dev").unwrap(), OpenPr::None);
9668        let two = r#"[{"number":1,"url":"u1","title":"","baseRefName":"main"},
9669                     {"number":2,"url":"u2","title":"","baseRefName":"main"}]"#;
9670        assert_eq!(
9671            pick_open_pr(two, "main").unwrap(),
9672            OpenPr::Many(vec!["u1".into(), "u2".into()])
9673        );
9674        // A fork's same-named branch is not a pull request for this head.
9675        let fork = r#"[{"url":"f","baseRefName":"main","isCrossRepository":true}]"#;
9676        assert_eq!(pick_open_pr(fork, "main").unwrap(), OpenPr::None);
9677        assert!(pick_open_pr("not json", "main").is_err());
9678        // An incomplete record is an error, never "nothing open".
9679        assert!(pick_open_pr(r#"[{"url":"u","title":"t"}]"#, "main").is_err());
9680        assert!(pick_open_pr(r#"[{"title":"t","baseRefName":"main"}]"#, "main").is_err());
9681    }
9682
9683    #[test]
9684    fn pick_merged_pr_picks_the_unique_match() {
9685        let json = r#"[
9686            {"url": "https://github.com/o/r/pull/42", "number": 42,
9687             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "main"}
9688        ]"#;
9689        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
9690        let found = pick_merged_pr(json, "main", created_at)
9691            .expect("valid json")
9692            .expect("one unambiguous match");
9693        assert_eq!(found.url, "https://github.com/o/r/pull/42");
9694        assert_eq!(found.number, 42);
9695    }
9696
9697    /// Two candidates surviving the filter is exactly as uninformative as
9698    /// zero — a branch name can be reused across runs — so neither is
9699    /// preferred over the other and nothing is recorded automatically.
9700    #[test]
9701    fn pick_merged_pr_refuses_when_more_than_one_candidate_survives() {
9702        let json = r#"[
9703            {"url": "https://github.com/o/r/pull/42", "number": 42,
9704             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "main"},
9705            {"url": "https://github.com/o/r/pull/43", "number": 43,
9706             "mergedAt": "2026-09-21T10:00:00Z", "baseRefName": "main"}
9707        ]"#;
9708        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
9709        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
9710    }
9711
9712    /// A pull request that targets a different base branch cannot be this
9713    /// run's, whatever its head branch is named — a reused branch name from
9714    /// an unrelated task must not be recorded as this run's merge.
9715    #[test]
9716    fn pick_merged_pr_ignores_a_different_base_branch() {
9717        let json = r#"[
9718            {"url": "https://github.com/o/r/pull/42", "number": 42,
9719             "mergedAt": "2026-09-20T10:00:00Z", "baseRefName": "release"}
9720        ]"#;
9721        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
9722        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
9723    }
9724
9725    /// A pull request merged before this run was even created cannot be this
9726    /// run's winner, no matter how its head branch is spelled.
9727    #[test]
9728    fn pick_merged_pr_ignores_a_merge_that_predates_the_run() {
9729        let json = r#"[
9730            {"url": "https://github.com/o/r/pull/42", "number": 42,
9731             "mergedAt": "2026-09-18T10:00:00Z", "baseRefName": "main"}
9732        ]"#;
9733        let created_at: Timestamp = "2026-09-19T00:00:00Z".parse().unwrap();
9734        assert_eq!(pick_merged_pr(json, "main", created_at).unwrap(), None);
9735    }
9736
9737    #[test]
9738    fn slug_of_pr_url_reads_host_owner_and_repo() {
9739        assert_eq!(
9740            slug_of_pr_url("https://github.com/yukimemi/shun/pull/272").as_deref(),
9741            Some("github.com/yukimemi/shun")
9742        );
9743    }
9744
9745    #[test]
9746    fn slug_of_pr_url_refuses_a_url_with_no_pull_segment() {
9747        assert_eq!(slug_of_pr_url("https://github.com/yukimemi/shun"), None);
9748        assert_eq!(slug_of_pr_url("not a url at all"), None);
9749        assert_eq!(slug_of_pr_url("https://github.com"), None);
9750    }
9751
9752    #[test]
9753    fn slug_of_repo_url_reads_host_owner_and_repo() {
9754        assert_eq!(
9755            slug_of_repo_url("https://github.com/yukimemi/magi").as_deref(),
9756            Some("github.com/yukimemi/magi")
9757        );
9758        assert_eq!(slug_of_repo_url("https://github.com"), None);
9759    }
9760
9761    #[test]
9762    fn ensure_same_repo_accepts_a_matching_slug_regardless_of_case() {
9763        ensure_same_repo("github.com/yukimemi/magi", "GitHub.Com/YukiMemi/Magi")
9764            .expect("same repo, different case");
9765    }
9766
9767    /// The shun/8c75 incident: an id-less `--merged` picked this repository's
9768    /// own in-progress run and rewrote its status from a pull request in a
9769    /// completely different repository. This is the guard that must catch
9770    /// that even when an explicit (but wrong) id is given.
9771    #[test]
9772    fn ensure_same_repo_refuses_a_different_repo() {
9773        let err =
9774            ensure_same_repo("github.com/yukimemi/magi", "github.com/yukimemi/shun").unwrap_err();
9775        let msg = format!("{err:#}");
9776        assert!(msg.contains("github.com/yukimemi/magi"), "{msg}");
9777        assert!(msg.contains("github.com/yukimemi/shun"), "{msg}");
9778    }
9779
9780    /// Same owner/repo on two different forge hosts (a GitHub Enterprise
9781    /// instance mirroring a `github.com` repository's name, say) must not be
9782    /// treated as the same repository just because the trailing path
9783    /// matches.
9784    #[test]
9785    fn ensure_same_repo_refuses_the_same_slug_on_a_different_host() {
9786        let err = ensure_same_repo(
9787            "github.com/yukimemi/magi",
9788            "github.example.com/yukimemi/magi",
9789        )
9790        .unwrap_err();
9791        let msg = format!("{err:#}");
9792        assert!(msg.contains("github.com/yukimemi/magi"), "{msg}");
9793        assert!(msg.contains("github.example.com/yukimemi/magi"), "{msg}");
9794    }
9795
9796    /// No winner decided yet means there is no branch to ask GitHub about at
9797    /// all — `find_external_merge` must return `None` without ever spawning
9798    /// `gh`, which this proves by never providing a real repository to spawn
9799    /// it in.
9800    #[tokio::test]
9801    async fn find_external_merge_returns_none_without_a_winner() {
9802        let state = RunState::new(
9803            PathBuf::from("/no/such/repo"),
9804            "main".to_owned(),
9805            "0000000000000000000000000000000000000000".to_owned(),
9806            "irrelevant".to_owned(),
9807            crate::config::Config::default(),
9808        );
9809        assert_eq!(find_external_merge(&state).await.unwrap(), None);
9810    }
9811
9812    fn pr_run(home: &Path, id: &str, repo: &str, status: RunStatus, url: &str, state: &str) {
9813        let mut run = RunState::new(
9814            PathBuf::from(repo),
9815            "main".to_owned(),
9816            "abcdef1234".to_owned(),
9817            "x".to_owned(),
9818            crate::config::Config::default(),
9819        );
9820        run.id = id.to_owned();
9821        run.status = status;
9822        run.driver_exited = true;
9823        run.pr = Some(crate::run::PrRecord {
9824            number: url.rsplit('/').next().unwrap().parse().unwrap(),
9825            url: url.to_owned(),
9826            state: state.to_owned(),
9827            checks: "red".to_owned(),
9828            round: 0,
9829            rounds: 2,
9830            red_at_merge: Vec::new(),
9831        });
9832        run.save_under(home).unwrap();
9833    }
9834
9835    fn recorded(home: &Path, id: &str) -> String {
9836        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
9837        serde_json::from_str::<RunState>(&body)
9838            .unwrap()
9839            .pr
9840            .unwrap()
9841            .state
9842    }
9843
9844    const PR: &str = "https://github.com/o/r/pull/7";
9845
9846    #[test]
9847    fn write_through_updates_predecessors_and_siblings_only() {
9848        let tmp = tempfile::tempdir().unwrap();
9849        let h = tmp.path();
9850        pr_run(
9851            h,
9852            "20261004-100000-aaaa",
9853            "/repo/r",
9854            RunStatus::Superseded,
9855            PR,
9856            "open",
9857        );
9858        pr_run(
9859            h,
9860            "20261004-100100-bbbb",
9861            "/repo/r",
9862            RunStatus::Blocked,
9863            PR,
9864            "open",
9865        );
9866        // Not terminal: a driver may be writing it.
9867        pr_run(
9868            h,
9869            "20261004-100200-cccc",
9870            "/repo/r",
9871            RunStatus::Landing,
9872            PR,
9873            "open",
9874        );
9875        // Another repository's pull request with the same number.
9876        pr_run(
9877            h,
9878            "20261004-100300-dddd",
9879            "/repo/other",
9880            RunStatus::Blocked,
9881            "https://github.com/o/other/pull/7",
9882            "open",
9883        );
9884        // A different pull request of the same repository.
9885        pr_run(
9886            h,
9887            "20261004-100400-eeee",
9888            "/repo/r",
9889            RunStatus::Blocked,
9890            "https://github.com/o/r/pull/8",
9891            "open",
9892        );
9893        pr_run(
9894            h,
9895            "20261004-100500-ffff",
9896            "/repo/r",
9897            RunStatus::Merged,
9898            PR,
9899            "open",
9900        );
9901        let source = RunState::load_under("20261004-100500-ffff", h).unwrap();
9902
9903        assert_eq!(
9904            write_pr_state_through_in(h, &source, PrLifecycle::Merged),
9905            2
9906        );
9907        assert_eq!(recorded(h, "20261004-100000-aaaa"), "merged");
9908        assert_eq!(recorded(h, "20261004-100100-bbbb"), "merged");
9909        assert_eq!(recorded(h, "20261004-100200-cccc"), "open");
9910        assert_eq!(recorded(h, "20261004-100300-dddd"), "open");
9911        assert_eq!(recorded(h, "20261004-100400-eeee"), "open");
9912        // The source's own record is the caller's to write.
9913        assert_eq!(recorded(h, "20261004-100500-ffff"), "open");
9914        // Idempotent.
9915        assert_eq!(
9916            write_pr_state_through_in(h, &source, PrLifecycle::Merged),
9917            0
9918        );
9919        let hit = RunState::load_under("20261004-100000-aaaa", h).unwrap();
9920        assert!(hit.events.iter().any(|e| e.message.contains("merged")));
9921    }
9922
9923    #[test]
9924    fn lifecycle_updates_preserve_live_and_unknown_terminal_drivers() {
9925        let home = tempfile::tempdir().unwrap();
9926        let live_id = "20261004-100000-aaaa";
9927        let unknown_id = "20261004-100100-bbbb";
9928        for id in [live_id, unknown_id] {
9929            pr_run(home.path(), id, "repo", RunStatus::Ready, PR, "open");
9930            let mut s = RunState::load_under(id, home.path()).unwrap();
9931            s.driver_exited = false;
9932            // Model legacy driver evidence, not a newly reserved unstarted run.
9933            s.driver_claimed = None;
9934            if id == live_id {
9935                s.driver_pid = Some(std::process::id());
9936                s.driver_started_at = crate::proc::process_started_at(std::process::id());
9937            }
9938            s.save_under(home.path()).unwrap();
9939            if id == unknown_id {
9940                assert_eq!(
9941                    s.liveness_under(home.path(), false),
9942                    crate::run::Liveness::Unknown
9943                );
9944            }
9945        }
9946        let known = BTreeMap::from([(PR.to_owned(), PrLifecycle::Merged)]);
9947        assert_eq!(apply_pr_states(home.path(), &known), 0);
9948        for id in [live_id, unknown_id] {
9949            assert_eq!(recorded(home.path(), id), "open");
9950        }
9951    }
9952
9953    #[test]
9954    fn repair_rewrites_merged_and_closed_and_leaves_open_and_unknown() {
9955        let tmp = tempfile::tempdir().unwrap();
9956        let h = tmp.path();
9957        let url = |n: u32| format!("https://github.com/o/r/pull/{n}");
9958        pr_run(
9959            h,
9960            "20261004-100000-aaaa",
9961            "/repo/r",
9962            RunStatus::Superseded,
9963            &url(1),
9964            "open",
9965        );
9966        pr_run(
9967            h,
9968            "20261004-100100-bbbb",
9969            "/repo/r",
9970            RunStatus::Blocked,
9971            &url(2),
9972            "open",
9973        );
9974        pr_run(
9975            h,
9976            "20261004-100200-cccc",
9977            "/repo/r",
9978            RunStatus::Ready,
9979            &url(3),
9980            "open",
9981        );
9982        pr_run(
9983            h,
9984            "20261004-100300-dddd",
9985            "/repo/r",
9986            RunStatus::Ready,
9987            &url(4),
9988            "open",
9989        );
9990        pr_run(
9991            h,
9992            "20261004-100400-eeee",
9993            "/repo/r",
9994            RunStatus::Implementing,
9995            &url(1),
9996            "open",
9997        );
9998        assert_eq!(stale_open_prs(h).len(), 4);
9999
10000        let mut known = BTreeMap::new();
10001        known.insert(url(1), PrLifecycle::Merged);
10002        known.insert(url(2), PrLifecycle::Closed);
10003        known.insert(url(3), PrLifecycle::Open);
10004        // #4: the forge could not be read, so it has no answer.
10005        assert_eq!(apply_pr_states(h, &known), 2);
10006        assert_eq!(recorded(h, "20261004-100000-aaaa"), "merged");
10007        assert_eq!(recorded(h, "20261004-100100-bbbb"), "closed");
10008        assert_eq!(recorded(h, "20261004-100200-cccc"), "open");
10009        assert_eq!(recorded(h, "20261004-100300-dddd"), "open");
10010        assert_eq!(recorded(h, "20261004-100400-eeee"), "open");
10011        assert_eq!(apply_pr_states(h, &known), 0);
10012    }
10013
10014    // --- the land loop against a scripted forge -------------------------
10015
10016    use std::collections::VecDeque;
10017    use std::sync::Mutex;
10018
10019    /// Answers views from a script (the last one repeats), merges from a
10020    /// queue, and records every call so a test can assert the order.
10021    struct Scripted {
10022        public_repo: Option<PathBuf>,
10023        evidence: Mutex<Option<CiEvidence>>,
10024        views: Mutex<VecDeque<Seen>>,
10025        merges: Mutex<VecDeque<(bool, String)>>,
10026        fix: Mutex<Option<Fixed>>,
10027        log: Mutex<Vec<&'static str>>,
10028        argvs: Mutex<Vec<Vec<String>>>,
10029        required: Mutex<Option<BTreeSet<String>>>,
10030        /// Set once a merge answered ok: the forge then reports `merged`,
10031        /// unless `queued` says the merge only entered a queue.
10032        merged: Mutex<bool>,
10033        queued: Mutex<bool>,
10034        /// Views fail once a merge answered ok.
10035        unreadable_after_merge: Mutex<bool>,
10036        /// Workflow runs asked to rerun, and whether that call fails.
10037        reruns: Mutex<Vec<String>>,
10038        rerun_fails: Mutex<bool>,
10039        /// Unix seconds; every poll moves it on by `POLL`.
10040        clock: Mutex<i64>,
10041    }
10042
10043    impl Scripted {
10044        fn new(views: Vec<Seen>, merges: Vec<(bool, &str)>) -> Self {
10045            Self {
10046                public_repo: None,
10047                evidence: Mutex::new(None),
10048                views: Mutex::new(views.into()),
10049                merges: Mutex::new(
10050                    merges
10051                        .into_iter()
10052                        .map(|(ok, m)| (ok, m.to_owned()))
10053                        .collect(),
10054                ),
10055                fix: Mutex::new(None),
10056                log: Mutex::new(Vec::new()),
10057                argvs: Mutex::new(Vec::new()),
10058                required: Mutex::new(None),
10059                merged: Mutex::new(false),
10060                queued: Mutex::new(false),
10061                unreadable_after_merge: Mutex::new(false),
10062                reruns: Mutex::new(Vec::new()),
10063                rerun_fails: Mutex::new(false),
10064                clock: Mutex::new(1_000),
10065            }
10066        }
10067        fn argvs(&self) -> Vec<Vec<String>> {
10068            self.argvs.lock().unwrap().clone()
10069        }
10070        fn calls(&self) -> Vec<&'static str> {
10071            self.log.lock().unwrap().clone()
10072        }
10073    }
10074
10075    impl Forge for Scripted {
10076        async fn attribution(&self, _state: &RunState, _seen: &Seen) -> Option<CiEvidence> {
10077            self.evidence.lock().unwrap().clone()
10078        }
10079        async fn view(&self, _repo: &Path, _url: &str) -> Result<Seen> {
10080            self.log.lock().unwrap().push("view");
10081            if *self.unreadable_after_merge.lock().unwrap()
10082                && !self.argvs.lock().unwrap().is_empty()
10083            {
10084                anyhow::bail!("forge unreachable");
10085            }
10086            let mut seen = {
10087                let mut v = self.views.lock().unwrap();
10088                if v.len() > 1 {
10089                    v.pop_front().unwrap()
10090                } else {
10091                    v[0].clone()
10092                }
10093            };
10094            if seen.head == "@published" {
10095                let head =
10096                    git::remote_head(self.public_repo.as_ref().unwrap(), "origin", "task-head")
10097                        .await?
10098                        .context("missing published head")?;
10099                seen.head.clone_from(&head);
10100                seen.rollup_head = head;
10101            }
10102            if *self.merged.lock().unwrap() {
10103                seen.pr.state = PrLifecycle::Merged;
10104            }
10105            Ok(seen)
10106        }
10107        async fn merge(&self, _repo: &Path, argv: &[String]) -> Result<(bool, String)> {
10108            self.log.lock().unwrap().push("merge");
10109            self.argvs.lock().unwrap().push(argv.to_vec());
10110            let out = self
10111                .merges
10112                .lock()
10113                .unwrap()
10114                .pop_front()
10115                .expect("unscripted merge");
10116            if out.0 && !*self.queued.lock().unwrap() && !argv.iter().any(|a| a == "--disable-auto")
10117            {
10118                *self.merged.lock().unwrap() = true;
10119            }
10120            Ok(out)
10121        }
10122        async fn poll(&self) {
10123            self.log.lock().unwrap().push("poll");
10124            *self.clock.lock().unwrap() += POLL.as_secs() as i64;
10125        }
10126        async fn rerun(&self, _repo: &Path, run: &str) -> Result<()> {
10127            self.log.lock().unwrap().push("rerun");
10128            self.reruns.lock().unwrap().push(run.to_owned());
10129            if *self.rerun_fails.lock().unwrap() {
10130                anyhow::bail!("gh run rerun: no");
10131            }
10132            Ok(())
10133        }
10134        fn now(&self) -> i64 {
10135            *self.clock.lock().unwrap()
10136        }
10137        async fn required_contexts(&self, _repo: &Path, _base: &str) -> Option<BTreeSet<String>> {
10138            self.required.lock().unwrap().clone()
10139        }
10140        async fn fix(
10141            &self,
10142            _state: &mut RunState,
10143            _pr: &PrState,
10144            _round: usize,
10145            _budget: usize,
10146            _reason: &str,
10147            _logs: &str,
10148        ) -> Result<Fixed> {
10149            self.log.lock().unwrap().push("fix");
10150            Ok(self.fix.lock().unwrap().take().expect("unscripted fix"))
10151        }
10152    }
10153
10154    const REFUSED: &str =
10155        "X Pull request #42 is not mergeable: the base branch policy prohibits the merge.";
10156
10157    fn seen(head: &str, checks: Checks, merge_state: &str, comments: bool) -> Seen {
10158        let mut pr = green_pr();
10159        pr.checks = checks;
10160        pr.blocking = Blocking::of(merge_state);
10161        if !comments {
10162            pr.review_comments.clear();
10163        }
10164        Seen {
10165            pr,
10166            title: "feat: x".to_owned(),
10167            failing_urls: Vec::new(),
10168            head: head.to_owned(),
10169            rollup_head: head.to_owned(),
10170            merge_state: merge_state.to_owned(),
10171            contexts: Vec::new(),
10172            base: "main".to_owned(),
10173        }
10174    }
10175
10176    fn landing_state() -> RunState {
10177        crate::run::pin_test_home();
10178        let mut state = run_state();
10179        state.config.graph.land_approval = false;
10180        state
10181    }
10182
10183    #[test]
10184    fn a_pushed_head_is_awaited_case_insensitively_and_an_unreadable_one_is_not_a_match() {
10185        assert!(!awaiting_new_head(None, "aaa"));
10186        assert!(!awaiting_new_head(Some("abc123"), "ABC123"));
10187        assert!(awaiting_new_head(Some("abc123"), "def456"));
10188        assert!(awaiting_new_head(Some("abc123"), ""));
10189    }
10190
10191    #[test]
10192    fn a_refusal_is_judged_by_the_pull_requests_state_not_by_its_wording() {
10193        let open = |c, m: &str| seen("a", c, m, false);
10194        let table = [
10195            (None, false, Refused::Pending),
10196            (
10197                Some(open(Checks::Pending, "BLOCKED")),
10198                false,
10199                Refused::Pending,
10200            ),
10201            (
10202                Some(open(Checks::Unknown, "BLOCKED")),
10203                false,
10204                Refused::Pending,
10205            ),
10206            (
10207                Some(open(Checks::Green, "UNKNOWN")),
10208                false,
10209                Refused::Pending,
10210            ),
10211            (Some(open(Checks::Green, "")), false, Refused::Pending),
10212            (
10213                Some(open(Checks::Green, "BLOCKED")),
10214                false,
10215                Refused::Recheck,
10216            ),
10217            (Some(open(Checks::Green, "BLOCKED")), true, Refused::Final),
10218        ];
10219        for (after, rechecked, want) in table {
10220            assert_eq!(
10221                classify_refusal(after.as_ref(), rechecked, "a", CiExpectation::Expected),
10222                want
10223            );
10224        }
10225        let mut closed = open(Checks::Green, "CLEAN");
10226        closed.pr.state = PrLifecycle::Closed;
10227        assert_eq!(
10228            classify_refusal(Some(&closed), false, "a", CiExpectation::Expected),
10229            Refused::Final
10230        );
10231    }
10232
10233    #[test]
10234    fn behind_precedes_old_ci_and_other_blocking_policies_stay_distinct() {
10235        for checks in [Checks::Pending, Checks::Unknown, Checks::Red, Checks::Green] {
10236            let pr = seen("a", checks, "BEHIND", false).pr;
10237            assert_eq!(
10238                decide_with(&pr, 0, 4, Duration::ZERO, CiExpectation::Expected),
10239                Step::Rebase
10240            );
10241        }
10242        for status in ["DRAFT", "BLOCKED", "UNKNOWN"] {
10243            let current = seen("a", Checks::Green, status, false);
10244            assert_ne!(
10245                decide_with(&current.pr, 0, 4, Duration::ZERO, CiExpectation::Expected),
10246                Step::Rebase
10247            );
10248            assert_ne!(
10249                classify_refusal(Some(&current), false, "a", CiExpectation::Expected),
10250                Refused::Behind
10251            );
10252        }
10253        let mut current = seen("a", Checks::Pending, "BEHIND", false);
10254        current.rollup_head = "old".into();
10255        assert_eq!(
10256            classify_refusal(Some(&current), true, "a", CiExpectation::Expected),
10257            Refused::Behind
10258        );
10259        assert_eq!(
10260            classify_refusal(Some(&current), true, "other", CiExpectation::Expected),
10261            Refused::Pending
10262        );
10263        current.pr.state = PrLifecycle::Closed;
10264        assert_eq!(
10265            classify_refusal(Some(&current), true, "a", CiExpectation::Expected),
10266            Refused::Final
10267        );
10268    }
10269
10270    #[tokio::test]
10271    async fn behind_at_each_landing_boundary_syncs_and_requires_new_head_approval() {
10272        for boundary in ["initial", "premerge", "refusal"] {
10273            let (_tmp, mut state, old) = landing_git_fixture().await;
10274            state.land_sync_pending = false;
10275            advance_landing_base(&state).await;
10276            state.config.verify.gate = vec!["test -f advance".into()];
10277            state.config.verify.e2e = vec!["test -f advance".into()];
10278            approval_gate(&mut state, &green_pr(), "feat: x", None, &old)
10279                .await
10280                .unwrap();
10281            let old_binding = state.land_approval.clone().unwrap();
10282            let store = ask::Questions::open();
10283            let mut question = store.get(&old_binding.question).unwrap();
10284            question
10285                .answer(ask::Answer::Choice(APPROVE.to_owned()))
10286                .unwrap();
10287            store.put(&mut question).unwrap();
10288            let mut views = Vec::new();
10289            if boundary != "initial" {
10290                views.push(seen(&old, Checks::Green, "CLEAN", false));
10291            }
10292            if boundary == "refusal" {
10293                views.push(seen(&old, Checks::Green, "CLEAN", false));
10294            }
10295            let mut behind = seen(&old, Checks::Pending, "BEHIND", false);
10296            behind.rollup_head = "old-ci-head".into();
10297            views.push(behind);
10298            // Publication checks the PR lease while verification has completed.
10299            views.push(seen(&old, Checks::Green, "CLEAN", false));
10300            views.push(seen("@published", Checks::Pending, "CLEAN", false));
10301            views.push(seen("@published", Checks::Green, "CLEAN", false));
10302            let merges = if boundary == "refusal" {
10303                vec![(false, REFUSED)]
10304            } else {
10305                vec![]
10306            };
10307            let mut forge = Scripted::new(views, merges);
10308            forge.public_repo = Some(state.repo.clone());
10309            let run = state.id.clone();
10310            land_with(&mut state, URL, &forge).await.unwrap();
10311            let head = state.pr_pushed_head.clone().unwrap();
10312            assert_ne!(head, old, "{boundary}");
10313            assert_eq!(state.id, run);
10314            assert_eq!(state.pr_branch(), Some("task-head"));
10315            assert_eq!(state.winner().unwrap().branch, "winner");
10316            assert_eq!(state.gate_head.as_deref(), Some(head.as_str()));
10317            assert!(state.gate_allows_progress());
10318            let e2e = state.head_e2e.as_ref().unwrap();
10319            assert_eq!(e2e.head, head);
10320            assert!(e2e.passed);
10321            assert_eq!(state.land_sync_attempts, 1);
10322            assert!(!state.land_sync_pending);
10323            assert!(state.parked);
10324            let binding = state.land_approval.as_ref().unwrap();
10325            assert_eq!(binding.head, head);
10326            assert_ne!(binding.question, old_binding.question);
10327            assert_eq!(forge.argvs().len(), usize::from(boundary == "refusal"));
10328            // The new question authorizes only the synchronized head on resume.
10329            let mut question = store.get(&binding.question).unwrap();
10330            question
10331                .answer(ask::Answer::Choice(APPROVE.to_owned()))
10332                .unwrap();
10333            store.put(&mut question).unwrap();
10334            let forge = Scripted::new(
10335                vec![seen(&head, Checks::Green, "CLEAN", false)],
10336                vec![(true, "")],
10337            );
10338            land_with(&mut state, URL, &forge).await.unwrap();
10339            assert_eq!(state.status, RunStatus::Merged);
10340            assert_eq!(
10341                value_of(&forge.argvs()[0], "--match-head-commit"),
10342                Some(head.as_str())
10343            );
10344        }
10345    }
10346
10347    #[tokio::test]
10348    async fn behind_refusal_remains_actionable_when_the_next_view_is_clean() {
10349        let (_tmp, mut state, old) = landing_git_fixture().await;
10350        state.land_sync_pending = false;
10351        state.config.graph.land_approval = false;
10352        state.config.verify.gate = vec!["test -f advance && test -f change".into()];
10353        advance_landing_base(&state).await;
10354        let mut forge = Scripted::new(
10355            vec![
10356                seen(&old, Checks::Green, "CLEAN", false),
10357                seen(&old, Checks::Green, "CLEAN", false),
10358                seen(&old, Checks::Green, "BEHIND", false),
10359                // The next observation is the publication lease check. The
10360                // refusal's evidence still applies to exactly this old head.
10361                seen(&old, Checks::Green, "CLEAN", false),
10362                seen("@published", Checks::Green, "CLEAN", false),
10363            ],
10364            vec![(false, REFUSED), (true, "")],
10365        );
10366        forge.public_repo = Some(state.repo.clone());
10367        land_with(&mut state, URL, &forge).await.unwrap();
10368        let head = state.pr_pushed_head.as_deref().unwrap();
10369        assert_ne!(head, old);
10370        assert_eq!(state.land_sync_attempts, 1);
10371        assert_eq!(state.gate_head.as_deref(), Some(head));
10372        assert_eq!(state.status, RunStatus::Merged);
10373        let requests = forge.argvs();
10374        assert_eq!(requests.len(), 2);
10375        assert_eq!(
10376            value_of(&requests[0], "--match-head-commit"),
10377            Some(old.as_str())
10378        );
10379        assert_eq!(value_of(&requests[1], "--match-head-commit"), Some(head));
10380    }
10381
10382    #[tokio::test]
10383    async fn behind_ancestry_failure_stops_without_rebasing_or_publishing() {
10384        let (tmp, mut state, old) = landing_git_fixture().await;
10385        state.land_sync_pending = false;
10386        // A damaged history must not be interpreted as a missing base. Keep
10387        // the head's tree intact so worktree restoration itself can succeed.
10388        let tree = git::rev_parse(&state.repo, "HEAD^{tree}").await.unwrap();
10389        let commit = tmp.path().join("broken-commit");
10390        std::fs::write(
10391            &commit,
10392            format!(
10393                "tree {tree}\nparent {}\nauthor Test <test@example.test> 1 +0000\ncommitter Test <test@example.test> 1 +0000\n\nbroken history\n",
10394                "f".repeat(40)
10395            ),
10396        )
10397        .unwrap();
10398        let replacement = git::git(
10399            &state.repo,
10400            &[
10401                "hash-object",
10402                "-t",
10403                "commit",
10404                "-w",
10405                commit.to_str().unwrap(),
10406            ],
10407        )
10408        .await
10409        .unwrap();
10410        git::git(&state.repo, &["replace", &old, replacement.trim()])
10411            .await
10412            .unwrap();
10413        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
10414        land_with(&mut state, URL, &forge).await.unwrap();
10415        assert_eq!(state.land_sync_attempts, 0);
10416        assert_eq!(state.pr_pushed_head.as_deref(), Some(old.as_str()));
10417        assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
10418        assert!(forge.argvs().is_empty());
10419        assert!(
10420            state.events.iter().any(|e| e.message.contains(
10421                "could not determine whether the landing head contains the fetched base"
10422            ))
10423        );
10424    }
10425
10426    #[tokio::test]
10427    async fn behind_fetch_failure_stops_without_rebasing_or_publishing() {
10428        let (_tmp, mut state, old) = landing_git_fixture().await;
10429        state.land_sync_pending = false;
10430        git::git(
10431            &state.repo,
10432            &["remote", "set-url", "origin", "missing-remote"],
10433        )
10434        .await
10435        .unwrap();
10436        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
10437        land_with(&mut state, URL, &forge).await.unwrap();
10438        assert_eq!(state.land_sync_attempts, 0);
10439        assert_eq!(git::rev_parse(&state.repo, "HEAD").await.unwrap(), old);
10440        assert!(
10441            state
10442                .events
10443                .iter()
10444                .any(|e| e.message.contains("cannot fetch landing base"))
10445        );
10446        assert!(forge.argvs().is_empty());
10447    }
10448
10449    #[tokio::test]
10450    async fn behind_without_base_progress_and_exhausted_resume_budget_never_publish() {
10451        let (_tmp, mut state, old) = landing_git_fixture().await;
10452        state.land_sync_pending = false;
10453        let forge = Scripted::new(vec![seen(&old, Checks::Green, "BEHIND", false)], vec![]);
10454        land_with(&mut state, URL, &forge).await.unwrap();
10455        assert_eq!(state.pr_pushed_head.as_deref(), Some(old.as_str()));
10456        assert_eq!(state.land_sync_attempts, 0);
10457        assert!(
10458            state
10459                .events
10460                .iter()
10461                .any(|e| e.message.contains("already included"))
10462        );
10463        advance_landing_base(&state).await;
10464        state.land_sync_attempts = state.config.graph.land_rounds;
10465        state.land_sync_pending = true;
10466        state.save().unwrap();
10467        let mut restored = RunState::load(&state.id).unwrap();
10468        assert!(
10469            resume_observed_head(&mut restored, &old)
10470                .await
10471                .unwrap_err()
10472                .to_string()
10473                .contains("budget exhausted")
10474        );
10475        assert_eq!(
10476            git::remote_head(&state.repo, "origin", "task-head")
10477                .await
10478                .unwrap(),
10479            Some(old)
10480        );
10481    }
10482
10483    #[tokio::test]
10484    async fn a_normal_landing_merges_on_the_first_look() {
10485        let mut state = landing_state();
10486        let forge = Scripted::new(
10487            vec![seen("a", Checks::Green, "CLEAN", false)],
10488            vec![(true, "")],
10489        );
10490        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10491            .await
10492            .unwrap();
10493        // One fresh read, then the head-bound merge.
10494        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
10495        assert_eq!(state.status, RunStatus::Merged);
10496    }
10497
10498    #[tokio::test]
10499    async fn a_successful_merge_command_that_only_queued_is_not_a_merge() {
10500        let mut state = landing_state();
10501        let forge = Scripted::new(
10502            vec![seen("a", Checks::Green, "CLEAN", false)],
10503            std::iter::repeat_n((true, ""), 100).collect(),
10504        );
10505        *forge.queued.lock().unwrap() = true;
10506        let task = async {
10507            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10508                .await
10509                .unwrap();
10510        };
10511        // Still open after the command succeeded: it keeps watching and
10512        // never records a merge (it stops at the wait ceiling instead).
10513        task.await;
10514        assert_ne!(state.status, RunStatus::Merged);
10515    }
10516
10517    #[tokio::test]
10518    async fn an_unreadable_forge_after_a_merge_command_is_not_a_confirmation() {
10519        let mut state = landing_state();
10520        let forge = Scripted::new(
10521            vec![seen("a", Checks::Green, "CLEAN", false)],
10522            std::iter::repeat_n((true, ""), 100).collect(),
10523        );
10524        *forge.unreadable_after_merge.lock().unwrap() = true;
10525        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10526            .await
10527            .ok();
10528        assert_ne!(state.status, RunStatus::Merged);
10529    }
10530
10531    #[tokio::test]
10532    async fn a_task_public_head_is_awaited_on_land_entry() {
10533        let mut state = landing_state();
10534        state.pr_head = Some("magi/task-abcd-1234".into());
10535        state.pr_pushed_head = Some("new".into());
10536        let forge = Scripted::new(
10537            vec![
10538                seen("old", Checks::Green, "CLEAN", false),
10539                seen("new", Checks::Green, "CLEAN", false),
10540            ],
10541            vec![(true, "")],
10542        );
10543        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10544            .await
10545            .unwrap();
10546        assert_eq!(
10547            forge.calls(),
10548            ["view", "poll", "view", "view", "merge", "view"]
10549        );
10550        assert_eq!(state.status, RunStatus::Merged);
10551    }
10552
10553    #[tokio::test]
10554    async fn a_superseded_public_head_owner_cannot_reenter_land() {
10555        let mut state = landing_state();
10556        state.pr_taken_over_by = Some("next".into());
10557        let forge = Scripted::new(vec![seen("a", Checks::Green, "CLEAN", false)], vec![]);
10558        assert!(
10559            land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10560                .await
10561                .is_err()
10562        );
10563        assert!(forge.calls().is_empty());
10564    }
10565
10566    #[tokio::test]
10567    async fn after_a_pushed_fix_no_merge_is_tried_until_the_head_matches() {
10568        let mut state = landing_state();
10569        let forge = Scripted::new(
10570            vec![
10571                seen("old", Checks::Green, "CLEAN", true),
10572                // The forge has not moved to the new head yet: still green.
10573                seen("old", Checks::Green, "CLEAN", true),
10574                seen("new", Checks::Pending, "BLOCKED", true),
10575                seen("new", Checks::Green, "CLEAN", true),
10576            ],
10577            vec![(true, "")],
10578        );
10579        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
10580            head: "NEW".to_owned(),
10581        });
10582        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10583            .await
10584            .unwrap();
10585        assert_eq!(
10586            forge.calls(),
10587            [
10588                "view", "fix", "poll", "view", "poll", "view", "poll", "view", "view", "merge",
10589                "view"
10590            ]
10591        );
10592        assert_eq!(state.status, RunStatus::Merged);
10593    }
10594
10595    #[tokio::test]
10596    async fn a_head_that_never_arrives_stops_naming_both_commits() {
10597        let mut state = landing_state();
10598        let forge = Scripted::new(
10599            vec![
10600                seen("old", Checks::Green, "CLEAN", true),
10601                seen("someone-elses", Checks::Green, "CLEAN", true),
10602            ],
10603            vec![],
10604        );
10605        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
10606            head: "mine".to_owned(),
10607        });
10608        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10609            .await
10610            .unwrap();
10611        assert!(!forge.calls().contains(&"merge"));
10612        let why = state.merge.as_ref().unwrap().detail.clone();
10613        assert!(
10614            why.contains("mine") && why.contains("someone-elses"),
10615            "{why}"
10616        );
10617        assert_eq!(state.status, RunStatus::Blocked);
10618    }
10619
10620    #[tokio::test]
10621    async fn a_policy_refusal_while_checks_run_waits_and_then_merges() {
10622        let mut state = landing_state();
10623        let forge = Scripted::new(
10624            vec![
10625                seen("a", Checks::Green, "CLEAN", false),
10626                seen("a", Checks::Green, "CLEAN", false),
10627                seen("a", Checks::Pending, "BLOCKED", false),
10628                seen("a", Checks::Pending, "BLOCKED", false),
10629                seen("a", Checks::Green, "CLEAN", false),
10630            ],
10631            vec![(false, REFUSED), (true, "")],
10632        );
10633        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10634            .await
10635            .unwrap();
10636        assert_eq!(
10637            forge.calls(),
10638            [
10639                "view", "view", "merge", "view", "poll", "view", "poll", "view", "view", "merge",
10640                "view"
10641            ]
10642        );
10643        assert_eq!(state.status, RunStatus::Merged);
10644    }
10645
10646    #[tokio::test]
10647    async fn a_refusal_that_outlives_settled_checks_stops_with_the_merge_state() {
10648        let mut state = landing_state();
10649        let forge = Scripted::new(
10650            vec![
10651                seen("a", Checks::Green, "CLEAN", false),
10652                seen("a", Checks::Green, "BLOCKED", false),
10653            ],
10654            vec![(false, REFUSED), (false, REFUSED)],
10655        );
10656        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10657            .await
10658            .unwrap();
10659        // One re-look is allowed for the forge's own lag, then it is final.
10660        assert_eq!(forge.calls().iter().filter(|c| **c == "merge").count(), 2);
10661        let why = state.merge.as_ref().unwrap().detail.clone();
10662        assert!(
10663            why.contains("policy prohibits") && why.contains("BLOCKED") && why.contains("refused"),
10664            "{why}"
10665        );
10666        assert_eq!(state.status, RunStatus::Blocked);
10667    }
10668
10669    #[test]
10670    fn a_decision_is_bound_to_a_head_only_when_every_signal_agrees() {
10671        assert_eq!(bound_head("abc", "abc", None), Some("abc"));
10672        assert_eq!(bound_head("abc", "ABC", Some("abc")), Some("abc"));
10673        // The pull request is still on the commit before the push.
10674        assert_eq!(bound_head("old", "old", Some("new")), None);
10675        // The checks are the previous commit's.
10676        assert_eq!(bound_head("new", "old", Some("new")), None);
10677        assert_eq!(bound_head("new", "old", None), None);
10678        // Nothing readable.
10679        assert_eq!(bound_head("", "", None), None);
10680        assert_eq!(bound_head("", "", Some("new")), None);
10681        assert_eq!(bound_head("abc", "", None), None);
10682    }
10683
10684    fn view_json(head: &str) -> String {
10685        format!(
10686            r#"{{"url":"https://github.com/o/r/pull/42","number":42,"state":"OPEN",
10687            "title":"t","headRefOid":"{head}","mergeStateStatus":"CLEAN",
10688            "reviews":[],"comments":[]}}"#
10689        )
10690    }
10691
10692    fn node_json(oid: &str, check: &str, has_next: bool) -> String {
10693        format!(
10694            r#"{{"data":{{"repository":{{"pullRequest":{{"commits":{{"nodes":[{{"commit":
10695            {{"oid":"{oid}","statusCheckRollup":{{"contexts":{{"pageInfo":{{"hasNextPage":{has_next}}},
10696            "nodes":[{{"__typename":"CheckRun","name":"ci","status":"COMPLETED",
10697            "conclusion":"{check}","detailsUrl":"https://example.test/1"}}]}}}}}}}}]}}}}}}}}}}"#
10698        )
10699    }
10700
10701    #[test]
10702    fn rollup_is_bound_to_the_commit_in_the_same_node() {
10703        // The view already points at the new head, but the node still answers
10704        // for the old commit with its red check: the head stays unbound.
10705        let s = seen_from(&view_json("new"), Some(&node_json("old", "FAILURE", false))).unwrap();
10706        assert_eq!(s.rollup_head, "old");
10707        assert_eq!(s.pr.checks, Checks::Red);
10708        assert_eq!(bound_head(&s.head, &s.rollup_head, Some("new")), None);
10709        assert_eq!(s.failing_urls.len(), 1);
10710    }
10711
10712    #[test]
10713    fn checks_come_from_the_node_not_the_view() {
10714        let view = view_json("new").replace(
10715            r#""reviews""#,
10716            r#""statusCheckRollup":[{"name":"ci","status":"COMPLETED","conclusion":"FAILURE"}],"reviews""#,
10717        );
10718        let s = seen_from(&view, Some(&node_json("new", "SUCCESS", false))).unwrap();
10719        assert_eq!(s.pr.checks, Checks::Green);
10720        assert!(s.pr.failing.is_empty());
10721        assert_eq!(
10722            bound_head(&s.head, &s.rollup_head, Some("new")),
10723            Some("new")
10724        );
10725    }
10726
10727    #[test]
10728    fn an_unreadable_or_paged_node_leaves_the_head_unbound() {
10729        for node in [
10730            None,
10731            Some("not json".to_owned()),
10732            Some(r#"{"errors":[{"message":"x"}]}"#.to_owned()),
10733            Some(node_json("new", "SUCCESS", true)),
10734        ] {
10735            let s = seen_from(&view_json("new"), node.as_deref()).unwrap();
10736            assert!(s.rollup_head.is_empty());
10737            assert_eq!(s.pr.checks, Checks::Unknown);
10738            assert_eq!(bound_head(&s.head, &s.rollup_head, None), None);
10739        }
10740    }
10741
10742    #[test]
10743    fn the_merge_command_is_pinned_to_the_observed_head() {
10744        let argv = merge_argv_at(7, "feat: x", "deadbeef");
10745        let at = argv
10746            .iter()
10747            .position(|a| a == "--match-head-commit")
10748            .unwrap();
10749        assert_eq!(argv[at + 1], "deadbeef");
10750    }
10751
10752    #[tokio::test]
10753    async fn stale_checks_after_a_fix_push_never_reach_a_merge() {
10754        let mut state = landing_state();
10755        // The pull request is on the pushed head but the rollup is still the
10756        // previous commit's red, non-required result.
10757        let mut stale = seen("new", Checks::Red, "CLEAN", false);
10758        stale.rollup_head = "old".to_owned();
10759        let forge = Scripted::new(
10760            vec![seen("old", Checks::Green, "CLEAN", true), stale],
10761            vec![],
10762        );
10763        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
10764            head: "new".to_owned(),
10765        });
10766        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10767            .await
10768            .unwrap();
10769        assert!(!forge.calls().contains(&"merge"));
10770        assert_eq!(state.status, RunStatus::Blocked);
10771        let why = state.merge.as_ref().unwrap().detail.clone();
10772        assert!(why.contains("new") && why.contains("old"), "{why}");
10773    }
10774
10775    #[test]
10776    fn a_refusal_read_against_another_commits_checks_is_pending() {
10777        let mut after = seen("a", Checks::Green, "BLOCKED", false);
10778        after.rollup_head = "old".to_owned();
10779        assert_eq!(
10780            classify_refusal(Some(&after), true, "a", CiExpectation::Expected),
10781            Refused::Pending
10782        );
10783    }
10784
10785    #[tokio::test]
10786    async fn absent_ci_empty_rollup_reaches_approval_then_merges_on_the_approved_head() {
10787        let mut state = landing_state();
10788        state.config.merge.ci = crate::config::MergeCi::None;
10789        state.config.graph.land_approval = true;
10790        let forge = Scripted::new(
10791            vec![seen("a", Checks::Unknown, "CLEAN", false)],
10792            vec![(true, "")],
10793        );
10794        land_with(&mut state, URL, &forge).await.unwrap();
10795        assert!(state.parked);
10796        assert_eq!(forge.calls(), ["view"]);
10797        let store = ask::Questions::open();
10798        let mut q = store
10799            .get(&state.land_approval.as_ref().unwrap().question)
10800            .unwrap();
10801        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
10802        store.put(&mut q).unwrap();
10803
10804        land_with(&mut state, URL, &forge).await.unwrap();
10805        assert_eq!(forge.calls(), ["view", "view", "view", "merge", "view"]);
10806        assert_eq!(state.status, RunStatus::Merged);
10807        assert_eq!(
10808            value_of(&forge.argvs()[0], "--match-head-commit"),
10809            Some("a")
10810        );
10811    }
10812
10813    #[tokio::test]
10814    async fn absent_ci_ignores_failed_workflow_runs_without_rerunning_them() {
10815        let mut state = landing_state();
10816        state.config.merge.ci = crate::config::MergeCi::None;
10817        let forge = Scripted::new(vec![red("a", Some("7"))], vec![(true, "")]);
10818        land_with(&mut state, URL, &forge).await.unwrap();
10819        assert!(forge.reruns.lock().unwrap().is_empty());
10820        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
10821        assert_eq!(state.status, RunStatus::Merged);
10822    }
10823
10824    #[test]
10825    fn absent_ci_still_requires_a_readable_matching_head_and_resolved_comments() {
10826        let shown = BTreeSet::new();
10827        let guard = |s: Option<&Seen>| {
10828            direct_merge_is_safe(s, "a", &shown, 0, 4, Duration::ZERO, CiExpectation::Absent)
10829        };
10830        let mut fresh = seen("a", Checks::Unknown, "CLEAN", false);
10831        assert!(guard(Some(&fresh)));
10832        assert!(!guard(None));
10833        fresh.rollup_head = "old".to_owned();
10834        assert!(!guard(Some(&fresh)));
10835        fresh.rollup_head = "a".to_owned();
10836        fresh.head = "b".to_owned();
10837        assert!(!guard(Some(&fresh)));
10838        assert!(!guard(Some(&seen("a", Checks::Unknown, "CLEAN", true))));
10839        assert!(!guard(Some(&seen("a", Checks::Unknown, "DIRTY", false))));
10840    }
10841
10842    #[test]
10843    fn absent_ci_refusal_does_not_wait_for_third_party_checks() {
10844        for checks in [Checks::Unknown, Checks::Pending, Checks::Red, Checks::Green] {
10845            let after = seen("a", checks, "BLOCKED", false);
10846            assert_eq!(
10847                classify_refusal(Some(&after), false, "a", CiExpectation::Absent),
10848                Refused::Recheck
10849            );
10850            assert_eq!(
10851                classify_refusal(Some(&after), true, "a", CiExpectation::Absent),
10852                Refused::Final
10853            );
10854        }
10855    }
10856
10857    #[tokio::test]
10858    async fn a_matching_head_with_red_non_required_checks_still_merges() {
10859        let mut state = landing_state();
10860        let forge = Scripted::new(
10861            vec![seen("a", Checks::Red, "CLEAN", false)],
10862            vec![(true, "")],
10863        );
10864        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10865            .await
10866            .unwrap();
10867        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
10868        assert_eq!(state.status, RunStatus::Merged);
10869    }
10870
10871    #[tokio::test]
10872    async fn a_merge_refused_because_the_head_moved_looks_again_instead_of_failing() {
10873        let mut state = landing_state();
10874        let forge = Scripted::new(
10875            vec![
10876                seen("a", Checks::Green, "CLEAN", false),
10877                seen("a", Checks::Green, "CLEAN", false),
10878                // Re-viewed after the refusal: someone pushed.
10879                seen("b", Checks::Green, "BLOCKED", false),
10880                seen("b", Checks::Green, "CLEAN", false),
10881            ],
10882            vec![(false, REFUSED), (true, "")],
10883        );
10884        land_with(&mut state, "https://github.com/o/r/pull/42", &forge)
10885            .await
10886            .unwrap();
10887        assert_eq!(
10888            forge.calls(),
10889            [
10890                "view", "view", "merge", "view", "poll", "view", "view", "merge", "view"
10891            ]
10892        );
10893        assert_eq!(state.status, RunStatus::Merged);
10894    }
10895
10896    fn merged_view(head: &str) -> Seen {
10897        let mut m = seen(head, Checks::Green, "CLEAN", false);
10898        m.pr.state = PrLifecycle::Merged;
10899        m
10900    }
10901
10902    fn has(argv: &[String], flag: &str) -> bool {
10903        argv.iter().any(|a| a == flag)
10904    }
10905
10906    fn value_of<'a>(argv: &'a [String], flag: &str) -> Option<&'a str> {
10907        let at = argv.iter().position(|a| a == flag)?;
10908        argv.get(at + 1).map(String::as_str)
10909    }
10910
10911    const URL: &str = "https://github.com/o/r/pull/42";
10912
10913    #[tokio::test]
10914    async fn the_merge_step_merges_directly_on_the_observed_head_and_never_arms() {
10915        let mut state = landing_state();
10916        let forge = Scripted::new(
10917            vec![
10918                seen("abc", Checks::Green, "CLEAN", false),
10919                seen("abc", Checks::Green, "CLEAN", false),
10920            ],
10921            vec![(true, "")],
10922        );
10923        land_with(&mut state, URL, &forge).await.unwrap();
10924        assert_eq!(forge.calls(), ["view", "view", "merge", "view"]);
10925        let argv = &forge.argvs()[0];
10926        assert!(has(argv, "--squash") && has(argv, "--subject"));
10927        assert!(!has(argv, "--auto") && !has(argv, "--admin"));
10928        assert_eq!(value_of(argv, "--match-head-commit"), Some("abc"));
10929        assert_eq!(state.status, RunStatus::Merged);
10930        assert!(state.land_armed_head.is_none());
10931    }
10932
10933    #[tokio::test]
10934    async fn a_resume_disables_an_arm_left_by_an_older_build_before_merging() {
10935        let mut state = landing_state();
10936        state.land_armed_head = Some("a".to_owned());
10937        let forge = Scripted::new(
10938            vec![seen("a", Checks::Green, "CLEAN", false)],
10939            vec![(true, ""), (true, "")],
10940        );
10941        land_with(&mut state, URL, &forge).await.unwrap();
10942        let argvs = forge.argvs();
10943        assert!(has(&argvs[0], "--disable-auto"));
10944        assert!(!has(&argvs[1], "--auto"));
10945        assert_eq!(value_of(&argvs[1], "--match-head-commit"), Some("a"));
10946        assert_eq!(state.status, RunStatus::Merged);
10947        assert!(state.land_armed_head.is_none());
10948    }
10949
10950    #[tokio::test]
10951    async fn an_approval_never_carries_over_to_a_new_head() {
10952        crate::run::pin_test_home();
10953        let mut state = run_state();
10954        state.config.graph.land_approval = true;
10955        let pr = green_pr();
10956        let store = ask::Questions::open();
10957
10958        approval_gate(&mut state, &pr, "feat: x", None, "aaa")
10959            .await
10960            .unwrap();
10961        let mut q = store
10962            .list()
10963            .into_iter()
10964            .find(|q| q.run == state.id)
10965            .unwrap();
10966        q.answer(ask::Answer::Choice(APPROVE.to_owned())).unwrap();
10967        store.put(&mut q).unwrap();
10968        assert_eq!(
10969            approval_gate(&mut state, &pr, "feat: x", None, "AAA")
10970                .await
10971                .unwrap(),
10972            ApprovalGate::Approved,
10973            "the same head keeps its approval"
10974        );
10975
10976        // A new head is a new question, not the old word.
10977        assert_eq!(
10978            approval_gate(&mut state, &pr, "feat: x", None, "bbb")
10979                .await
10980                .unwrap(),
10981            ApprovalGate::Pending
10982        );
10983        let all: Vec<_> = store
10984            .list()
10985            .into_iter()
10986            .filter(|q| q.run == state.id)
10987            .collect();
10988        assert_eq!(all.len(), 2);
10989
10990        // A question recorded before heads were tracked is not reused either.
10991        state.land_approval = None;
10992        assert_eq!(
10993            approval_gate(&mut state, &pr, "feat: x", None, "bbb")
10994                .await
10995                .unwrap(),
10996            ApprovalGate::Pending
10997        );
10998        let open = store
10999            .list()
11000            .into_iter()
11001            .filter(|q| q.run == state.id && q.status.open())
11002            .count();
11003        assert_eq!(open, 1, "the superseded question was retired");
11004    }
11005
11006    #[tokio::test]
11007    async fn the_merge_is_bound_to_the_head_it_was_decided_on() {
11008        let mut state = landing_state();
11009        let forge = Scripted::new(
11010            vec![
11011                seen("a", Checks::Green, "CLEAN", false),
11012                // The fresh read before the merge: someone pushed.
11013                seen("b", Checks::Green, "CLEAN", false),
11014            ],
11015            vec![(true, "")],
11016        );
11017        land_with(&mut state, URL, &forge).await.unwrap();
11018        let argvs = forge.argvs();
11019        assert_eq!(argvs.len(), 1, "no merge was tried on the moved head");
11020        assert!(!has(&argvs[0], "--auto"));
11021        assert_eq!(value_of(&argvs[0], "--match-head-commit"), Some("b"));
11022        assert_eq!(state.status, RunStatus::Merged);
11023    }
11024
11025    fn passing(label: &str) -> CheckInfo {
11026        CheckInfo {
11027            label: label.to_owned(),
11028            verdict: Verdict::Pass,
11029            required: Some(false),
11030            run: None,
11031        }
11032    }
11033
11034    fn failing(label: &str, run: Option<&str>) -> (String, Option<String>) {
11035        (label.to_owned(), run.map(str::to_owned))
11036    }
11037
11038    fn reran(head: &str, runs: &[(&str, i64)]) -> LandReruns {
11039        LandReruns {
11040            head: head.to_owned(),
11041            runs: runs.iter().map(|(r, at)| ((*r).to_owned(), *at)).collect(),
11042        }
11043    }
11044
11045    #[test]
11046    fn a_failed_run_is_rerun_once_then_waited_on_then_left_to_the_fixer() {
11047        let f = [failing("test (macos)", Some("7"))];
11048        assert_eq!(
11049            rerun_step(&f, None, "h", 100),
11050            RerunStep::Rerun(vec!["7".to_owned()])
11051        );
11052        let rec = reran("h", &[("7", 100)]);
11053        let grace = crate::release_watch::RERUN_GRACE;
11054        assert_eq!(
11055            rerun_step(&f, Some(&rec), "h", 100 + grace - 1),
11056            RerunStep::Grace
11057        );
11058        assert_eq!(rerun_step(&f, Some(&rec), "h", 100 + grace), RerunStep::Fix);
11059    }
11060
11061    #[test]
11062    fn a_failure_without_a_run_id_goes_to_the_fixer() {
11063        let f = [failing("a", Some("7")), failing("ci/external", None)];
11064        assert_eq!(rerun_step(&f, None, "h", 0), RerunStep::Fix);
11065        assert_eq!(rerun_step(&[], None, "h", 0), RerunStep::Fix);
11066    }
11067
11068    #[test]
11069    fn a_moved_head_forgets_the_reruns() {
11070        let f = [failing("a", Some("7"))];
11071        let rec = reran("old", &[("7", 100)]);
11072        assert_eq!(
11073            rerun_step(&f, Some(&rec), "new", 101),
11074            RerunStep::Rerun(vec!["7".to_owned()])
11075        );
11076    }
11077
11078    #[test]
11079    fn only_unrerun_runs_are_rerun_and_duplicates_collapse() {
11080        let f = [
11081            failing("a", Some("7")),
11082            failing("b", Some("7")),
11083            failing("c", Some("8")),
11084        ];
11085        assert_eq!(
11086            rerun_step(&f, None, "h", 0),
11087            RerunStep::Rerun(vec!["7".to_owned(), "8".to_owned()])
11088        );
11089        let rec = reran("h", &[("7", 0)]);
11090        assert_eq!(
11091            rerun_step(&f, Some(&rec), "h", 1),
11092            RerunStep::Rerun(vec!["8".to_owned()])
11093        );
11094    }
11095
11096    #[test]
11097    fn only_blocking_failures_are_candidates_for_a_rerun() {
11098        let check = |label: &str, verdict, required, run: &str| CheckInfo {
11099            label: label.to_owned(),
11100            verdict,
11101            required,
11102            run: Some(run.to_owned()),
11103        };
11104        let got = rerunnable(&[
11105            check("passed", Verdict::Pass, Some(true), "1"),
11106            check("optional", Verdict::Fail, Some(false), "2"),
11107            check("required", Verdict::Fail, Some(true), "3"),
11108            check("unknown", Verdict::Fail, None, "4"),
11109        ]);
11110        let labels: Vec<_> = got.iter().map(|(l, _)| l.as_str()).collect();
11111        assert_eq!(labels, ["required", "unknown"]);
11112    }
11113
11114    fn unrelated_ci_fixture() -> CiEvidence {
11115        let failure = CiFailure {
11116            path: "tests/web_render.rs".into(),
11117            start_line: 42,
11118            end_line: 42,
11119            title: "question_identity_disclosure_copy_and_live_updates".into(),
11120            message: "assertion failed".into(),
11121        };
11122        CiEvidence {
11123            head: "a".into(),
11124            base: "base-sha".into(),
11125            changed: vec![
11126                "AGENTS.md".into(),
11127                "src/talk.rs".into(),
11128                "tests/consult_investigation.rs".into(),
11129            ],
11130            checks: vec![CiCheckEvidence {
11131                label: "coverage".into(),
11132                head_check: 70,
11133                base_check: 60,
11134                app: 1,
11135                run: "7".into(),
11136                base_run: "6".into(),
11137                head_failures: vec![failure.clone()],
11138                base_failures: vec![failure],
11139                rerun_exhausted: true,
11140            }],
11141        }
11142    }
11143
11144    #[test]
11145    fn unrelated_ci_requires_complete_structural_evidence_for_every_failure() {
11146        let good = unrelated_ci_fixture();
11147        let red = vec!["coverage".into()];
11148        assert!(good.unrelated("a", &red));
11149        assert!(!good.unrelated("another-head", &red));
11150        assert!(!good.unrelated("a", &["coverage".into(), "test".into()]));
11151        assert!(!good.unrelated("a", &[]));
11152        for mutation in 0..8 {
11153            let mut bad = good.clone();
11154            match mutation {
11155                0 => bad.checks[0].rerun_exhausted = false,
11156                1 => bad.checks[0].base_failures.clear(),
11157                2 => bad.checks[0].head_failures.clear(),
11158                3 => bad.changed.push("tests/web_render.rs".into()),
11159                4 => bad.changed.push(".github/workflows/ci.yml".into()),
11160                5 => bad.checks[0].base_failures[0].message = "different failure".into(),
11161                6 => bad.checks.push(bad.checks[0].clone()),
11162                _ => bad.base.clear(),
11163            }
11164            assert!(!bad.unrelated("a", &red), "mutation {mutation}");
11165        }
11166    }
11167
11168    #[test]
11169    fn red_unknown_merge_state_waits_before_repair_but_never_implies_merge() {
11170        let pr = seen("a", Checks::Red, "UNKNOWN", false).pr;
11171        assert_eq!(decide(&pr, 0, 2, Duration::ZERO), Step::Wait);
11172        assert!(matches!(decide(&pr, 0, 2, CHECKS_GRACE), Step::Fix { .. }));
11173        assert!(matches!(
11174            decide(&pr, 2, 2, CHECKS_GRACE),
11175            Step::GiveUp { .. }
11176        ));
11177        let optional = CheckInfo {
11178            label: "coverage".into(),
11179            verdict: Verdict::Fail,
11180            required: Some(false),
11181            run: Some("7".into()),
11182        };
11183        assert!(rerunnable_with(std::slice::from_ref(&optional), false).is_empty());
11184        assert_eq!(
11185            rerunnable_with(&[optional], true),
11186            vec![("coverage".into(), Some("7".into()))]
11187        );
11188    }
11189
11190    #[tokio::test]
11191    async fn unrelated_ci_after_a_comment_round_does_not_charge_a_no_commit_stop() {
11192        let mut state = landing_state();
11193        let mut red = coverage_unknown();
11194        red.pr = seen("a", Checks::Red, "BLOCKED", true).pr;
11195        red.pr.failing = vec!["coverage".into()];
11196        let forge = Scripted::new(vec![red], vec![]);
11197        *forge.evidence.lock().unwrap() = Some(unrelated_ci_fixture());
11198        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11199        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11200        assert!(forge.calls().contains(&"fix"));
11201        assert!(state.land_unrelated.is_some());
11202        assert!(state.parked);
11203        assert!(
11204            !state
11205                .events
11206                .iter()
11207                .any(|e| e.message.contains("fixer produced no commit"))
11208        );
11209    }
11210
11211    fn coverage_unknown() -> Seen {
11212        let mut s = red("a", Some("7"));
11213        s.pr.blocking = Blocking::Unsaid;
11214        s.merge_state = "UNKNOWN".into();
11215        s.pr.failing = vec!["coverage".into()];
11216        s.contexts[0].label = "coverage".into();
11217        s.contexts[0].required = Some(false);
11218        s
11219    }
11220
11221    #[tokio::test]
11222    async fn run_196c_unknown_then_unstable_does_not_spend_a_fix_round() {
11223        let mut state = landing_state();
11224        let unknown = coverage_unknown();
11225        let mut unstable = unknown.clone();
11226        unstable.pr.blocking = Blocking::of("UNSTABLE");
11227        unstable.merge_state = "UNSTABLE".into();
11228        let forge = Scripted::new(vec![unknown, unstable], vec![(true, "")]);
11229        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11230        assert!(!forge.calls().contains(&"fix"));
11231        assert!(!forge.calls().contains(&"rerun"));
11232        assert_eq!(state.status, RunStatus::Merged);
11233        assert_eq!(state.pr.unwrap().round, 0);
11234    }
11235
11236    #[tokio::test]
11237    async fn run_196c_persistent_unknown_reruns_optional_once_then_parks_with_evidence() {
11238        let mut state = landing_state();
11239        let forge = Scripted::new(vec![coverage_unknown()], vec![]);
11240        *forge.evidence.lock().unwrap() = Some(unrelated_ci_fixture());
11241        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11242        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11243        assert!(!forge.calls().contains(&"fix"));
11244        assert!(state.parked);
11245        assert_eq!(state.status, RunStatus::Landing);
11246        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11247        let hold = state.land_unrelated.as_ref().unwrap();
11248        let q = ask::Questions::open().get(&hold.question).unwrap();
11249        assert!(
11250            q.actions
11251                .values()
11252                .any(|a| matches!(a, ask::ChoiceAction::Resume { .. }))
11253        );
11254        assert!(
11255            state
11256                .events
11257                .iter()
11258                .any(|e| e.message.contains("[ci-unrelated]") && e.message.contains("base-sha"))
11259        );
11260        let first = state.land_unsaid.clone();
11261        // A resume on this head neither extends UNKNOWN grace nor reruns 7.
11262        state.parked = false;
11263        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11264        assert_eq!(state.land_unsaid, first);
11265        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11266    }
11267
11268    fn red(head: &str, run: Option<&str>) -> Seen {
11269        let mut s = seen(head, Checks::Red, "BLOCKED", false);
11270        s.pr.failing = vec!["test (macos)".to_owned()];
11271        s.contexts = vec![CheckInfo {
11272            label: "test (macos)".to_owned(),
11273            verdict: Verdict::Fail,
11274            required: Some(true),
11275            run: run.map(str::to_owned),
11276        }];
11277        s
11278    }
11279
11280    const RERUN_PR: &str = "https://github.com/o/r/pull/42";
11281
11282    #[tokio::test]
11283    async fn a_flaky_red_check_is_rerun_without_a_fix_round_and_then_merges() {
11284        let mut state = landing_state();
11285        let forge = Scripted::new(
11286            vec![
11287                red("a", Some("7")),
11288                seen("a", Checks::Pending, "BLOCKED", false),
11289                seen("a", Checks::Green, "CLEAN", false),
11290            ],
11291            vec![(true, "")],
11292        );
11293        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11294        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11295        assert!(!forge.calls().contains(&"fix"));
11296        assert_eq!(state.status, RunStatus::Merged);
11297        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11298        let argvs = forge.argvs();
11299        assert_eq!(value_of(&argvs[0], "--match-head-commit"), Some("a"));
11300        assert!(
11301            state
11302                .events
11303                .iter()
11304                .any(|e| e.message.contains("test (macos)") && e.message.contains("run 7"))
11305        );
11306    }
11307
11308    #[tokio::test]
11309    async fn still_red_after_the_grace_goes_to_the_fixer_and_a_run_is_not_rerun_twice() {
11310        let mut state = landing_state();
11311        let forge = Scripted::new(
11312            vec![
11313                red("a", Some("7")),
11314                seen("a", Checks::Green, "CLEAN", false),
11315            ],
11316            vec![(true, "")],
11317        );
11318        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11319        // The red view repeats for the grace, then the fixer is asked once.
11320        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11321        assert_eq!(forge.reruns.lock().unwrap().len(), 1);
11322        let calls = forge.calls();
11323        let rerun_at = calls.iter().position(|c| *c == "rerun").unwrap();
11324        let fix_at = calls.iter().position(|c| *c == "fix");
11325        assert!(fix_at.is_none_or(|f| f > rerun_at));
11326    }
11327
11328    #[tokio::test]
11329    async fn a_failed_run_is_rerun_while_another_run_is_still_pending() {
11330        let mut state = landing_state();
11331        let mut v = red("a", Some("7"));
11332        v.pr.checks = Checks::Pending;
11333        v.contexts.push(CheckInfo {
11334            label: "slow".to_owned(),
11335            verdict: Verdict::Pending,
11336            required: Some(true),
11337            run: Some("8".to_owned()),
11338        });
11339        let forge = Scripted::new(
11340            vec![v, seen("a", Checks::Green, "CLEAN", false)],
11341            vec![(true, "")],
11342        );
11343        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11344        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11345        assert_eq!(state.status, RunStatus::Merged);
11346    }
11347
11348    #[test]
11349    fn a_run_with_a_job_still_going_is_not_rerun_yet() {
11350        let mut v = red("a", Some("7"));
11351        v.contexts.push(CheckInfo {
11352            label: "same run, still going".to_owned(),
11353            verdict: Verdict::Pending,
11354            required: Some(true),
11355            run: Some("7".to_owned()),
11356        });
11357        assert!(rerunnable(&v.contexts).is_empty());
11358    }
11359
11360    #[tokio::test]
11361    async fn the_rerun_is_made_even_when_the_fix_budget_is_spent() {
11362        let mut state = landing_state();
11363        state.config.graph.land_rounds = 0;
11364        let forge = Scripted::new(
11365            vec![
11366                red("a", Some("7")),
11367                seen("a", Checks::Green, "CLEAN", false),
11368            ],
11369            vec![(true, "")],
11370        );
11371        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11372        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11373        assert_eq!(state.status, RunStatus::Merged);
11374        assert!(!forge.calls().contains(&"fix"));
11375        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11376    }
11377
11378    #[tokio::test]
11379    async fn a_deferred_landing_fix_keeps_its_round_for_resume() {
11380        let mut state = landing_state();
11381        state.config.graph.land_rounds = 1;
11382        let forge = Scripted::new(vec![seen("a", Checks::Green, "CLEAN", true)], vec![]);
11383        *forge.fix.lock().unwrap() = Some(Fixed::Deferred);
11384        let pr = land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11385        assert_eq!(pr.state, PrLifecycle::Open);
11386        assert_eq!(state.status, RunStatus::Blocked);
11387        assert_eq!(state.pr.as_ref().unwrap().round, 0);
11388        assert!(
11389            state.merge_decision.is_none(),
11390            "no ordinary failure handoff"
11391        );
11392        assert!(forge.argvs().is_empty(), "no merge on outage");
11393
11394        let recovered = Scripted::new(
11395            vec![
11396                seen("a", Checks::Green, "CLEAN", true),
11397                seen("b", Checks::Green, "CLEAN", false),
11398            ],
11399            vec![(true, "")],
11400        );
11401        *recovered.fix.lock().unwrap() = Some(Fixed::Committed { head: "b".into() });
11402        land_with(&mut state, RERUN_PR, &recovered).await.unwrap();
11403        assert_eq!(state.status, RunStatus::Merged);
11404        assert_eq!(state.pr.as_ref().unwrap().round, 1);
11405        assert_eq!(recovered.calls().iter().filter(|c| **c == "fix").count(), 1);
11406    }
11407
11408    #[tokio::test]
11409    async fn the_last_fix_rounds_new_head_gets_its_rerun() {
11410        let mut state = landing_state();
11411        state.config.graph.land_rounds = 1;
11412        let forge = Scripted::new(
11413            vec![
11414                seen("a", Checks::Green, "CLEAN", true),
11415                red("b", Some("7")),
11416                seen("b", Checks::Green, "CLEAN", false),
11417            ],
11418            vec![(true, "")],
11419        );
11420        *forge.fix.lock().unwrap() = Some(Fixed::Committed {
11421            head: "b".to_owned(),
11422        });
11423        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11424        assert_eq!(*forge.reruns.lock().unwrap(), ["7"]);
11425        assert_eq!(forge.calls().iter().filter(|c| **c == "fix").count(), 1);
11426        assert_eq!(state.pr.as_ref().unwrap().round, 1);
11427        assert_eq!(state.status, RunStatus::Merged);
11428        assert_eq!(state.land_reruns.as_ref().unwrap().head, "b");
11429        assert_eq!(
11430            value_of(&forge.argvs()[0], "--match-head-commit"),
11431            Some("b")
11432        );
11433    }
11434
11435    #[tokio::test]
11436    async fn a_failed_rerun_call_falls_through_to_the_fix_in_the_same_lap() {
11437        let mut state = landing_state();
11438        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
11439        *forge.rerun_fails.lock().unwrap() = true;
11440        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11441        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11442        assert_eq!(forge.reruns.lock().unwrap().len(), 1, "never retried");
11443        assert_eq!(
11444            forge.calls().iter().filter(|c| **c == "fix").count(),
11445            1,
11446            "{:?}",
11447            forge.calls()
11448        );
11449    }
11450
11451    #[tokio::test]
11452    async fn a_saved_rerun_record_stops_a_restart_from_rerunning() {
11453        let mut state = landing_state();
11454        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
11455        // The record was written just before the previous pass died.
11456        state.land_reruns = Some(reran("a", &[("7", *forge.clock.lock().unwrap())]));
11457        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11458        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11459        assert!(forge.reruns.lock().unwrap().is_empty());
11460    }
11461
11462    #[tokio::test]
11463    async fn the_switch_off_and_a_missing_run_id_go_straight_to_the_fixer() {
11464        let mut state = landing_state();
11465        state.config.graph.rerun_flaky_checks = false;
11466        let forge = Scripted::new(vec![red("a", Some("7"))], vec![]);
11467        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11468        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11469        assert!(forge.reruns.lock().unwrap().is_empty());
11470        assert!(forge.calls().contains(&"fix"));
11471
11472        let mut state = landing_state();
11473        let forge = Scripted::new(vec![red("a", None)], vec![]);
11474        *forge.fix.lock().unwrap() = Some(Fixed::Declined);
11475        land_with(&mut state, RERUN_PR, &forge).await.unwrap();
11476        assert!(forge.reruns.lock().unwrap().is_empty());
11477        assert!(forge.calls().contains(&"fix"));
11478    }
11479
11480    fn names(xs: &[&str]) -> BTreeSet<String> {
11481        xs.iter().map(|x| (*x).to_owned()).collect()
11482    }
11483
11484    #[test]
11485    fn a_required_check_the_rollup_never_listed_is_named() {
11486        let req = names(&["build"]);
11487        let why = waiting_on("BLOCKED", &[passing("review")], Some(&req));
11488        assert!(why.contains("never reported: build"), "{why}");
11489        assert!(!why.contains("probably waiting for a review"), "{why}");
11490    }
11491
11492    #[test]
11493    fn an_unreadable_required_list_is_not_read_as_a_review_wait() {
11494        let why = waiting_on("BLOCKED", &[passing("review")], None);
11495        assert!(why.contains("could not be read"), "{why}");
11496        assert!(!why.contains("probably waiting for a review"), "{why}");
11497    }
11498
11499    #[test]
11500    fn all_required_reported_keeps_the_review_guess() {
11501        let req = names(&["build"]);
11502        let why = waiting_on("BLOCKED", &[passing("build")], Some(&req));
11503        assert!(why.contains("probably waiting for a review"), "{why}");
11504        assert!(!why.contains("never reported"), "{why}");
11505    }
11506
11507    #[test]
11508    fn required_names_match_the_rollup_ignoring_case_only() {
11509        let req = names(&["Build"]);
11510        let why = waiting_on("BLOCKED", &[passing("build")], Some(&req));
11511        assert!(!why.contains("never reported"), "{why}");
11512    }
11513
11514    #[test]
11515    fn required_contexts_are_read_from_protection_and_rulesets() {
11516        let classic = r#"{"contexts":["build"],"checks":[{"context":"lint","app_id":1}]}"#;
11517        assert_eq!(
11518            parse_classic_required(classic),
11519            Some(names(&["build", "lint"]))
11520        );
11521        let rules = r#"[{"type":"pull_request","parameters":{}},
11522            {"type":"required_status_checks","parameters":{"required_status_checks":[{"context":"test"}]}}]"#;
11523        assert_eq!(parse_ruleset_required(rules), Some(names(&["test"])));
11524        assert_eq!(parse_ruleset_required("nope"), None);
11525        assert_eq!(encode_path_segment("release/1.x"), "release%2F1.x");
11526    }
11527
11528    #[test]
11529    fn the_direct_merge_guard_needs_the_approved_head_bound_to_its_checks() {
11530        let shown = BTreeSet::new();
11531        let ok = seen("a", Checks::Green, "CLEAN", false);
11532        let guard = |s: Option<&Seen>| {
11533            direct_merge_is_safe(
11534                s,
11535                "A",
11536                &shown,
11537                0,
11538                4,
11539                Duration::ZERO,
11540                CiExpectation::Expected,
11541            )
11542        };
11543        assert!(guard(Some(&ok)));
11544        assert!(!guard(None));
11545        assert!(!guard(Some(&seen("b", Checks::Green, "CLEAN", false))));
11546        let mut stale = ok.clone();
11547        stale.rollup_head = "old".to_owned();
11548        assert!(!guard(Some(&stale)));
11549        assert!(!guard(Some(&seen("a", Checks::Pending, "BLOCKED", false))));
11550        assert!(!guard(Some(&merged_view("a"))));
11551    }
11552
11553    #[test]
11554    fn the_rollup_node_carries_whether_each_check_is_required() {
11555        let node = node_json("new", "SUCCESS", false)
11556            .replace(r#""name":"ci","#, r#""name":"ci","isRequired":true,"#);
11557        let s = seen_from(&view_json("new"), Some(&node)).unwrap();
11558        assert_eq!(s.contexts.len(), 1);
11559        assert_eq!(s.contexts[0].required, Some(true));
11560        let s = seen_from(&view_json("new"), Some(&node_json("new", "SUCCESS", false))).unwrap();
11561        assert_eq!(s.contexts[0].required, None);
11562    }
11563
11564    #[tokio::test]
11565    async fn a_resume_that_cannot_disable_a_recorded_arm_stops_and_keeps_the_record() {
11566        let mut state = landing_state();
11567        state.land_armed_head = Some("a".to_owned());
11568        let forge = Scripted::new(
11569            vec![seen("a", Checks::Green, "CLEAN", true)],
11570            vec![(false, "disable exploded")],
11571        );
11572        land_with(&mut state, URL, &forge).await.unwrap();
11573        assert!(!forge.calls().contains(&"fix"));
11574        assert_eq!(state.status, RunStatus::Blocked);
11575        assert_eq!(state.land_armed_head.as_deref(), Some("a"));
11576        let why = state.merge.as_ref().unwrap().detail.clone();
11577        assert!(why.contains("disable exploded"), "{why}");
11578    }
11579}