Skip to main content

magi/
graph.rs

1//! The competition graph.
2//!
3//! ```text
4//! prep ──► implement ×N ──► judge ×M (blind) ──► split? ──► deliberate ──► vote (private)
5//!                                                   │                          │
6//!                                                   └──── unanimous ───────────┤
7//!                                                                              ▼
8//!   merge ◄── gate ◄── review ×R + E2E, fix, repeat ◄── fold losers ◄──────── tally
9//! ```
10//!
11//! Every node persists before the next one starts, so a run can be resumed
12//! after a crash, a rate limit, or a reboot without re-spending the work that
13//! already landed.
14//!
15//! The design decision that matters most is *where the facilitator lives*.
16//! There is no moderator agent: magi assigns the labels, decides the
17//! presentation order, relays the transcript, and collects the final votes
18//! one-to-one. A moderator that never learns an author cannot leak one.
19use std::collections::{BTreeMap, BTreeSet};
20use std::path::{Path, PathBuf};
21use std::sync::atomic::{AtomicBool, Ordering};
22use std::sync::{Arc, Mutex};
23use std::time::{Duration, Instant};
24
25use anyhow::{Context as _, Result, bail};
26use jiff::Timestamp;
27use tokio::sync::Semaphore;
28
29use crate::advise;
30use crate::agent::{self, AgentOutput, Invocation, SeatState};
31use crate::ask;
32use crate::blind;
33use crate::bump;
34use crate::config::{
35    AgentSpec, Config, IncompleteReviewPolicy, LeakPolicy, MergeMode, MergeStyle, Prompts,
36    ResolvedRoles,
37};
38use crate::fixer;
39use crate::git;
40use crate::graft;
41use crate::land;
42use crate::proc::Quiet as _;
43use crate::prompt::{
44    self, CandidateView, Lens, ReviewPatch, ReviewReconsiderCtx, ReviewSeatReport, Turn,
45};
46use crate::queue;
47#[cfg(test)]
48use crate::refs;
49use crate::run::{
50    BaseSync, Candidate, CommandOutcome, ContinuationOutcome, ContinuationRecord,
51    DeliberationRound, DeliberationTurn, E2eStatus, FailClass, FixRecord, GateFixRecord,
52    GithubTextChoice, GraftOutcome, GraftRecord, Handover, JobRecord, JobStatus, Judgement,
53    MergeOutcome, OperatorFixFinding, OperatorFixOutcome, OperatorFixRequest, Origin, ParkCause,
54    QuotaLoss, ReviewRecord, ReviewRevoteRecord, ReviewRound, RunState, RunStatus, SeatHistory,
55    Tally, VoteRecord, summarize_verify, write_artifact,
56};
57use crate::verdict::{
58    self, FinalVote, Finding, FixReport, Position, Proposal, Ranking, Review, ReviewRevote,
59    ReviewVote, Severity,
60};
61
62/// Fixed commit message for graph-owned mechanical `verify.pre_gate` commits.
63pub const PRE_GATE_COMMIT_MESSAGE: &str = "magi: pre_gate (mechanical fixes)";
64
65/// Event node recorded by [`Runner::run_pre_gate`].
66pub(crate) const PRE_GATE_EVENT_NODE: &str = "pre_gate";
67
68/// Durable event text logged when [`Runner::run_pre_gate`] commits mechanical changes.
69pub(crate) fn pre_gate_commit_event(head: &str) -> String {
70    format!("committed mechanical fixes ({head})")
71}
72use crate::worktree_setup;
73
74/// Bytes of a failing command's output kept in an event, so the reason a run
75/// stopped is readable from the report without opening `run.json`.
76const EVENT_OUTPUT_TAIL: usize = 2_000;
77
78/// How often [`wait_for_timed_out_children_to_die`] re-checks a timed-out
79/// command's pid before releasing the build cache's lease.
80const LEASE_RELEASE_POLL: Duration = Duration::from_secs(1);
81
82/// The most [`wait_for_timed_out_children_to_die`] will wait for a timed-out
83/// command's pid to actually exit before giving up and releasing anyway.
84///
85/// A timeout means the process was asked to die (`kill_on_drop`,
86/// `start_kill`), not that it already has — on Windows in particular that can
87/// take a moment, the same reason `agent`'s own `PIPE_GRACE` exists. Releasing
88/// the instant the command returns would let the very next acquirer (this
89/// run's own next round, another run's verification, the janitor's prune)
90/// start touching the same directory while it might still be writing to it,
91/// so this polls the actual pid — real confirmation, not a fixed guess —
92/// until it is gone or this ceiling is reached. It is still not full
93/// process-tree reaping: a grandchild the timed-out process spawned and that
94/// outlives it independently is invisible to a pid check, and continuing to
95/// observe and collect *that* stays a different piece of work with its own
96/// owner. Set generously because the common case returns early the moment
97/// the pid is confirmed gone, not because every timeout pays this in full.
98const LEASE_RELEASE_MAX_WAIT: Duration = Duration::from_secs(30);
99
100/// Consecutive review rounds with no tree progress (see
101/// [`crate::run::ReviewRound::progressed`]) before `review_loop` hands off
102/// instead of spending the rest of the round budget.
103///
104/// Not 1: a single non-progressing round is not yet a pattern — a fixer that
105/// legitimately finds nothing left to change (its previous round's fix already
106/// covered it, and this round's reviewers re-raised only nits) looks the same
107/// as one that is spinning, for exactly one round. Two in a row is where the
108/// two stop being distinguishable, and a review round on this workload has
109/// been measured at 30-45 minutes of reviewer-plus-fixer agent time, so a
110/// third attempt at a tree that has not moved twice running is pure cost.
111/// This does not touch `review_rounds` itself, which stays the operator's
112/// call.
113pub(crate) const STAGNANT_LIMIT: usize = 2;
114
115/// How many times [`Runner::sync_to_base`] will re-land the winner's tree on
116/// a base that moved before giving up and leaving the run `Blocked` for a
117/// person.
118///
119/// Mirrors `land::Step::Rebase`'s budget and the reasoning behind it: a base
120/// that keeps moving faster than a run can catch it is not something more
121/// rebasing fixes, it is a person's call. Not the same *number as*
122/// `land_rounds` - this budget is spent before a pull request exists, land's
123/// after - but bounded for the identical reason, so it uses the same
124/// default. Counted across both call sites in [`Runner::finish_after_tally`]
125/// (once before review, once before the gate), because either one finding
126/// the base still moving is the same signal.
127pub(crate) const BASE_SYNC_ROUNDS: usize = 4;
128
129/// How many times [`Runner::continue_fix_report`] will resume the fixer's own
130/// seat when its CLI turn ended cleanly — usable, non-empty, exit 0 — but the
131/// reply held no [`FixReport`].
132///
133/// The shape this recovers: run 20260912-114326-d3b8's fix-2 came back
134/// `subtype=success`/`is_error=false`/`stop_reason=end_turn` with the reply
135/// "I'll pause here until the `cargo make check` background run reports
136/// back." — a CLI turn that ended cleanly while the fixer's own job had not.
137/// No `FixReport` was ever collected from that seat, and the run moved on to
138/// the next review round regardless.
139///
140/// Bounded independently of `review_rounds` and `graph.retries`: this
141/// recovers one seat's missing report mid-round, not a new round of review or
142/// an ordinary parse retry, and must not itself become the unbounded wait the
143/// rest of this module exists to avoid.
144const MAX_FIX_CONTINUATIONS: usize = 2;
145
146/// One queued agent invocation.
147///
148/// `Clone` so a node can keep the jobs it sent and re-send one: a seat whose
149/// CLI hung up on its own stream is asked again from the same job rather than
150/// rebuilt from scratch. See [`Runner::resume_undelivered`].
151#[derive(Clone)]
152struct SeatJob {
153    spec: AgentSpec,
154    seat: SeatState,
155    cwd: PathBuf,
156    prompt: String,
157    timeout: Duration,
158    allow_write: bool,
159    sessions: bool,
160    artifacts: PathBuf,
161    stem: String,
162    /// The prompt for a seat that has been handed to another roster agent
163    /// (a fresh session): everything the original seat would have
164    /// remembered. `None` when `prompt` already carries it, as the first
165    /// ranking and the implement prompt do. Never a resume-style prompt.
166    handover: Option<String>,
167}
168
169/// How the graph reads one agent invocation.
170///
171/// Quota is split out from an ordinary failure on purpose: a rate-limited call
172/// is known to fail again if retried now, so the retry loop must not spend an
173/// attempt on it. `Dropped` is split out for the opposite reason: unlike
174/// `Failed`, it is worth re-asking, and unlike `Ok`, its text is the CLI's raw
175/// error JSON, never the agent's answer — a caller that matched only
176/// `Ok`/`Quota`/`Failed` before `Dropped` existed must be updated rather than
177/// left to read that JSON as if it were usable output. `resume_undelivered`
178/// is the only caller that acts on it; everywhere else it is reported like an
179/// ordinary failure.
180enum AgentOutcome {
181    /// A usable output.
182    Ok(AgentOutput),
183    /// The CLI ran out of quota / rate limit. Retrying now is pointless.
184    Quota(AgentOutput),
185    /// The CLI hung up on its own stream after billed work. See
186    /// [`agent::AgentOutput::work_undelivered`].
187    Dropped(AgentOutput),
188    /// Any other failure: a timeout, a bad exit code, an empty reply.
189    Failed(String),
190    /// A resource prevented admission or interrupted execution. Not an agent
191    /// failure: never advance a fallback chain or spend an attempt on it.
192    /// Post-spawn interruptions carry a typed error into wave, which records
193    /// implementation preservation before returning this outcome. This outcome
194    /// alone is not proof that no source changes were made.
195    /// [`RunState::resource_block`] says why.
196    ResourceBlocked(String),
197}
198
199/// A request to park the run at its next node boundary.
200///
201/// Cloning is how the request travels: the loop keeps one handle and hands a
202/// clone to each [`Runner`], and every clone points at the same flag. There
203/// is no channel because there is nothing to send - the only message is
204/// "park", it is idempotent, and a flag cannot be missed by a receiver that
205/// was not listening yet.
206///
207/// The boundary is what makes this cheap. Every node writes the run's state
208/// before the next one starts, and every node skips what is already recorded:
209/// `prep` returns early once candidates exist, `implement` asks only the seats
210/// with nothing on disk, `judge` returns early once judgements exist. So a
211/// parked run resumes into exactly the node it stopped before, and no agent
212/// work is thrown away. Killing the process mid-node, by contrast, loses
213/// whatever the seats in flight had not yet written - which for an implement
214/// wave is an hour of paid work.
215///
216/// A [`Runner`] watches two independent handles of this type - see
217/// [`Runner::on_pause`] and [`Runner::watch_interrupt`] - never one shared
218/// between them. `magi serve`'s own shutdown (`Stop::park`) hands out one
219/// clone covering the whole daemon's lifetime and is never asked to un-park,
220/// which is correct exactly because nothing is dispatched after it fires.
221/// `magi serve`'s interrupt scheduler needs the opposite lifetime - a run
222/// that parks for an interrupted task must go on to run other tasks
223/// afterward - so it mints a fresh, unshared [`Pause`] per run instead of
224/// reusing the daemon-wide one.
225#[derive(Debug, Clone, Default)]
226pub struct Pause(Arc<AtomicBool>, Arc<Mutex<Option<ParkCause>>>);
227
228impl Pause {
229    /// A pause nobody has asked for yet.
230    #[must_use]
231    pub fn new() -> Self {
232        Self::default()
233    }
234
235    /// Ask the run to park at its next node boundary. Idempotent.
236    pub fn park(&self) {
237        self.0.store(true, Ordering::SeqCst);
238    }
239
240    /// Same as [`Pause::park`], but records why, for [`Runner::park_here`] to
241    /// fold into the run's own `park` event - so an operator reading the run
242    /// later knows this was a deliberate interrupt rather than a shutdown or
243    /// a binary swap. The first reason recorded wins; a park already in
244    /// flight is not relabelled by a second, unrelated request.
245    pub fn park_because(&self, reason: impl Into<String>) {
246        self.park_for(ParkCause::Interrupt {
247            reason: reason.into(),
248        });
249    }
250
251    /// [`Pause::park`], recording the structured cause. The first cause
252    /// recorded wins, like [`Pause::park_because`].
253    pub fn park_for(&self, cause: ParkCause) {
254        let mut reason_guard = self
255            .1
256            .lock()
257            .unwrap_or_else(std::sync::PoisonError::into_inner);
258        if reason_guard.is_none() {
259            *reason_guard = Some(cause);
260        }
261        drop(reason_guard);
262        self.park();
263    }
264
265    /// Has a park been asked for?
266    #[must_use]
267    pub fn parked(&self) -> bool {
268        self.0.load(Ordering::SeqCst)
269    }
270
271    /// Why the park was asked for, when the caller used [`Pause::park_because`].
272    #[must_use]
273    pub fn reason(&self) -> Option<String> {
274        self.cause().map(|c| c.label())
275    }
276
277    /// The structured cause, when one was recorded.
278    #[must_use]
279    pub fn cause(&self) -> Option<ParkCause> {
280        self.1
281            .lock()
282            .unwrap_or_else(std::sync::PoisonError::into_inner)
283            .clone()
284    }
285}
286
287/// Drives one run.
288pub struct Runner {
289    /// Run state; public so the CLI can report on it.
290    pub state: RunState,
291    roles: ResolvedRoles,
292    sem: Arc<Semaphore>,
293    /// Set when the daemon's own shutdown (Ctrl-C, a binary swap) wants the
294    /// run parked at its next node boundary. See [`Pause`]'s own doc for why
295    /// this is never the same handle as `interrupt`.
296    pause: Pause,
297    /// Set when `magi serve`'s interrupt scheduler wants this specific run
298    /// parked at its next node boundary, to let a task marked
299    /// [`crate::queue::Task::interrupt`] run alone before this one carries
300    /// on. Unlike `pause`, a fresh, unshared handle per run - see
301    /// [`Runner::watch_interrupt`].
302    interrupt: Pause,
303}
304
305/// Where the branch's own commits start: its merge base with the base branch
306/// as the remote has it now, else with the recorded `base_commit`. A branch
307/// rebased onto a base that moved past `base_commit` would otherwise count
308/// the base's commits as its own under `base_commit..branch`.
309async fn review_base(
310    repo: &Path,
311    remote: &str,
312    base_branch: &str,
313    base_commit: &str,
314    branch: &str,
315) -> String {
316    review_base_checked(repo, remote, base_branch, base_commit, branch)
317        .await
318        .0
319}
320
321/// [`review_base`] plus whether the base was read from a freshly fetched
322/// tracking ref. A failed fetch still uses whatever tracking ref exists (it is
323/// never older than `base_commit`'s view of the base), but the answer is then
324/// not trusted to rewrite a pull request's title.
325async fn review_base_checked(
326    repo: &Path,
327    remote: &str,
328    base_branch: &str,
329    base_commit: &str,
330    branch: &str,
331) -> (String, bool) {
332    let tracking = format!("{remote}/{base_branch}");
333    let fresh = matches!(git::fetch(repo, remote, base_branch).await, Ok(o) if o.ok());
334    if git::rev_exists(repo, &tracking).await
335        && let Ok(mb) = git::merge_base(repo, &tracking, branch).await
336        && !mb.is_empty()
337    {
338        return (mb, fresh);
339    }
340    let mb = git::merge_base(repo, base_commit, branch)
341        .await
342        .ok()
343        .filter(|mb| !mb.is_empty())
344        .unwrap_or_else(|| base_commit.to_owned());
345    (mb, false)
346}
347
348/// Recompute `reviewed_commits` from the branch's own commits. Left as it was
349/// when git cannot say or finds nothing: a stale list is better than a wrong
350/// or empty one.
351pub(crate) async fn refresh_reviewed_commits(state: &mut RunState, branch: &str) {
352    if !is_review_run(state) {
353        return;
354    }
355    let base = review_base(
356        &state.repo,
357        &state.config.merge.remote,
358        &state.base_branch,
359        &state.base_commit,
360        branch,
361    )
362    .await;
363    if let Ok(subjects) = git::subjects(&state.repo, &base, branch).await
364        && !subjects.is_empty()
365        && state.reviewed_commits.as_ref() != Some(&subjects)
366    {
367        state.reviewed_commits = Some(subjects);
368        state.save().ok();
369    }
370}
371
372/// Subjects of the base's commits between the recorded start and the branch's
373/// merge base: what a stale `base_commit..branch` would have mistaken for the
374/// branch's own work.
375async fn leaked_subjects(state: &RunState, branch: &str) -> Option<Vec<String>> {
376    let (base, trusted) = review_base_checked(
377        &state.repo,
378        &state.config.merge.remote,
379        &state.base_branch,
380        &state.base_commit,
381        branch,
382    )
383    .await;
384    if !trusted {
385        return None;
386    }
387    git::subjects(&state.repo, &state.base_commit, &base)
388        .await
389        .ok()
390}
391
392/// May an adopted pull request's title be replaced with `computed`? Only when
393/// it is empty, magi's own shape, or a base commit's subject that leaked in;
394/// a title a person wrote stays. Never when `computed` is itself a leak.
395pub(crate) fn should_retitle(current: &str, computed: &str, leaked: &[String]) -> bool {
396    let is_leak = |t: &str| leaked.iter().any(|l| l.trim() == t.trim());
397    if is_leak(computed) {
398        return false;
399    }
400    let cur = current.trim();
401    cur.is_empty()
402        || cur.starts_with(REVIEW_PROMPT_OPENING)
403        || cur.starts_with("chore: land candidate")
404        || cur.starts_with("magi: candidate")
405        || is_leak(cur)
406}
407
408/// The commit a run branches from: the base branch as the remote has it.
409///
410/// Two failures this replaces. A run used to branch off `HEAD` and so refused
411/// to start on a dirty tree, which made `magi serve` decline every task for as
412/// long as the operator had work in progress - most of the time. Branching off
413/// the *local* base branch fixed that and introduced a worse one: `land` merges
414/// the winner on GitHub, nothing updates the local ref, and the next run
415/// branches off a base missing everything the previous runs landed. Two tasks
416/// in a row from a phone would have had the second silently re-implementing
417/// against stale code and opening a pull request that reverted the first.
418///
419/// Only refs move here - no checkout, no local branch, no merge - so it is safe
420/// with uncommitted work in the tree. A machine with no network still starts:
421/// the fetch may fail and the local tip is used with a warning, because
422/// refusing to run offline is a worse failure than running against a base the
423/// operator can see for themselves.
424///
425/// One function, called by both entry points. Two answers to "where does a run
426/// branch from" is the kind of drift nobody notices until a diff is wrong.
427/// Bring the local `branch` in line with `<remote>/<branch>` before a review
428/// checks it out.
429///
430/// `git worktree add <branch>` resolves the *local* ref, and a branch pushed by
431/// anything other than plain `git push` from this checkout (a jj colocated
432/// workspace, another clone) moves only the remote-tracking ref - so the local
433/// one can be a stale placeholder. It moves only when local is behind the remote or is an
434/// empty placeholder that diverged from it; unpushed local work is kept, and a real
435/// divergence is refused rather than guessed at.
436async fn sync_review_branch(repo: &Path, branch: &str, remote: &str, base: &str) -> Result<()> {
437    let tracking = format!("{remote}/{branch}");
438    let fetched = git::fetch(repo, remote, branch).await;
439    let fresh = matches!(&fetched, Ok(o) if o.ok()) && git::rev_exists(repo, &tracking).await;
440    let local_exists = git::branch_exists(repo, branch).await?;
441    if !fresh {
442        if !local_exists {
443            bail!("no branch `{branch}` in {} or on {remote}", repo.display());
444        }
445        tracing::warn!(
446            "could not read {tracking}; reviewing the local `{branch}`, which may be stale"
447        );
448        return Ok(());
449    }
450    let remote_sha = git::rev_parse(repo, &tracking).await?;
451    if !local_exists {
452        git::git(repo, &["branch", branch, &tracking]).await?;
453        return Ok(());
454    }
455    let local_sha = git::rev_parse(repo, &format!("refs/heads/{branch}")).await?;
456    if local_sha == remote_sha || git::is_ancestor(repo, &remote_sha, &local_sha).await {
457        return Ok(());
458    }
459    if !git::is_ancestor(repo, &local_sha, &remote_sha).await {
460        // Diverged. `reconcile` settles it only when it can prove nothing is
461        // lost: a local tip that is the remote's change rebased is pushed over
462        // it (lease pinned to the tip read here), a tip whose every extra
463        // commit is empty is a placeholder the remote's work replaced, and
464        // anything else is two different changes - a question for a person.
465        match crate::reconcile::reconcile(repo, remote, branch, &local_sha, &remote_sha, base)
466            .await?
467        {
468            crate::reconcile::Reconciliation::Pushed => {
469                tracing::warn!(
470                    "local `{branch}` ({}) is {tracking} ({}) rebased; pushed it over",
471                    short(&local_sha),
472                    short(&remote_sha)
473                );
474                return Ok(());
475            }
476            crate::reconcile::Reconciliation::Placeholder => {}
477            crate::reconcile::Reconciliation::Genuine(d) => return Err((*d).into()),
478        }
479    }
480    let out = git::git_raw(repo, &["branch", "-f", branch, &tracking]).await?;
481    if !out.ok() {
482        bail!(
483            "local `{branch}` ({}) is stale against {tracking} ({}) but git will not move it: {}",
484            short(&local_sha),
485            short(&remote_sha),
486            out.stderr
487        );
488    }
489    tracing::warn!(
490        "local `{branch}` was stale: fast-forwarded {} -> {}",
491        short(&local_sha),
492        short(&remote_sha)
493    );
494    Ok(())
495}
496
497async fn resolve_base(
498    repo: &Path,
499    base_branch: &str,
500    remote: &str,
501    coordination: Option<&crate::config::Coordination>,
502) -> Result<crate::run::FetchedBase> {
503    let _lease = crate::repo_lock::SeatLease::operation_with(
504        repo,
505        coordination,
506        &crate::repo_lock::WaitPolicy::current(),
507    )
508    .await?;
509    let tracking = format!("{remote}/{base_branch}");
510    let fetched = git::fetch(repo, remote, base_branch).await;
511    if let Ok(out) = &fetched
512        && out.ok()
513        && git::rev_exists(repo, &tracking).await
514    {
515        return Ok(crate::run::FetchedBase {
516            remote: remote.to_owned(),
517            branch: base_branch.to_owned(),
518            commit: git::rev_parse(repo, &tracking).await?,
519            fetched_at: jiff::Timestamp::now(),
520        });
521    }
522    let why = match &fetched {
523        Ok(out) if !out.ok() => out.stderr.trim().to_owned(),
524        Ok(_) => format!("{remote} has no {base_branch}"),
525        Err(e) => e.to_string(),
526    };
527    // No fallback to the local branch: it may be behind, and branching off an
528    // old commit is the stale-checkout bug this check exists to prevent.
529    bail!(
530        "cannot read {tracking} ({why}); refusing to branch off the local \
531         `{base_branch}`, which may be behind. Fix the remote, or set [merge] \
532         base / remote in magi.toml. This is launcher preparation: check the \
533         launcher's network, Git access and repository coordination before \
534         retrying"
535    )
536}
537
538/// Outcome of the shared fixer chain, before caller-owned stop policy.
539enum FixStep {
540    Resource,
541    Recorded { report_lost: bool },
542}
543
544/// Exclusive claim shared by targeted repairs and repository reassignment.
545/// Held before asynchronous fix preflight and released on every return or panic.
546///
547/// `daemon::is_working_on` only sees a heartbeat-publishing daemon; two
548/// manual `magi fix` invocations against the same run are otherwise
549/// invisible to each other and would race to remove and recreate the same
550/// worktree (see [`Runner::fix_selected`]). The lock file itself is the same
551/// `create_new` shape as `queue::Claim`, but unlike a queued task's lock —
552/// which is only ever reclaimed later, out of band, by
553/// `daemon::sweep_stale_claims` running inside `magi serve`/`magi web` — a
554/// `magi fix` invocation is not necessarily running under either of those, so
555/// nothing would ever sweep a lock a killed or crashed process left behind.
556/// [`Self::acquire`] therefore reclaims a stale lock itself, on the same
557/// conservative PID-liveness policy `sweep_stale_claims` and `cache`'s own
558/// lease use: an unreadable or unparsable pid, or a liveness query the
559/// platform cannot answer, reads as alive and the lock is left in place.
560pub(crate) struct FixClaim {
561    path: PathBuf,
562}
563
564impl FixClaim {
565    pub(crate) fn acquire(dir: &Path) -> Result<Self> {
566        std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
567        let path = dir.join("fix.lock");
568        let retry = crate::lock_file::Retry::new(None);
569        match Self::create(&path, retry) {
570            Ok(claim) => Ok(claim),
571            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
572                if Self::reclaim_if_dead(&path) {
573                    Self::create(&path, retry).with_context(|| format!("lock {}", path.display()))
574                } else {
575                    bail!(
576                        "another repair or `magi fix` is already running for this run ({} exists)",
577                        path.display()
578                    )
579                }
580            }
581            Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
582        }
583    }
584
585    fn create(path: &Path, retry: crate::lock_file::Retry) -> std::io::Result<Self> {
586        let mut f = retry.create(path)?;
587        use std::io::Write as _;
588        // Read back by `reclaim_if_dead` on a later, stuck invocation.
589        writeln!(f, "{}", std::process::id())?;
590        Ok(Self {
591            path: path.to_owned(),
592        })
593    }
594
595    /// True if the lock named a process confirmed dead, in which case it was
596    /// also removed. Never true on an unreadable file, an unparsable pid, or
597    /// a liveness query the platform cannot answer — see this type's own doc.
598    fn reclaim_if_dead(path: &Path) -> bool {
599        let dead = std::fs::read_to_string(path)
600            .ok()
601            .and_then(|body| body.trim().parse::<u32>().ok())
602            .is_some_and(|pid| !crate::proc::pid_alive(pid));
603        dead && std::fs::remove_file(path).is_ok()
604    }
605}
606
607impl Drop for FixClaim {
608    fn drop(&mut self) {
609        let _ = std::fs::remove_file(&self.path);
610    }
611}
612
613#[doc(hidden)]
614pub struct ExecutionLeaseGuard {
615    _lease: crate::driver::ExecutionLease,
616}
617
618#[doc(hidden)]
619pub fn hold_execution_lease_for_test(home: &Path, run_id: &str) -> Result<ExecutionLeaseGuard> {
620    Ok(ExecutionLeaseGuard {
621        _lease: crate::driver::maintenance(home, run_id)?,
622    })
623}
624
625/// Holds the mutable runner as well as its durable lease: cancellation must
626/// clear both copies of ownership, including state a caller may save later.
627struct DriverExecution<'a> {
628    runner: &'a mut Runner,
629    driver: crate::driver::DriverGuard,
630}
631
632impl Drop for DriverExecution<'_> {
633    fn drop(&mut self) {
634        self.driver.release_local(&mut self.runner.state);
635    }
636}
637
638fn startup_stage(state: &mut RunState, stage: &str) -> Result<()> {
639    if let Some(startup) = &mut state.startup {
640        startup.stage = stage.to_owned();
641    }
642    state.save()
643}
644
645/// Keep a reservation visible as blocked until startup finishes. A killed process
646/// leaves the same explicit incomplete marker; dropping a cancelled future records it.
647struct StartupGuard {
648    id: String,
649    armed: bool,
650}
651
652impl StartupGuard {
653    fn reserve(state: &mut RunState, kind: &str, branch: Option<&str>) -> Result<Self> {
654        state.startup = Some(crate::run::Startup {
655            kind: kind.to_owned(),
656            branch: branch.map(str::to_owned),
657            stage: "reserved".to_owned(),
658            complete: false,
659            failure: None,
660        });
661        state.status = RunStatus::Blocked;
662        state.reserve()?;
663        Ok(Self {
664            id: state.id.clone(),
665            armed: true,
666        })
667    }
668
669    fn stage(&self, state: &mut RunState, stage: &str) -> Result<()> {
670        startup_stage(state, stage)
671    }
672
673    fn finish(mut self, state: &mut RunState, result: Result<()>) -> Result<()> {
674        let result = result.and_then(|()| {
675            state.startup.as_mut().expect("reserved startup").complete = true;
676            state.save()
677        });
678        self.armed = false;
679        match result {
680            Ok(()) => Ok(()),
681            Err(error) => {
682                let startup = state.startup.as_mut().expect("reserved startup");
683                startup.complete = false;
684                startup.failure = Some(format!("{error:#}"));
685                let context = crate::run::StartupFailure {
686                    run: state.id.clone(),
687                    stage: startup.stage.clone(),
688                };
689                // Repository assets may remain. Never infer that a failed startup
690                // is safe to resume or that an earlier owner has been restored.
691                state.status = RunStatus::Failed;
692                state.driver_exited = true;
693                state.event(
694                    "startup-failed",
695                    format!("{context}: {error:#}; retained assets require inspection"),
696                );
697                if let Err(save) = state.save() {
698                    tracing::warn!(
699                        "run {}: could not save terminal startup record: {save:#}; reservation requires reconciliation",
700                        state.id
701                    );
702                }
703                Err(error.context(context))
704            }
705        }
706    }
707}
708
709impl Drop for StartupGuard {
710    fn drop(&mut self) {
711        if self.armed
712            && let Ok(mut state) = RunState::load(&self.id)
713        {
714            state.status = RunStatus::Blocked;
715            state.driver_exited = true;
716            if let Some(startup) = &mut state.startup {
717                startup.failure = Some("startup interrupted; reconciliation required".to_owned());
718            }
719            state.event(
720                "startup-interrupted",
721                "startup did not finish; inspect retained assets before recovery",
722            );
723            if let Err(error) = state.save() {
724                tracing::error!(
725                    "could not record interrupted startup {}: {error:#}",
726                    self.id
727                );
728            }
729        }
730    }
731}
732
733impl Runner {
734    /// A queue-side failure after construction must not strand an unexecuted run.
735    pub(crate) fn fail_startup(&mut self, stage: &str, error: anyhow::Error) -> anyhow::Error {
736        if !self.state.passes.is_empty() || self.state.driver_claimed != Some(false) {
737            return error;
738        }
739        if let Some(startup) = &mut self.state.startup {
740            startup.stage = stage.to_owned();
741        } else {
742            // A resumed run already has execution history: do not rewrite it.
743            return error;
744        }
745        StartupGuard {
746            id: self.state.id.clone(),
747            armed: true,
748        }
749        .finish(&mut self.state, Err(error))
750        .expect_err("startup failed")
751    }
752
753    /// Start a fresh run against `repo`.
754    pub async fn start(
755        repo: &Path,
756        instruction: String,
757        config: Config,
758        origin: Origin,
759    ) -> Result<Self> {
760        Self::start_naming(repo, instruction, "", config, origin).await
761    }
762
763    /// [`Runner::start`] for a queued task. Titles and instructions never
764    /// select implementation sources. The title argument is retained for callers.
765    pub async fn start_naming(
766        repo: &Path,
767        instruction: String,
768        _also_scan: &str,
769        config: Config,
770        origin: Origin,
771    ) -> Result<Self> {
772        let repo = git::toplevel(repo).await?;
773        let missing = agent::missing_programs(&config.agents);
774        if !missing.is_empty() {
775            bail!(
776                "these agent programs are not on PATH: {}. Fix the roster in \
777                 magi.toml or install them.",
778                missing.join(", ")
779            );
780        }
781        let base_branch =
782            git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
783                .await?;
784        let fetched_base = resolve_base(
785            &repo,
786            &base_branch,
787            &config.merge.remote,
788            config.coordination.as_ref(),
789        )
790        .await?;
791        let base_commit = fetched_base.commit.clone();
792        let roles = config.resolve_roles()?;
793        let max_parallel = config.graph.max_parallel.max(1);
794        let mut state = RunState::new(repo, base_branch, base_commit, instruction, config);
795        // Capture task identity and repository assignment before the first
796        // save, so publication scope survives crashes and later task moves.
797        state.fetched_base = Some(fetched_base);
798        state.set_origin(origin)?;
799        let startup = StartupGuard::reserve(&mut state, "implementation", None)?;
800        state.status = RunStatus::Prep;
801        state.event("start", format!("run {} created", state.id));
802        startup.finish(&mut state, Ok(()))?;
803        Ok(Self {
804            state,
805            roles,
806            sem: Arc::new(Semaphore::new(max_parallel)),
807            pause: Pause::new(),
808            interrupt: Pause::new(),
809        })
810    }
811
812    /// Open a review-only run against work that already exists on `branch`.
813    ///
814    /// The expensive half of the graph is the implement wave — measured at
815    /// 111 and 134 internal tool-loop turns on this repository, against a
816    /// handful for a judge or a reviewer. The cheap half is worth running on
817    /// hand-written work too, and there was no way to reach it.
818    ///
819    /// No new state and no schema change are needed: a run with **one** viable
820    /// candidate and a tally already decided degrades `execute` to exactly
821    /// review → gate → merge, because `judge` skips a single-candidate field,
822    /// `deliberate` has fewer than two first choices to reconcile, `vote`
823    /// returns early, `tally` is already present and `fold_losers` has no
824    /// losers. Resuming such a run therefore does the right thing as well.
825    pub async fn review(repo: &Path, branch: &str, config: Config, origin: Origin) -> Result<Self> {
826        Self::review_taking_over(repo, branch, config, None, origin).await
827    }
828
829    /// [`Runner::review`] for a queued task's retry: when an earlier attempt
830    /// at the same task still has `branch` checked out, its worktree is
831    /// released first if that is safe (see [`crate::handover`]), and the
832    /// review refuses with the reason if it is not. `None` is a hand-run
833    /// review: it has no earlier attempts, so only a worktree of a dead run
834    /// magi recorded itself can be released.
835    pub async fn review_taking_over(
836        repo: &Path,
837        branch: &str,
838        config: Config,
839        takeover: Option<crate::handover::Takeover>,
840        origin: Origin,
841    ) -> Result<Self> {
842        let repo = git::toplevel(repo).await?;
843        let missing = agent::missing_programs(&config.agents);
844        if !missing.is_empty() {
845            bail!(
846                "these agent programs are not on PATH: {}. Fix the roster in \
847                 magi.toml or install them.",
848                missing.join(", ")
849            );
850        }
851        let base_branch =
852            git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
853                .await?;
854        if base_branch == branch {
855            bail!("`{branch}` is the base branch; there is nothing to review against");
856        }
857        let fetched_base = resolve_base(
858            &repo,
859            &base_branch,
860            &config.merge.remote,
861            config.coordination.as_ref(),
862        )
863        .await?;
864        let base_commit = fetched_base.commit.clone();
865
866        let roles = config.resolve_roles()?;
867        let max_parallel = config.graph.max_parallel.max(1);
868        let mut state = RunState::new(
869            repo.clone(),
870            base_branch,
871            base_commit.clone(),
872            format!("Review the work already on branch `{branch}`."),
873            config,
874        );
875        state.fetched_base = Some(fetched_base);
876        state.set_origin(origin)?;
877        state.task_instruction = takeover.as_ref().and_then(|t| t.task_instruction.clone());
878        let startup = StartupGuard::reserve(&mut state, "review", Some(branch))?;
879        let opened = async {
880            startup.stage(&mut state, "handover")?;
881
882            // Released before anything else touches the branch: a stale local
883            // branch is moved with `git branch -f`, which git refuses while an
884            // earlier attempt's worktree still has it checked out. Everything
885            // after this point that can fail puts the old run back.
886            // A hand-run review has no task, hence no earlier attempts, but a
887            // worktree of a dead run magi made may still be released.
888            let takeover = takeover.unwrap_or_else(|| crate::handover::Takeover {
889                earlier: Vec::new(),
890                home: crate::run::home(),
891                choice: None,
892                task_instruction: None,
893            });
894            let wait = repository_wait(&state, None);
895            let coordination_config = state.config.coordination.clone();
896            let coordination =
897                crate::repo_lock::SeatLease::operation_with(&repo, coordination_config.as_ref(), &wait)
898                    .await?;
899            let released = crate::handover::release(&repo, branch, &state.id, &takeover).await?;
900            if let Some(released) = &released {
901                state.event(
902                    "release",
903                    format!(
904                        "took `{branch}` over from run {}: its worktree was released: {}",
905                        crate::run::short_of(&released.old_id),
906                        released.audit
907                    ),
908                );
909            }
910            let opened = async {
911                startup.stage(&mut state, "review-preflight")?;
912                // The owner's answer to an earlier divergence question is applied
913                // here: after the release (git will not move a checked-out branch)
914                // and before the sync that would otherwise ask again.
915                state.foreign_checkout = crate::handover::preflight_review(
916                    &repo,
917                    branch,
918                    &takeover.home,
919                    &state.config.merge.remote,
920                )
921                .await?;
922                if state.foreign_checkout.is_some() && takeover.choice.is_some() {
923                    bail!("cannot reconcile a foreign checkout automatically; resolve its branch first");
924                }
925                if let Some(choice) = takeover.choice.as_ref()
926                    && let Err(e) =
927                        crate::reconcile::apply_choice(&repo, &state.config.merge.remote, branch, choice)
928                            .await
929                {
930                    return Err(e.context("applying the owner's answer about the diverged branch"));
931                }
932                // An earlier attempt of this task that published the task head, and
933                // whose work is the branch under review, hands that head over: the
934                // review run updates the same pull request. Without one (a legacy
935                // `magi/<run>/<label>` PR, a hand-named branch) the branch keeps its
936                // own head and its own open pull request is adopted as before.
937                for id in takeover.earlier.iter().rev() {
938                    if let Ok(old) = RunState::load_under(id, &takeover.home)
939                        && let Some(head) = old.pr_head.clone()
940                        && (head == branch || old.winner().is_some_and(|w| w.branch == branch))
941                    {
942                        state.pr_head = Some(head);
943                        break;
944                    }
945                }
946                drop(coordination);
947                startup.stage(&mut state, "open-review")?;
948                Self::open_review(&repo, branch, &mut state, base_commit, &takeover).await
949            }
950            .await;
951            if opened.is_err()
952                && let Some(released) = &released
953            {
954                // Restoration is ownership checked and best effort. Keep the original
955                // startup cause even if reacquiring coordination is no longer possible.
956                match crate::repo_lock::SeatLease::operation_with(
957                    &repo,
958                    coordination_config.as_ref(),
959                    &wait,
960                )
961                .await
962                {
963                    Ok(_coordination) => {
964                        released.restore(&repo, branch).await;
965                        let outcome = RunState::load_under(&released.old_id, &takeover.home)
966                            .map(|old| {
967                                format!(
968                                    "predecessor released_to={:?}; candidate path exists={}",
969                                    old.released_to,
970                                    old.candidates.iter().any(|c| {
971                                        c.branch == branch && c.worktree.exists()
972                                    }),
973                                )
974                            })
975                            .unwrap_or_else(|error| format!("predecessor could not be inspected: {error:#}"));
976                        state.event("startup-restore", format!("ownership-checked restoration attempted: {outcome}; retained successor assets require inspection"));
977                    }
978                    Err(error) => {
979                        tracing::warn!(
980                            "run {}: could not take the repository lease to restore `{branch}`: {error:#}",
981                            state.id
982                        );
983                        state.event(
984                            "startup-restore",
985                            format!("restoration not attempted: {error:#}"),
986                        );
987                    }
988                }
989            }
990            opened
991        }
992        .await;
993        startup.finish(&mut state, opened)?;
994        Ok(Self {
995            state,
996            roles,
997            sem: Arc::new(Semaphore::new(max_parallel)),
998            pause: Pause::new(),
999            interrupt: Pause::new(),
1000        })
1001    }
1002
1003    /// Recover exactly the operator-selected public implementation, without touching old sources.
1004    pub async fn recover_pr(
1005        repo: &Path,
1006        task: &str,
1007        selection: crate::pr_recovery::Selection,
1008        mut config: Config,
1009    ) -> Result<Self> {
1010        selection.configure(&mut config)?;
1011        let assignment = crate::run::task_assignment_for(task)?;
1012        selection.check_task_assignment(task, &selection.instruction, assignment)?;
1013        let base_branch =
1014            git::merge_base_branch(repo, &config.merge.remote, config.merge.base.as_deref())
1015                .await?;
1016        let fetched_base = resolve_base(
1017            repo,
1018            &base_branch,
1019            &config.merge.remote,
1020            config.coordination.as_ref(),
1021        )
1022        .await?;
1023        let base_commit = fetched_base.commit.clone();
1024        selection
1025            .verify(repo, &config.merge.remote, &base_branch, &selection.head)
1026            .await?;
1027        Box::pin(selection.verify_source(repo)).await?;
1028        if let Some(proof) = &selection.source_proof {
1029            anyhow::ensure!(
1030                git::is_ancestor(repo, &proof.new_base, &base_commit).await,
1031                "source rebase base is outside the fetched landing base"
1032            );
1033        }
1034        let roles = config.resolve_roles()?;
1035        let max_parallel = config.graph.max_parallel.max(1);
1036        let mut state = RunState::new(
1037            repo.to_path_buf(),
1038            base_branch,
1039            base_commit.clone(),
1040            selection.instruction.clone(),
1041            config,
1042        );
1043        state.fetched_base = Some(fetched_base);
1044        state.set_origin(crate::run::Origin::queue(task))?;
1045        state.pr_head = Some(selection.branch.clone());
1046        state.pr_recovery = Some(selection.clone());
1047        Self::open_selected(repo, state, roles, max_parallel, base_commit, selection).await
1048    }
1049
1050    async fn open_selected(
1051        repo: &Path,
1052        mut state: RunState,
1053        roles: ResolvedRoles,
1054        max_parallel: usize,
1055        base_commit: String,
1056        selection: crate::pr_recovery::Selection,
1057    ) -> Result<Self> {
1058        let startup = StartupGuard::reserve(&mut state, "pr-recovery", Some(&selection.branch))?;
1059        let opened = async {
1060            startup.stage(&mut state, "predecessors")?;
1061            crate::pr_head::check_predecessors(&state, &selection.branch).await?;
1062            startup.stage(&mut state, "open-selected")?;
1063            let branch = state.branch_for('A');
1064            let wait = repository_wait(&state, None);
1065            let prepared = async {
1066                let coordination = coordinate_operation(&mut state, repo, &wait).await?;
1067                git::git(repo, &["branch", &branch, selection.source()]).await?;
1068                drop(coordination);
1069                anyhow::Ok(())
1070            }
1071            .await;
1072            prepared?;
1073            state.event(
1074                "recovery",
1075                format!(
1076                    "selected implementation {} for {} (public lease {})",
1077                    selection.source(),
1078                    selection.url,
1079                    selection.head
1080                ),
1081            );
1082            let takeover = crate::handover::Takeover {
1083                earlier: Vec::new(),
1084                home: crate::run::home(),
1085                choice: None,
1086                task_instruction: Some(selection.instruction.clone()),
1087            };
1088            state.save()?;
1089            Self::open_review(repo, &branch, &mut state, base_commit, &takeover).await
1090        }
1091        .await;
1092        startup.finish(&mut state, opened)?;
1093        Ok(Self {
1094            state,
1095            roles,
1096            sem: Arc::new(Semaphore::new(max_parallel)),
1097            pause: Pause::new(),
1098            interrupt: Pause::new(),
1099        })
1100    }
1101
1102    /// What the newest earlier attempt that reviewed `branch` leaves for this
1103    /// run (see [`crate::recovery`]). `None` for a hand-run review, which has
1104    /// no earlier attempts. Reads the earlier record only: ownership of its
1105    /// worktree and branch is [`crate::handover`]'s business.
1106    async fn inherit(
1107        repo: &Path,
1108        branch: &str,
1109        base_commit: &str,
1110        takeover: &crate::handover::Takeover,
1111    ) -> Option<crate::recovery::RecoveryRecord> {
1112        use crate::recovery::{Relation, assess};
1113        let newest = takeover.earlier.last()?;
1114        let mut chosen = None;
1115        for id in takeover.earlier.iter().rev() {
1116            if let Ok(old) = RunState::load_under(id, &takeover.home)
1117                && !old.reviews.is_empty()
1118                && (old.winner().is_some_and(|w| w.branch == branch)
1119                    || old.pr_head.as_deref() == Some(branch))
1120            {
1121                chosen = Some(old);
1122                break;
1123            }
1124        }
1125        let tip = git::rev_parse(repo, &format!("refs/heads/{branch}"))
1126            .await
1127            .unwrap_or_default();
1128        let relation = match chosen.as_ref().and_then(|o| o.reviews.last()) {
1129            Some(last) if last.head == tip => Relation::Same,
1130            Some(last) if git::is_ancestor(repo, &last.head, &tip).await => Relation::Descendant,
1131            _ => Relation::Diverged,
1132        };
1133        let from = chosen.as_ref().map_or(newest.as_str(), |o| o.id.as_str());
1134        Some(assess(from, chosen.as_ref(), base_commit, relation))
1135    }
1136
1137    /// The half of [`Runner::review_taking_over`] that can fail after an
1138    /// earlier attempt's worktree was released.
1139    async fn open_review(
1140        repo: &Path,
1141        branch: &str,
1142        state: &mut RunState,
1143        base_commit: String,
1144        takeover: &crate::handover::Takeover,
1145    ) -> Result<()> {
1146        startup_stage(state, "review-sync")?;
1147        let wait = repository_wait(state, None);
1148        let _coordination = coordinate_operation(state, repo, &wait).await?;
1149        if state.foreign_checkout.is_some() {
1150            // Never reconcile or force-move a ref checked out by the operator.
1151            if state.pr_head.is_none() {
1152                state.pr_head = Some(branch.to_owned());
1153            }
1154        } else if state.pr_recovery.is_none() {
1155            sync_review_branch(repo, branch, &state.config.merge.remote, &base_commit).await?;
1156        }
1157        // The commit subjects are the closest thing to a task statement that
1158        // existing work carries, and the reviewers are told as much.
1159        let start = review_base(
1160            repo,
1161            &state.config.merge.remote,
1162            &state.base_branch,
1163            &base_commit,
1164            branch,
1165        )
1166        .await;
1167        let log = git::log_oneline(repo, &start, branch)
1168            .await
1169            .unwrap_or_default();
1170        let log_text = if log.trim().is_empty() {
1171            "(no commit messages)"
1172        } else {
1173            log.trim()
1174        };
1175        let mut instruction = format!(
1176            "Review the work already on branch `{branch}`. There is no task \
1177             statement: what the change claims to do is whatever its commits \
1178             say.\n\n{log_text}"
1179        );
1180        // A retry of a task whose earlier attempt left reviews behind carries
1181        // that attempt's evidence, and the task's own statement with it: the
1182        // completion criteria are the task's, not whatever the commits claim.
1183        if let Some(mut rec) = Self::inherit(repo, branch, &base_commit, takeover).await {
1184            if let Some(task) = takeover
1185                .task_instruction
1186                .as_deref()
1187                .filter(|t| !t.trim().is_empty())
1188                && rec.reviewed_head.is_some()
1189            {
1190                instruction = format!(
1191                    "{}\n\n# Work already on branch `{branch}` (commit subjects)\n\n{log_text}",
1192                    task.trim()
1193                );
1194                rec.criteria_inherited = true;
1195            }
1196            state.event("recovery", rec.summary());
1197            state.recovery = Some(rec);
1198        }
1199        if let Some(selected) = &state.pr_recovery {
1200            instruction = selected.instruction.clone();
1201        }
1202        state.task_instruction = takeover.task_instruction.clone();
1203        state.instruction = instruction;
1204        state.reviewed_commits = Some(
1205            git::subjects(repo, &start, branch)
1206                .await
1207                .unwrap_or_default(),
1208        );
1209
1210        // A takeover must not forget a hold that a previous review observed,
1211        // even if repairs have since removed it from the branch.
1212        for id in &takeover.earlier {
1213            if let Ok(old) = RunState::load_under(id, &takeover.home)
1214                && old.repo == state.repo
1215                && (old.pr_head.as_deref() == Some(branch)
1216                    || old.winner().is_some_and(|w| w.branch == branch))
1217            {
1218                for hold in old.branch_owner_holds {
1219                    if !state.branch_owner_holds.contains(&hold) {
1220                        state.event(
1221                            "approval-policy",
1222                            format!(
1223                                "inherited {}=true from the reviewed branch's {} at {} (run {id})",
1224                                hold.control.key(),
1225                                hold.file,
1226                                hold.head
1227                            ),
1228                        );
1229                        state.branch_owner_holds.push(hold);
1230                    }
1231                }
1232            }
1233        }
1234        // Select the actual review tip before observing owner policy. A foreign
1235        // checkout can lag its remote descendant, and repairs must not erase
1236        // holds introduced only on that selected commit.
1237        let reviewed_head = if let Some(checkout) = &state.foreign_checkout {
1238            let tracking = format!("{}/{branch}", state.config.merge.remote);
1239            // A surviving tracking ref is not evidence that the remote still
1240            // offers this tip. Adopt it only after a successful fetch here.
1241            let fetched = git::fetch(repo, &state.config.merge.remote, branch).await;
1242            let mut head = checkout.synced_head.clone();
1243            if matches!(fetched, Ok(out) if out.ok()) {
1244                let remote = git::rev_parse(repo, &tracking).await?;
1245                if git::is_ancestor(repo, &checkout.synced_head, &remote).await {
1246                    head = remote;
1247                }
1248            }
1249            head
1250        } else {
1251            git::rev_parse(repo, branch).await?
1252        };
1253        state.observe_branch_owner_holds(&reviewed_head).await;
1254
1255        // An attached worktree, so the fixer's commits land on the branch under
1256        // review rather than on a detached head nobody will look at again.
1257        let worktree = state.worktree_root().join("under-review");
1258        if let Some(parent) = worktree.parent() {
1259            tokio::fs::create_dir_all(parent).await.ok();
1260        }
1261        let path = worktree.to_string_lossy().to_string();
1262        let review_branch = if state.foreign_checkout.is_some() {
1263            let shadow = format!("magi/{}/review", state.short());
1264            git::git(repo, &["branch", &shadow, &reviewed_head]).await?;
1265            shadow
1266        } else {
1267            branch.to_owned()
1268        };
1269        startup_stage(state, "review-checkout")?;
1270        git::git(repo, &["worktree", "add", &path, &review_branch])
1271            .await
1272            .with_context(|| {
1273                format!("checking out `{branch}` at {path} (is it checked out elsewhere?)")
1274            })?;
1275
1276        startup_stage(state, "worktree-setup")?;
1277        let setup = match ensure_setup_config(state, repo).await {
1278            Ok(()) => {
1279                worktree_setup::prepare_with(
1280                    &state.config,
1281                    repo,
1282                    &worktree,
1283                    crate::build_target::Coordination::Held(_coordination.as_ref()),
1284                )
1285                .await
1286            }
1287            Err(e) => Err(e),
1288        };
1289        if let Err(e) = setup {
1290            git::worktree_remove_clean(repo, &worktree).await.ok();
1291            return Err(e);
1292        }
1293        let commits = git::commits_ahead(&worktree, &base_commit, "HEAD")
1294            .await
1295            .unwrap_or(0);
1296        if commits == 0 {
1297            git::worktree_remove_clean(repo, &worktree).await.ok();
1298            bail!("`{branch}` has no commits beyond {}", short(&base_commit));
1299        }
1300        let files = git::changed_files(&worktree, &base_commit, "HEAD")
1301            .await
1302            .map(|f| f.len())
1303            .unwrap_or(0);
1304        if files == 0
1305            && let (Ok(head_tree), Ok(base_tree)) = (
1306                git::tree_of(&worktree, "HEAD").await,
1307                git::tree_of(&worktree, &base_commit).await,
1308            )
1309            && head_tree == base_tree
1310        {
1311            let head = git::rev_parse(&worktree, "HEAD").await.unwrap_or_default();
1312            git::worktree_remove_clean(repo, &worktree).await.ok();
1313            bail!(
1314                "`{branch}` at {} has a tree identical to base {}; this usually means \
1315                 the branch ref is stale (check `git rev-parse refs/heads/{branch}` \
1316                 against `{}/{branch}`) rather than an empty change",
1317                short(&head),
1318                short(&base_commit),
1319                state.config.merge.remote
1320            );
1321        }
1322        let stat = git::diff_stat(&worktree, &base_commit, "HEAD")
1323            .await
1324            .unwrap_or_default();
1325
1326        state.candidates.push(Candidate {
1327            index: 0,
1328            label: 'A',
1329            // Not an agent id on purpose: nothing in the roster wrote this, and
1330            // the stats tables must not credit anyone with a win for it.
1331            agent: EXISTING_BRANCH.to_owned(),
1332            branch: review_branch,
1333            worktree,
1334            summary: String::new(),
1335            stat,
1336            files,
1337            commits,
1338            empty: false,
1339            failed: None,
1340            verified_noop: None,
1341            duration_ms: 0,
1342            folded: false,
1343        });
1344        state.tally = Some(Tally {
1345            first_choice: BTreeMap::from([('A', 0)]),
1346            borda: BTreeMap::new(),
1347            winner: 'A',
1348            rankings: 0,
1349            unanimous_initial: false,
1350            deliberated: false,
1351            changed_votes: 0,
1352            unanimous_final: false,
1353            tie_break: None,
1354            // No panel sat, so no quorum applies. Zero judges is the correct
1355            // number for work that never competed, and must not be reported as
1356            // a collapsed panel.
1357            judges: 0,
1358            present: 0,
1359            quorum: 0,
1360            met_quorum: true,
1361            uncontested: Some("review-only run: nothing competed".to_owned()),
1362        });
1363        state.status = RunStatus::Reviewing;
1364        state.prep_complete = Some(true);
1365        state.event(
1366            "start",
1367            format!(
1368                "review-only run {} on `{branch}` ({files} files, {commits} commits)",
1369                state.id
1370            ),
1371        );
1372        Ok(())
1373    }
1374
1375    /// Authorize one bounded synchronization interval, under the caller's queue task
1376    /// claim and the same owner/execution locks used by run maintenance.
1377    pub async fn authorize_base_recovery(home: &Path, id: &str, task: &str) -> Result<()> {
1378        Self::authorize_base_recovery_request(home, id, task, false, None, None).await
1379    }
1380
1381    /// Authorize a known preparation failure against the inspected evidence.
1382    pub async fn authorize_base_preparation_recovery(
1383        home: &Path,
1384        id: &str,
1385        task: &str,
1386        digest: &str,
1387    ) -> Result<()> {
1388        Self::authorize_base_recovery_request(home, id, task, false, None, Some(digest)).await
1389    }
1390
1391    /// Queue release uses its durable approval generation exactly once.
1392    pub(crate) async fn authorize_base_recovery_from_resumption(
1393        home: &Path,
1394        id: &str,
1395        task: &str,
1396    ) -> Result<()> {
1397        Self::authorize_base_recovery_request(home, id, task, true, None, None).await
1398    }
1399
1400    pub(crate) async fn authorize_base_recovery_control(
1401        home: &Path,
1402        task: &str,
1403        control: &mut crate::base_recovery_control::Transaction,
1404    ) -> Result<()> {
1405        let id = control.request.run.clone();
1406        Self::authorize_base_recovery_request(home, &id, task, false, Some(control), None).await
1407    }
1408
1409    async fn authorize_base_recovery_request(
1410        home: &Path,
1411        id: &str,
1412        task: &str,
1413        resumption: bool,
1414        mut control: Option<&mut crate::base_recovery_control::Transaction>,
1415        terminal_digest: Option<&str>,
1416    ) -> Result<()> {
1417        let _owner = crate::pr_head::owner_lock(home, id)?;
1418        let mut state = RunState::load_under(id, home)?;
1419        crate::pr_head::ensure_owner(&state)?;
1420        let queued = crate::queue::Queue::at(home.join("queue")).get(task)?;
1421        anyhow::ensure!(
1422            queued.execution_runs().last().is_some_and(|run| run == id)
1423                && queued.assignment_accepts(&state)
1424                && queued.status != crate::queue::TaskStatus::Done
1425                && !queued.fresh_start
1426                && queued.review_branch.is_none(),
1427            "run task ownership changed"
1428        );
1429        anyhow::ensure!(
1430            state
1431                .origin
1432                .as_ref()
1433                .and_then(|o| o.task.as_deref())
1434                .is_none_or(|owner| owner == task),
1435            "run belongs to another task"
1436        );
1437        let claimed = crate::daemon::is_working_on_other(home, id, Timestamp::now())?;
1438        anyhow::ensure!(
1439            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
1440            "run is live or its ownership is unknown"
1441        );
1442        // Judge the previous driver's lease before acquiring our maintenance
1443        // lease. The owner lock excludes new driver claims across both steps.
1444        let _execution = crate::driver::maintenance(home, id)?;
1445        anyhow::ensure!(
1446            state.status.resumable()
1447                && state.released_to.is_none()
1448                && state.retired_to.is_none()
1449                && state.pr_taken_over_by.is_none(),
1450            "run ownership is final"
1451        );
1452        anyhow::ensure!(state.base_sync_blocked(), "run has no base-sync stop");
1453        anyhow::ensure!(
1454            !state.pr_publication_pending
1455                && !crate::handover::landing_checkpoint(&state)
1456                && state.merge_decision.is_none(),
1457            "publication or landing has its own retained checkpoint; base recovery cannot replace it"
1458        );
1459        let winner = state.winner().context("run has no retained winner")?;
1460        anyhow::ensure!(
1461            git::is_clean(&winner.worktree).await?,
1462            "retained worktree has uncommitted changes"
1463        );
1464        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
1465        anyhow::ensure!(
1466            git::rev_parse(&state.repo, &format!("refs/heads/{}", winner.branch)).await? == head,
1467            "retained worktree does not match the winner branch"
1468        );
1469        if let Some(control) = control.as_ref() {
1470            anyhow::ensure!(
1471                head.starts_with(&control.request.head),
1472                "retained HEAD changed since the owner request"
1473            );
1474            anyhow::ensure!(
1475                state
1476                    .base_sync_recovery
1477                    .stop
1478                    .as_ref()
1479                    .is_none_or(|stop| stop.head == head),
1480                "retained HEAD differs from the recorded stop head; inspect it first"
1481            );
1482        }
1483        anyhow::ensure!(
1484            crate::repair_budget::legacy::legacy_sequencer_head(&state).is_none(),
1485            "{}",
1486            crate::repair_budget::legacy::LEGACY_EXEC_ACTION
1487        );
1488        state.ensure_base_episode();
1489        state.record_base_sync_stop(&head);
1490        let preparation = state.unknown_preparation_stop(&head);
1491        anyhow::ensure!(
1492            state
1493                .base_sync_recovery
1494                .stop
1495                .as_ref()
1496                .is_some_and(|s| s.kind == crate::base_sync_recovery::StopKind::Exhausted)
1497                || (preparation && !resumption),
1498            "base recovery refused: missing eligible movement-exhaustion or preparation-stop evidence; inspect with `magi task inspect-base-stop {task} --run {id}`. Textual stops require an evidence-bound base-conflict grant"
1499        );
1500        let fetched =
1501            git::fetch(&state.repo, &state.config.merge.remote, &state.base_branch).await?;
1502        anyhow::ensure!(
1503            fetched.ok(),
1504            "cannot authorize base recovery without a fetched base"
1505        );
1506        let approved_tip = git::rev_parse(
1507            &state.repo,
1508            &format!("{}/{}", state.config.merge.remote, state.base_branch),
1509        )
1510        .await?;
1511        let preparation_digest = state.preparation_digest(&head);
1512        anyhow::ensure!(
1513            preparation
1514                || (terminal_digest.is_none()
1515                    && control
1516                        .as_ref()
1517                        .is_none_or(|c| c.request.evidence_digest.is_none())),
1518            "preparation evidence digest does not name an eligible preparation stop"
1519        );
1520        if preparation {
1521            anyhow::ensure!(
1522                crate::daemon::compatible_run_instruction(&state, &queued),
1523                "task instruction does not match the retained run"
1524            );
1525            if let Some(control) = control.as_ref() {
1526                anyhow::ensure!(
1527                    control.request.head == head
1528                        && control.request.evidence_digest.is_some()
1529                        && control.request.evidence_digest == preparation_digest
1530                        && control.request.decision.is_none(),
1531                    "preparation stop requires the full HEAD and current inspected evidence digest"
1532                );
1533            } else {
1534                anyhow::ensure!(
1535                    terminal_digest.is_some() && terminal_digest == preparation_digest.as_deref(),
1536                    "preparation stop requires the current inspected evidence digest"
1537                );
1538            }
1539            let stop = state.base_sync_recovery.stop.as_ref().unwrap();
1540            anyhow::ensure!(
1541                git::is_ancestor(&state.repo, &stop.tip, &approved_tip).await,
1542                "current base does not descend from the stopped base"
1543            );
1544            git::probe_rebase_preparation(
1545                &state,
1546                &head,
1547                &home.join("runs").join(id),
1548                &repository_wait(&state, None),
1549            )
1550            .await?;
1551        }
1552        if let Some(control) = control.as_deref_mut() {
1553            let queue = crate::queue::Queue::at(home.join("queue"));
1554            control.prepare(&queue, &state, &queued, &head, &approved_tip)?;
1555            if let Some(prior) = state
1556                .base_sync_recovery
1557                .authorizations
1558                .iter()
1559                .find(|a| a.request.as_deref() == Some(&control.key()))
1560            {
1561                anyhow::ensure!(
1562                    !prior.consumed && prior.invalidated.is_none() && state.base_recovery_pending(),
1563                    "recovery request was consumed or invalidated; it cannot queue again"
1564                );
1565                return control.enqueue(&queue);
1566            }
1567        }
1568        if resumption {
1569            anyhow::ensure!(
1570                crate::daemon::compatible_run_instruction(&state, &queued),
1571                "resumption instruction does not match the retained run"
1572            );
1573            let approval = queued
1574                .resumption
1575                .as_ref()
1576                .context("no operator resumption")?;
1577            anyhow::ensure!(
1578                approval.instruction == queued.instruction,
1579                "resumption approval does not match the current task instruction"
1580            );
1581            state.authorize_base_sync_resumption(task, approval)?;
1582        } else {
1583            state.authorize_base_sync(task)?;
1584        }
1585        let episode = state.base_sync_recovery.episodes.last().unwrap().id;
1586        state
1587            .base_sync_recovery
1588            .authorizations
1589            .last_mut()
1590            .unwrap()
1591            .scope = Some(crate::base_sync_recovery::Scope {
1592            tip: approved_tip,
1593            instruction: queued.instruction.clone(),
1594            episode,
1595            preparation_digest,
1596        });
1597        if let Some(control) = control.as_deref_mut() {
1598            let authorization = state.base_sync_recovery.authorizations.last_mut().unwrap();
1599            authorization.request = Some(control.key());
1600            authorization.generation = control.generation();
1601            authorization.decision = control.decision();
1602            authorization.question = control
1603                .request
1604                .decision
1605                .as_ref()
1606                .map(|_| control.request.request.clone());
1607        }
1608        state.event(
1609            "base-recovery",
1610            if preparation {
1611                "owner authorized the proven preparation-stop recovery; remaining budget retained; fresh verification required"
1612            } else {
1613                "owner authorized a bounded base synchronization interval; fresh verification required"
1614            },
1615        );
1616        state.save_under(home)?;
1617        if let Some(control) = control {
1618            control.enqueue(&crate::queue::Queue::at(home.join("queue")))?;
1619        }
1620        Ok(())
1621    }
1622
1623    /// Reopen an existing run.
1624    pub fn resume(id: &str) -> Result<Self> {
1625        let state = RunState::load(id)?;
1626        crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &state.id)?;
1627        if state.startup.as_ref().is_some_and(|s| !s.complete)
1628            || (state.status == RunStatus::Prep
1629                && state.instruction.trim().is_empty()
1630                && state.candidates.is_empty()
1631                && state.prep_complete == Some(false))
1632        {
1633            bail!(
1634                "run {id} did not finish startup; inspect its startup evidence and retained assets, then start an explicitly authorized review or recovery"
1635            );
1636        }
1637        crate::pr_head::ensure_owner(&state)?;
1638        if state.pr_recovery.is_some() && state.reviewed_commits.is_none() {
1639            bail!(
1640                "selected public-head recovery did not finish setup; use `magi task recover-pr` after correcting the cause"
1641            );
1642        }
1643        if let Some(to) = &state.released_to {
1644            bail!(
1645                "run {} cannot be resumed: its worktree was released to run {}",
1646                state.short(),
1647                crate::run::short_of(to)
1648            );
1649        }
1650        let roles = state.config.resolve_roles()?;
1651        if let Some(id) = &state.config.graph.selected_implementer
1652            && state.candidates.iter().any(|c| c.agent != *id)
1653        {
1654            bail!(
1655                "replacement implementer pin does not match the saved candidates; task must stay held"
1656            );
1657        }
1658        let max_parallel = state.config.graph.max_parallel.max(1);
1659        Ok(Self {
1660            state,
1661            roles,
1662            sem: Arc::new(Semaphore::new(max_parallel)),
1663            pause: Pause::new(),
1664            interrupt: Pause::new(),
1665        })
1666    }
1667
1668    /// Walk the graph to a terminal state, skipping nodes already recorded.
1669    ///
1670    /// Every way a run is driven - the queue loop, `magi run`, a resume from
1671    /// the phone - ends here, so this is the one place a run that ended
1672    /// Blocked / Stalled / Failed, or died with an error, is announced to the
1673    /// attention-report outbox. Best-effort: see [`crate::notices::raise`].
1674    pub fn execute(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
1675        // Allocate before polling: boxing inside an async wrapper would still
1676        // retain its construction frame while the nested graph is polled.
1677        Box::pin(self.execute_inner(None))
1678    }
1679
1680    pub(crate) async fn execute_sync_only(
1681        &mut self,
1682        request: crate::base_sync_only::Request,
1683    ) -> Result<()> {
1684        Box::pin(self.execute_inner(Some(request))).await
1685    }
1686
1687    async fn execute_inner(
1688        &mut self,
1689        sync_only: Option<crate::base_sync_only::Request>,
1690    ) -> Result<()> {
1691        anyhow::ensure!(
1692            self.state.startup.as_ref().is_none_or(|s| s.complete),
1693            "startup incomplete; inspect retained evidence before explicit recovery"
1694        );
1695        if let Some(selection) = &self.state.pr_recovery
1696            && (selection.source_proof.is_some() || selection.source_run.is_some())
1697        {
1698            Box::pin(selection.verify_source(&self.state.repo)).await?;
1699        }
1700        // Queue claims cover daemon work; this also serializes manual drivers
1701        // consuming a repair answer, including the new review and decision.
1702        let _repair_claim = if self.state.config.graph.selected_implementer.is_some()
1703            || self.state.land_approval.is_some()
1704            || self.state.merge_decision.is_some()
1705            || !self.state.merge_repairs.is_empty()
1706            || (self.state.status == RunStatus::Landing && land::repair_available(&self.state))
1707        {
1708            let claim = FixClaim::acquire(&self.state.dir())?;
1709            crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &self.state.id)?;
1710            let disk = RunState::load(&self.state.id)?;
1711            let checkpoint = |s: &RunState| {
1712                (
1713                    s.merge_repairs.len(),
1714                    s.merge_repairs
1715                        .last()
1716                        .map(|r| (r.question.clone(), r.phase)),
1717                    s.land_approval
1718                        .as_ref()
1719                        .map(|a| (a.question.clone(), a.head.clone())),
1720                )
1721            };
1722            if checkpoint(&disk) != checkpoint(&self.state) {
1723                bail!(
1724                    "repair decision changed since this run was loaded; reload and resume the existing run, never start a second repair"
1725                );
1726            }
1727            Some(claim)
1728        } else {
1729            None
1730        };
1731        let base_only = sync_only.is_some();
1732        let mut execution = self.claim_driver(sync_only).await?;
1733        let runner = &mut *execution.runner;
1734        let wait = runner.repository_wait();
1735        // Keep the graph's large future off the callers' stack, including
1736        // standalone task attempts running on a default-sized test thread.
1737        let result = if base_only {
1738            wait.scope(Box::pin(async {
1739                let repo = runner.state.repo.clone();
1740                let result = async {
1741                    let _coordination = runner.coordinate(&repo).await?;
1742                    anyhow::ensure!(
1743                        !runner.pause.parked() && !runner.interrupt.parked(),
1744                        "paused before base synchronization"
1745                    );
1746                    crate::base_sync_only::sync(&mut runner.state).await
1747                }
1748                .await;
1749                let pass = runner.state.sync_only_passes.last_mut().unwrap();
1750                pass.result = match result {
1751                    Ok(outcome) => outcome,
1752                    Err(error) => crate::base_sync_only::Outcome::Stopped(format!("{error:#}")),
1753                };
1754                let summary = pass.summary();
1755                runner.state.event("base-sync-only", summary);
1756                runner.state.save()
1757            }))
1758            .await
1759        } else {
1760            wait.scope(Box::pin(runner.execute_graph())).await
1761        };
1762        let result = match result {
1763            Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
1764                record_repository_block(&mut runner.state, &e);
1765                runner.park_here()?;
1766                Ok(())
1767            }
1768            other => other,
1769        };
1770        execution.driver.finish(&mut runner.state).await?;
1771        let ended = if result.is_err() {
1772            Some({
1773                let mut notice = crate::notices::run_stopped(&runner.state.id, &runner.state);
1774                if let Err(error) = &result {
1775                    notice.message = format!(
1776                        "Run {} stopped with an error: {}",
1777                        runner.state.id,
1778                        error.to_string().lines().next().unwrap_or("unknown error")
1779                    );
1780                }
1781                notice
1782            })
1783        } else {
1784            crate::notices::run_ended(&runner.state)
1785        };
1786        if let Some(notice) = ended {
1787            crate::notices::raise(notice);
1788        }
1789        result
1790    }
1791
1792    fn repository_wait(&self) -> crate::repo_lock::WaitPolicy {
1793        repository_wait(&self.state, Some((&self.pause, &self.interrupt)))
1794    }
1795
1796    async fn coordinate(&mut self, cwd: &Path) -> Result<Option<crate::repo_lock::SeatLease>> {
1797        let wait = self.repository_wait();
1798        coordinate_operation(&mut self.state, cwd, &wait).await
1799    }
1800
1801    /// Validate ownership and persist the driver claim in one critical section.
1802    async fn claim_driver(
1803        &mut self,
1804        sync_only: Option<crate::base_sync_only::Request>,
1805    ) -> Result<DriverExecution<'_>> {
1806        let owner = match crate::pr_head::owner_lock_wait(
1807            &crate::run::home(),
1808            &self.state.id,
1809            Duration::from_secs(self.state.config.graph.timeout_resource_wait),
1810        )
1811        .await
1812        {
1813            Ok(owner) => owner,
1814            Err(error) => {
1815                let detail = format!("worktree maintenance or ownership update: {error:#}");
1816                // Admission did not own run.json: retain this resource outcome
1817                // in memory for queue settlement without overwriting a concurrent
1818                // retirement or publication transaction.
1819                self.state.resource_block = Some(crate::run::ResourceBlock {
1820                    cause: crate::run::ResourceBlockCause::Other,
1821                    node: "start".into(),
1822                    kind: "worktree maintenance".into(),
1823                    detail: detail.clone(),
1824                    at: Timestamp::now(),
1825                });
1826                return Err(crate::repo_lock::ResourceBlocked(detail).into());
1827            }
1828        };
1829        let disk = RunState::load(&self.state.id)?;
1830        crate::pr_head::ensure_owner(&disk)?;
1831        let now = Timestamp::now();
1832        let home = crate::run::home();
1833        let claim = crate::daemon::other_claim_for_run(&home, &disk.id, now)?;
1834        let assessment = disk.assess_liveness_under(&home, claim, now);
1835        // Only proven-live ownership refuses here. Unknown records (legacy runs
1836        // with no claim marker or process identity) fall through to the
1837        // exclusive execution lease taken just below, which is what actually
1838        // keeps a second driver out.
1839        anyhow::ensure!(
1840            assessment.verdict != crate::run::Liveness::Live,
1841            "{}",
1842            assessment.live_driver_refusal()
1843        );
1844        if let Some(to) = &disk.released_to {
1845            bail!(
1846                "run {} cannot continue: its worktree was released to run {}",
1847                self.state.short(),
1848                crate::run::short_of(to)
1849            );
1850        }
1851        anyhow::ensure!(
1852            serde_json::to_value(&disk.base_sync_recovery)?
1853                == serde_json::to_value(&self.state.base_sync_recovery)?,
1854            "base recovery changed since this run was loaded; reload the saved run"
1855        );
1856        anyhow::ensure!(
1857            disk.sync_only_passes == self.state.sync_only_passes,
1858            "base-only synchronization changed since this run was loaded; reload the saved run"
1859        );
1860        let driver = crate::driver::DriverGuard::acquire(&crate::run::home(), &disk)?;
1861        let mut execution = DriverExecution {
1862            runner: self,
1863            driver,
1864        };
1865        // Declare after the execution guard: on any claim error this short
1866        // lock must drop before that guard reloads and releases ownership.
1867        let _owner = owner;
1868        if let Some(request) = sync_only {
1869            crate::base_sync_only::validate_run(&disk, &crate::run::home())?;
1870            anyhow::ensure!(
1871                request.run == disk.id,
1872                "sync-base-only request targets a different run"
1873            );
1874            let state = &mut execution.runner.state;
1875            let task_entry = state.next_pass_task_entry;
1876            *state = disk;
1877            state.next_pass_task_entry = task_entry;
1878            if state.pending_sync_only().is_some() {
1879                let pass_index = state.passes.len();
1880                let pass = state.sync_only_passes.last_mut().unwrap();
1881                anyhow::ensure!(
1882                    pass.request == request,
1883                    "interrupted base-only synchronization belongs to a different request"
1884                );
1885                pass.pass_index = pass_index;
1886            } else {
1887                let pass = crate::base_sync_only::Pass::new(request, state);
1888                state.sync_only_passes.push(pass);
1889            }
1890            if state.status == RunStatus::Failed {
1891                state.status = RunStatus::Blocked;
1892            }
1893        } else {
1894            anyhow::ensure!(
1895                disk.pending_sync_only().is_none(),
1896                "base-only synchronization has not succeeded; resume with --sync-base-only before verifying"
1897            );
1898            crate::repair_budget::apply(&crate::run::home(), &mut execution.runner.state, &disk)
1899                .await?;
1900        }
1901        let state = &mut execution.runner.state;
1902        // Moving again, so it is no longer parked. Set before the walk rather
1903        // than in `resume`, so every way of re-entering the graph clears it
1904        // and a card cannot claim a run is waiting to be resumed while the
1905        // agents are already working.
1906        state.parked = false;
1907        state.resource_wait = None;
1908        state.resource_block = None;
1909        // Any seat this state still lists as answering belongs to whatever
1910        // process last drove this run — this one included, if it crashed
1911        // mid-wave. Cleared and flushed immediately, before anything else
1912        // runs, so a resume can never show a seat as live when nothing is
1913        // asking it anything yet; the node that actually dispatches the next
1914        // wave repopulates it.
1915        state.clear_active();
1916        // Recorded in the same spot, and flushed together with the clear
1917        // above: this is the pid a reader checks (`RunState::liveness`) when
1918        // no daemon claim exists to answer "is a process still driving this
1919        // run" — a plain `magi run` / `magi review` typed into a terminal
1920        // claims nothing there. Always overwritten, never only-if-absent, so
1921        // a resumed run's stale pid from a previous, possibly-dead process
1922        // can never survive into this one's own report. Unlike
1923        // `clear_active`, this changes on every single `execute()` call, so
1924        // the save below is now unconditional rather than only-if-cleared.
1925        //
1926        // `driver_started_at` is recorded in the same breath, from this same
1927        // pid, so `liveness` can tell a live pid that is genuinely still us
1928        // apart from one the OS has since handed to an unrelated process —
1929        // see that field's own doc for why the pid alone is not enough.
1930        let pid = std::process::id();
1931        state.driver_pid = Some(pid);
1932        state.driver_started_at = crate::proc::process_started_at(pid);
1933        state.driver_exited = false;
1934        state.driver_claimed = Some(true);
1935        state.begin_pass();
1936        execution.driver.bind(state);
1937        state.save()?;
1938        execution.driver.record(state)?;
1939        Ok(execution)
1940    }
1941
1942    /// No conflict checkpoint proves dispatch was never reached. End that
1943    /// consumed generation so an owner can explicitly authorize a fresh one.
1944    async fn repair_base_conflict(&mut self, dispatch: bool) -> Result<()> {
1945        let result = crate::base_conflict::repair(&mut self.state, dispatch).await;
1946        if let Err(error) = &result
1947            && !error.is::<crate::repo_lock::ResourceBlocked>()
1948            && self
1949                .state
1950                .repair_grants
1951                .last()
1952                .is_some_and(|g| g.conflict.is_none())
1953        {
1954            self.state.repair_grants.last_mut().unwrap().phase =
1955                crate::repair_budget::Phase::Complete;
1956            self.state.status = RunStatus::Blocked;
1957            self.state.save()?;
1958            bail!(
1959                "{error:#}. The consumed reservation ended before editing-seat dispatch. Inspect its scratch tree, then authorize a new base-conflict grant with a new request ID and current --expect-pass {}; the old request will not dispatch again",
1960                self.state.passes.last().map_or(0, |p| p.index)
1961            );
1962        }
1963        result
1964    }
1965
1966    /// A grant owns only these repair attempts. Confirmation reviews cannot
1967    /// create another fixer allowance, and every operation is restart-checkpointed.
1968    async fn execute_granted_repair(&mut self) -> Result<()> {
1969        use crate::repair_budget::{Kind, Phase};
1970        let index = self.state.repair_grants.len() - 1;
1971        let winner = self
1972            .state
1973            .winner()
1974            .cloned()
1975            .context("repair winner missing")?;
1976        loop {
1977            let grant = self.state.repair_grants[index].clone();
1978            match grant.phase {
1979                Phase::Pending => {
1980                    if grant.spent >= grant.receipt.request.rounds {
1981                        self.state.repair_grants[index].phase = Phase::Complete;
1982                        self.state.status = RunStatus::Blocked;
1983                        self.state.save()?;
1984                        return Ok(());
1985                    }
1986                    if grant.spent == 0 && grant.receipt.request.kind == Kind::Review {
1987                        crate::repair_budget::verify_initial_review_grant(&self.state, &grant)
1988                            .await?;
1989                    }
1990                    // Reserve before dispatch. A crash can consume an attempt,
1991                    // but can never duplicate it or reset saved fixer history.
1992                    self.state.repair_grants[index].spent += 1;
1993                    self.state.repair_grants[index].phase = Phase::Fixing;
1994                    self.state.save()?;
1995                    match grant.receipt.request.kind {
1996                        Kind::BaseConflict => self.repair_base_conflict(true).await?,
1997                        Kind::Gate => {
1998                            let failed = self.state.gate.clone();
1999                            let _ = self.gate_fix_round(&winner, &failed).await?;
2000                        }
2001                        Kind::Review => {
2002                            let mut record = self
2003                                .state
2004                                .reviews
2005                                .last()
2006                                .cloned()
2007                                .context("review failure missing")?;
2008                            let round = record.round;
2009                            let step = self.run_fix_round(&winner, &mut record).await?;
2010                            self.state.reviews[round - 1] = record;
2011                            if matches!(step, FixStep::Recorded { report_lost: true }) {
2012                                self.state.repair_grants[index].phase = Phase::Complete;
2013                                self.state.status = RunStatus::Blocked;
2014                                self.state.event("repair-grant", "fixer continuation remains unresolved; repair grant cannot bypass its stop");
2015                                self.state.save()?;
2016                                return Ok(());
2017                            }
2018                            if matches!(step, FixStep::Resource) {
2019                                self.stop_for_resource()?;
2020                                return Ok(());
2021                            }
2022                            self.state.save()?;
2023                        }
2024                    }
2025                    if self.resource_halt()? {
2026                        return Ok(());
2027                    }
2028                }
2029                Phase::Fixing => {
2030                    if grant.receipt.request.kind == Kind::BaseConflict {
2031                        self.repair_base_conflict(false).await?;
2032                    }
2033                    // Interrupted fixers may have left source changes or an
2034                    // unpushed commit. Preserve them before fresh assessment.
2035                    let _coordination = self.coordinate(&winner.worktree).await?;
2036                    let rescued = git::rescue_commit(
2037                        &winner.worktree,
2038                        "magi: preserve interrupted granted repair",
2039                    )
2040                    .await?;
2041                    self.state.note_withheld("repair-grant", &rescued.withheld);
2042                    // Fresh checks must supersede even a same-head failure.
2043                    // Archive rather than erase failure evidence or counters.
2044                    self.state
2045                        .verification_history
2046                        .push(crate::run::VerificationEvidence {
2047                            superseded_by: None,
2048                            archived_at: Some(Timestamp::now()),
2049                            fixes_spent: Some(self.state.gate_fixes.len()),
2050                            gate_head: self.state.gate_head.take(),
2051                            gate_ran: std::mem::take(&mut self.state.gate_ran),
2052                            gate: std::mem::take(&mut self.state.gate),
2053                            e2e: self.state.head_e2e.take(),
2054                        });
2055                    if let Some(e2e) = self.state.gate_repair_e2e.take() {
2056                        self.state
2057                            .verification_history
2058                            .push(crate::run::VerificationEvidence {
2059                                superseded_by: None,
2060                                archived_at: Some(Timestamp::now()),
2061                                fixes_spent: Some(self.state.gate_fixes.len()),
2062                                gate_head: None,
2063                                gate_ran: false,
2064                                gate: Vec::new(),
2065                                e2e: Some(e2e),
2066                            });
2067                    }
2068                    self.state.repair_grants[index].review_start = self.state.reviews.len();
2069                    self.state.repair_grants[index].head =
2070                        git::rev_parse(&winner.worktree, "HEAD").await?;
2071                    self.state.repair_grants[index].phase = Phase::Reviewing;
2072                    if grant.receipt.request.kind == Kind::BaseConflict {
2073                        self.state.base_sync_recovery.stop = None;
2074                        if let Some(sync) = &mut self.state.base_sync {
2075                            sync.tip = grant
2076                                .receipt
2077                                .request
2078                                .tip
2079                                .clone()
2080                                .context("repair base tip missing")?;
2081                            sync.conflict = None;
2082                            sync.behind = 0;
2083                        }
2084                        refresh_reviewed_commits(&mut self.state, &winner.branch).await;
2085                    }
2086                    self.state.save()?;
2087                }
2088                Phase::Reviewing => {
2089                    self.review_loop_pass().await?;
2090                    if self.resource_halt()? {
2091                        return Ok(());
2092                    }
2093                    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
2094                    let reviewed = (self.state.reviews.len() > grant.review_start)
2095                        .then(|| self.state.reviews.last())
2096                        .flatten();
2097                    let review_passed = reviewed.is_some_and(|r| {
2098                        r.clean
2099                            && r.expected > 0
2100                            && r.answered == r.expected
2101                            && matches!(
2102                                r.e2e_status(),
2103                                E2eStatus::Passed | E2eStatus::NotConfigured
2104                            )
2105                            && ((r.e2e_status() == E2eStatus::NotConfigured
2106                                && self.state.config.verify.e2e.is_empty())
2107                                || r.verified_head.as_deref() == Some(head.as_str()))
2108                    });
2109                    let clean = review_passed && reviewed.is_some_and(|r| r.head == head);
2110                    if !clean {
2111                        let next = if review_passed
2112                            && let Some(r) = reviewed
2113                            && r.head != head
2114                        {
2115                            crate::repair_budget::prove_mechanical_pre_gate_commit(
2116                                &self.state,
2117                                r,
2118                                &head,
2119                            )
2120                            .await
2121                            .map(|_| Some(Phase::Reviewing))
2122                        } else if grant.receipt.request.kind == Kind::Review
2123                            && grant.spent < grant.receipt.request.rounds
2124                        {
2125                            crate::repair_budget::prove_review_target(&self.state, &head)
2126                                .await
2127                                .map(|_| Some(Phase::Pending))
2128                        } else {
2129                            Ok(None)
2130                        };
2131                        let next = match next {
2132                            Ok(next) => next,
2133                            Err(error) => {
2134                                if self.state.repair_grants[index]
2135                                    .checkpoint_provenance_retry(&head, &error)
2136                                {
2137                                    self.state.status = RunStatus::Blocked;
2138                                    self.state.event("repair-grant", format!(
2139                                        "pre-gate provenance unavailable; resume confirmation without spending repair budget: {error:#}"
2140                                    ));
2141                                    self.state.save()?;
2142                                    return Ok(());
2143                                }
2144                                None
2145                            }
2146                        };
2147                        if next == Some(Phase::Reviewing) {
2148                            self.state.repair_grants[index].review_start = self.state.reviews.len();
2149                            self.state.repair_grants[index].head = head;
2150                            self.state.repair_grants[index].phase = Phase::Reviewing;
2151                            self.state.status = RunStatus::Blocked;
2152                            self.state.event(
2153                                "repair-grant",
2154                                "pre-gate changed the reviewed head; resume for fresh review before publication",
2155                            );
2156                            self.state.save()?;
2157                            return Ok(());
2158                        }
2159                        // A confirmation review carries no additional fix budget.
2160                        self.state.repair_grants[index].phase = if next == Some(Phase::Pending) {
2161                            self.state.repair_grants[index].head = head;
2162                            Phase::Pending
2163                        } else {
2164                            Phase::Complete
2165                        };
2166                        self.state.status = RunStatus::Blocked;
2167                        self.state.event(
2168                            "repair-grant",
2169                            "fresh review did not clear the repaired head; no publication",
2170                        );
2171                        self.state.save()?;
2172                        if self.state.repair_grants[index].phase == Phase::Pending {
2173                            continue;
2174                        }
2175                        return Ok(());
2176                    }
2177                    self.state.repair_grants[index].phase = Phase::Gating;
2178                    self.state.save()?;
2179                }
2180                Phase::Gating => {
2181                    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
2182                    self.state.reconcile_verification_head(&head);
2183                    let wait = self.repository_wait();
2184                    if self
2185                        .state
2186                        .reviews
2187                        .last()
2188                        .is_none_or(|r| r.head != head || !r.clean)
2189                    {
2190                        self.state.status = RunStatus::Blocked;
2191                        self.state.repair_grants[index].phase = Phase::Complete;
2192                        self.state.event(
2193                            "repair-grant",
2194                            "head changed since fresh review; repair held",
2195                        );
2196                        self.state.save()?;
2197                        return Ok(());
2198                    }
2199                    if !verify_current_head(&mut self.state, &winner, &wait).await? {
2200                        return Ok(());
2201                    }
2202                    let outcomes = self.run_gate(&winner).await?;
2203                    if verify_inconclusive(&outcomes) {
2204                        return Ok(());
2205                    }
2206                    let after = git::rev_parse(&winner.worktree, "HEAD").await?;
2207                    if after != head {
2208                        self.state.repair_grants[index].review_start = self.state.reviews.len();
2209                        self.state.repair_grants[index].head = after;
2210                        self.state.repair_grants[index].phase = Phase::Reviewing;
2211                        self.state.status = RunStatus::Blocked;
2212                        self.state.event("repair-grant", "pre-gate changed the reviewed head; resume for fresh review before publication");
2213                        self.state.save()?;
2214                        return Ok(());
2215                    }
2216                    let passed = outcomes.iter().all(CommandOutcome::ok);
2217                    // Follow-up grants owe the same guarded checkout delivery
2218                    // as the conflict repair that introduced the new head.
2219                    if passed
2220                        && !crate::foreign_checkout::write_back(&mut self.state, &head).await?
2221                    {
2222                        return Ok(());
2223                    }
2224                    self.state.repair_grants[index].succeeded = passed;
2225                    self.state.gate = outcomes;
2226                    self.state.gate_ran = true;
2227                    self.state.status = if passed {
2228                        RunStatus::Gating
2229                    } else {
2230                        RunStatus::Blocked
2231                    };
2232                    self.state.repair_grants[index].phase = if !passed
2233                        && grant.receipt.request.kind == Kind::Gate
2234                        && grant.spent < grant.receipt.request.rounds
2235                    {
2236                        Phase::Pending
2237                    } else {
2238                        Phase::Complete
2239                    };
2240                    if passed && self.state.config.merge.mode == MergeMode::Pr {
2241                        // Persist publication debt with the successful checkpoint.
2242                        self.state.pr_publication_pending = true;
2243                    } else if passed {
2244                        self.state.status = RunStatus::Ready;
2245                    }
2246                    self.state.save()?;
2247                    if !passed {
2248                        continue;
2249                    }
2250                    // Existing PR ownership and push lease stay in place. The
2251                    // normal publisher owes the new reviewed/gated SHA, and
2252                    // land's fresh owner approval remains mandatory.
2253                    if self.state.config.merge.mode != MergeMode::Pr {
2254                        self.state.status = RunStatus::Ready;
2255                        self.state.event(
2256                            "repair-grant",
2257                            "repair verified locally; grant carries no merge authorization",
2258                        );
2259                        self.state.save()?;
2260                        return Ok(());
2261                    }
2262                    return self.merge().await;
2263                }
2264                Phase::Complete => return Ok(()),
2265            }
2266        }
2267    }
2268
2269    async fn execute_graph(&mut self) -> Result<()> {
2270        // Even a terminal run may reenter through an explicit recovery action.
2271        // Restore before prep shortcuts, saved conversations or graph nodes use
2272        // a disposable path; GC may already have removed its original objects.
2273        let archive_home = crate::run::home().canonicalize()?;
2274        if crate::retention::has_archived_seats(&archive_home, &self.state)? {
2275            let repo = self.state.repo.clone();
2276            let _coordination = self.coordinate(&repo).await?;
2277            ensure_setup_config(&mut self.state, &repo).await?;
2278            crate::retention::restore_execution_seats(
2279                &archive_home,
2280                &self.state,
2281                _coordination.as_ref(),
2282            )
2283            .await?;
2284        }
2285        self.state.configure_recovery_resume()?;
2286        if self
2287            .state
2288            .repair_grants
2289            .last()
2290            .is_some_and(|g| g.phase != crate::repair_budget::Phase::Complete)
2291        {
2292            return self.execute_granted_repair().await;
2293        }
2294        if self
2295            .state
2296            .repair_grants
2297            .last()
2298            .is_some_and(|g| !g.succeeded)
2299        {
2300            self.state.status = RunStatus::Blocked;
2301            self.state.save()?;
2302            return Ok(());
2303        }
2304        // Preservation may invalidate an old empty classification. Resolve it
2305        // before any resume shortcut can reuse a verdict or publish a branch.
2306        self.persist_candidates().await?;
2307        // A saved base stop outranks stage markers, including legacy Voting.
2308        // Recovery never reenters implementation, deliberation or voting.
2309        if self.state.base_sync_blocked() {
2310            self.sync_to_base().await?;
2311            if !self.state.base_sync_blocked()
2312                && self.state.status != RunStatus::AlreadyInBase
2313                && !self.resource_halt()?
2314            {
2315                self.finish_after_tally().await?;
2316            }
2317            return Ok(());
2318        }
2319        if self
2320            .state
2321            .merge_decision
2322            .as_ref()
2323            .is_some_and(|decision| !decision.closed)
2324            && self.state.status != RunStatus::Landing
2325        {
2326            if crate::merge_decision::resumable_hold(&self.state) {
2327                self.state.merge = Some(MergeOutcome {
2328                    mode: MergeMode::Pr,
2329                    ok: false,
2330                    detail: self
2331                        .state
2332                        .merge_decision
2333                        .as_ref()
2334                        .unwrap()
2335                        .target
2336                        .pr
2337                        .clone(),
2338                    empty: false,
2339                });
2340                self.run_land().await?;
2341                self.settle_questions();
2342                return Ok(());
2343            }
2344            bail!(
2345                "owner stop decision is held; inspect the existing PR and request an explicit fresh review/decision before further work"
2346            );
2347        }
2348        if self.state.config.graph.selected_implementer.is_some()
2349            && self.state.status == RunStatus::Blocked
2350            && self.state.tally.is_none()
2351            && self.state.candidate_preservation.is_empty()
2352            && self.state.interrupted_implementations.is_empty()
2353        {
2354            bail!(
2355                "selected implementation is held; explicitly release the owning task to retry it"
2356            );
2357        }
2358
2359        if self.state.merge_repairs.last().is_some_and(|r| {
2360            matches!(
2361                r.phase,
2362                crate::run::MergeRepairPhase::Requested
2363                    | crate::run::MergeRepairPhase::Fixing
2364                    | crate::run::MergeRepairPhase::Reviewing
2365            )
2366        }) {
2367            if self.repair_merge_review().await? {
2368                self.run_land().await?;
2369            }
2370            self.settle_questions();
2371            return Ok(());
2372        }
2373        // Publication already passed review and gate. Resume only that node:
2374        // syncing to a newer base here could change the verified commit.
2375        if self.state.pr_publication_pending {
2376            self.merge().await?;
2377            if self.resource_halt()? {
2378                return Ok(());
2379            }
2380            self.state.save()?;
2381            self.settle_questions();
2382            return Ok(());
2383        }
2384        // A run that already lost its quorum never resumes into the verdict
2385        // machinery: `deliberate` and `vote` would otherwise clobber the
2386        // stalled marker back to Voting and the run would keep going past a
2387        // verdict that is no longer trustworthy. Everything already recorded is
2388        // kept, so the run stays resumable (or foldable) for a human to pick up.
2389        //
2390        // On --resume the run gets one chance to repair itself: the seats a
2391        // rate limit took out are re-asked. If their quota has since reset and
2392        // the quorum is restored, the run picks up and finishes; otherwise it
2393        // stays stale and still-resumable for a later retry. If it does not
2394        // recover, the returned status stays `Stalled` and nothing was
2395        // clobbered (the recovery only mutates entries for the lost seats).
2396        if self.state.status == RunStatus::Stalled {
2397            if self.recover_stall().await? {
2398                self.finish_after_tally().await?;
2399            } else {
2400                // Still below quorum: persist the marker and stay resumable.
2401                self.state.save()?;
2402            }
2403            return Ok(());
2404        }
2405        // A run parked inside `land` - watching CI, mid fix-round, or
2406        // waiting on the owner's merge approval - resumes directly into it,
2407        // never back through `prep`. Everything before `merge` already
2408        // concluded; that is the only way `status` reaches `Landing` in the
2409        // first place. Re-walking `review_loop` first would also be actively
2410        // wrong: its own status recomputation (see its doc) treats any
2411        // clean round as reason to set `status` to `Gating`, which would
2412        // clobber this marker before `merge` ever ran, and this run would
2413        // never find its way back into `land` at all.
2414        if self.state.status == RunStatus::Landing
2415            || crate::handover::landing_checkpoint(&self.state)
2416        {
2417            self.state.land_sync_pending = true;
2418            self.state.save()?;
2419            self.run_land().await?;
2420            // `run_land` may have settled the run right here - CI came back
2421            // green and the PR merged, say - without ever passing back
2422            // through `merge`'s own trailing call. Whatever it left `status`
2423            // as is what this has to read.
2424            self.settle_questions();
2425            return Ok(());
2426        }
2427        // A run parked at `merge` on the owner's word about a withheld PR text
2428        // resumes straight into `merge`. Re-walking the tail would sync to the
2429        // base again (possibly rebasing, possibly spending the fixer) after the
2430        // gate had passed, and then push a tree nobody reviewed or gated.
2431        if self.state.github_text.is_some()
2432            && self.state.merge.is_none()
2433            && self.state.status == RunStatus::Gating
2434        {
2435            self.merge().await?;
2436            if self.resource_halt()? {
2437                return Ok(());
2438            }
2439            self.state.save()?;
2440            return Ok(());
2441        }
2442        // A resource stop left the reserved synchronization unfinished. Reconcile
2443        // its exact HEAD and base before starting any earlier graph stage.
2444        if self.state.pending_base_operation().is_some() {
2445            return self.finish_after_tally().await;
2446        }
2447        if let Err(e) = self.prep().await {
2448            if e.is::<crate::repo_lock::ResourceBlocked>() {
2449                return Err(e);
2450            }
2451            self.state.status = RunStatus::Blocked;
2452            self.state
2453                .prep_failure
2454                .get_or_insert_with(|| format!("{e:#}"));
2455            self.state
2456                .event("prep", format!("preparation stopped: {e:#}"));
2457            self.state.save()?;
2458            return Err(e);
2459        }
2460        if self.park_here()? {
2461            return Ok(());
2462        }
2463        self.advise().await?;
2464        if self.park_here()? {
2465            return Ok(());
2466        }
2467        self.implement().await?;
2468        if self.park_here()? {
2469            return Ok(());
2470        }
2471        // `after_implement` already saved the state and settled any open
2472        // questions when it set this; nothing later in the graph has
2473        // anything to judge.
2474        if self.state.status == RunStatus::VerifiedNoop {
2475            return Ok(());
2476        }
2477        self.judge().await?;
2478        if self.park_here()? {
2479            return Ok(());
2480        }
2481        self.deliberate().await?;
2482        if self.park_here()? {
2483            return Ok(());
2484        }
2485        self.vote().await?;
2486        if self.park_here()? {
2487            return Ok(());
2488        }
2489        self.tally()?;
2490        // A verdict that lost its quorum is not trustworthy: do not review,
2491        // gate, or merge on it. Everything already done is kept, so the run
2492        // stays resumable (or foldable); the human can replace the agent that
2493        // ran out of quota and pick it up.
2494        if self.state.status == RunStatus::Stalled {
2495            // Persist the stalled marker now — the normal end-of-execute save
2496            // below is below this early return, and without it a resumed run
2497            // would reload a pre-tally status and keep going.
2498            self.state.save()?;
2499            return Ok(());
2500        }
2501        self.finish_after_tally().await?;
2502        Ok(())
2503    }
2504
2505    /// A wave could not start its agents because a shared resource stayed busy
2506    /// (see [`RunState::resource_block`]): leave the run `Blocked` and
2507    /// resumable. Unstarted seats have no result; completed peers retain
2508    /// their saved candidate state.
2509    fn stop_for_resource(&mut self) -> Result<()> {
2510        // Resource acquisition observes cancellation inside a node. Complete
2511        // the same durable park as every other node boundary before returning.
2512        if self.pause.parked() || self.interrupt.parked() {
2513            self.park_here()?;
2514            return Ok(());
2515        }
2516        if self.state.resource_block.is_some() {
2517            self.state.status = RunStatus::Blocked;
2518        }
2519        self.state.save()
2520    }
2521
2522    /// Stop walking the graph if a node ended on a resource block.
2523    fn resource_halt(&mut self) -> Result<bool> {
2524        if self.state.resource_block.is_none() {
2525            return Ok(false);
2526        }
2527        self.stop_for_resource()?;
2528        Ok(true)
2529    }
2530
2531    /// Park here if asked to, recording it in the run's own timeline.
2532    ///
2533    /// Returns whether the caller should stop walking the graph. The state is
2534    /// saved either way by the node that just finished; this adds the event so
2535    /// the operator's card says why a run that is neither finished nor moving
2536    /// is sitting where it is.
2537    fn park_here(&mut self) -> Result<bool> {
2538        let parking = self.pause.parked() || self.interrupt.parked();
2539        if !parking && self.state.resource_block.is_some() {
2540            self.stop_for_resource()?;
2541            return Ok(true);
2542        }
2543        // Either handle asking is enough - see `Pause`'s own doc for why
2544        // they are never the same one. `interrupt` is checked second so a
2545        // reason it carries is preferred in the message below over a plain
2546        // shutdown park racing it at the same boundary.
2547        if !self.pause.parked() && !self.interrupt.parked() {
2548            return Ok(false);
2549        }
2550        if self.state.parked {
2551            return Ok(true);
2552        }
2553        let cause = self.interrupt.cause().or_else(|| self.pause.cause());
2554        if let Some(block) = &mut self.state.resource_block
2555            && matches!(
2556                block.cause,
2557                crate::run::ResourceBlockCause::Cancelled { .. }
2558            )
2559        {
2560            block.cause = crate::run::ResourceBlockCause::Cancelled {
2561                park: cause.clone(),
2562            };
2563        }
2564        let why = match cause.as_ref().map(ParkCause::label) {
2565            Some(reason) => format!(
2566                "parked after `{}` ({reason}) — resume to carry on from here",
2567                self.state.status.as_str()
2568            ),
2569            None => format!(
2570                "parked after `{}` — resume to carry on from here",
2571                self.state.status.as_str()
2572            ),
2573        };
2574        self.state.event("park", why);
2575        self.state
2576            .end_pass_parked(cause.unwrap_or(ParkCause::Unspecified));
2577        self.state.parked = true;
2578        self.state.save()?;
2579        Ok(true)
2580    }
2581
2582    /// Only a new explicit operator approval may retry failed preparation.
2583    pub fn retry_preparation(&mut self, approval_at: jiff::Timestamp) -> Result<()> {
2584        if self.state.prep_failure.is_none() {
2585            return Ok(());
2586        }
2587        let failed_at = self
2588            .state
2589            .events
2590            .iter()
2591            .rev()
2592            .find(|event| event.node == "prep")
2593            .map_or(self.state.updated_at, |event| event.at);
2594        anyhow::ensure!(
2595            approval_at > failed_at,
2596            "preparation retry requires a new explicit release after the failure"
2597        );
2598        self.state.prep_failure = None;
2599        self.state.prep_complete = Some(false);
2600        self.state
2601            .event("prep-retry", "operator approved retry of preparation");
2602        Ok(())
2603    }
2604
2605    /// Hand the runner the pause `magi serve`'s own shutdown watches.
2606    pub fn on_pause(&mut self, pause: Pause) {
2607        self.pause = pause;
2608    }
2609
2610    /// Hand the runner a second, independent pause: `magi serve`'s interrupt
2611    /// scheduler asking this one run - and no other - to park so a task
2612    /// marked [`crate::queue::Task::interrupt`] can run alone. See
2613    /// [`Pause`]'s own doc for why this is never [`Runner::on_pause`]'s
2614    /// handle.
2615    pub fn watch_interrupt(&mut self, pause: Pause) {
2616        self.interrupt = pause;
2617    }
2618
2619    /// Abandon this run's own open questions, once `status` has actually
2620    /// settled rather than merely paused.
2621    ///
2622    /// `Blocked` and `Stalled` are `RunStatus::resumable` — a human can pick
2623    /// either back up with the candidates, the review round and the seat
2624    /// sessions already on disk, so a question an implementer asked mid-round
2625    /// may still get a real answer read by a real resume. Only the statuses
2626    /// `resumable` excludes are actually final: the run merged, it reached
2627    /// `Ready` with nothing left to do, it failed outright with no
2628    /// established point to continue from, or every candidate agreed, with
2629    /// evidence, that nothing belonged in the worktree (`VerifiedNoop`). In
2630    /// every one of those the seat that asked is gone for good, exactly like
2631    /// the run being deleted under `magi run rm` - so the same cleanup
2632    /// applies, worded for what actually happened instead of "the run was
2633    /// deleted".
2634    ///
2635    /// Best-effort and silent on success: called from every place `status`
2636    /// can land on one of those three, including ones a resumed run revisits,
2637    /// so it must cost nothing when there was nothing open to begin with.
2638    fn settle_questions(&mut self) {
2639        if let Err(e) = ask::Questions::open().settle_run(&self.state.id, self.state.status) {
2640            tracing::warn!("abandon questions for {}: {e:#}", self.state.id);
2641        }
2642    }
2643
2644    /// The tail of the graph after a trustworthy tally: fold losers, review,
2645    /// gate, merge, and persist.
2646    fn finish_after_tally(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
2647        Box::pin(self.finish_after_tally_inner())
2648    }
2649
2650    async fn finish_after_tally_inner(&mut self) -> Result<()> {
2651        // Before the losers are folded: their branches are what the graft
2652        // reads from.
2653        self.graft().await?;
2654        if self.resource_halt()? {
2655            return Ok(());
2656        }
2657        self.fold_losers().await?;
2658        // Before review starts, and again right before the gate: a run's
2659        // review rounds can themselves take long enough for the base to move
2660        // a second time, and the gate is the one node whose "green" gets
2661        // acted on.
2662        self.sync_to_base().await?;
2663        if self.hold_base_sync().await? || self.resource_halt()? {
2664            return Ok(());
2665        }
2666        if self.state.status == RunStatus::AlreadyInBase {
2667            return Ok(());
2668        }
2669        self.review_loop().await?;
2670        if self.resource_halt()? {
2671            return Ok(());
2672        }
2673        self.sync_to_base().await?;
2674        if self.hold_base_sync().await? || self.resource_halt()? {
2675            return Ok(());
2676        }
2677        if self.state.status == RunStatus::AlreadyInBase {
2678            return Ok(());
2679        }
2680        self.gate().await?;
2681        self.merge().await?;
2682        if self.resource_halt()? {
2683            return Ok(());
2684        }
2685        self.state.save()?;
2686        Ok(())
2687    }
2688
2689    // ---------------------------------------------------------------- prep
2690
2691    /// Run `[worktree] setup` in a seat's fresh worktree. A failure blocks the
2692    /// run with the step and its output in the event; it is never swallowed.
2693    /// During `prep` (`in_prep`) the whole preparation is rolled back, so a
2694    /// resume starts over instead of finding candidates and missing seats.
2695    async fn setup_seat_worktree(
2696        &mut self,
2697        repo: &Path,
2698        wt: &Path,
2699        in_prep: bool,
2700        coordination: Option<&crate::repo_lock::SeatLease>,
2701    ) -> Result<()> {
2702        let result = match ensure_setup_config(&mut self.state, repo).await {
2703            Ok(()) => {
2704                worktree_setup::prepare_with(
2705                    &self.state.config,
2706                    repo,
2707                    wt,
2708                    crate::build_target::Coordination::Held(coordination),
2709                )
2710                .await
2711            }
2712            Err(e) => Err(e),
2713        };
2714        if let Err(e) = result {
2715            git::worktree_remove_clean(repo, wt).await.ok();
2716            if in_prep {
2717                self.rollback_prep(repo).await;
2718            }
2719            self.state.status = RunStatus::Blocked;
2720            self.state.event(
2721                "setup",
2722                format!("worktree setup failed in {}: {e:#}", wt.display()),
2723            );
2724            self.state.save()?;
2725            return Err(e);
2726        }
2727        Ok(())
2728    }
2729
2730    /// Undo everything `prep` created, so a resume re-runs it whole.
2731    async fn rollback_prep(&mut self, repo: &Path) {
2732        let root = self.state.worktree_root();
2733        for c in std::mem::take(&mut self.state.candidates) {
2734            if matches!(
2735                git::worktree_remove_clean(repo, &c.worktree).await,
2736                Ok(true)
2737            ) {
2738                git::branch_delete(repo, &c.branch).await.ok();
2739            } else {
2740                self.state.candidates.push(c);
2741            }
2742        }
2743        let seats = self.roles.judges.len().max(self.state.config.graph.judges);
2744        for j in 1..=seats {
2745            remove_read_seat_worktree(&mut self.state, &root.join(format!("judge-{j}")))
2746                .await
2747                .ok();
2748        }
2749        for k in 1..=self.state.config.graph.advisors {
2750            remove_read_seat_worktree(&mut self.state, &root.join(format!("advisor-{k}")))
2751                .await
2752                .ok();
2753        }
2754    }
2755
2756    async fn prep(&mut self) -> Result<()> {
2757        if let Some(reason) = &self.state.prep_failure {
2758            bail!(
2759                "candidate preparation previously failed: {reason}; correct the source before retrying"
2760            );
2761        }
2762        if self
2763            .state
2764            .prep_complete
2765            .unwrap_or(!self.state.candidates.is_empty())
2766        {
2767            return Ok(());
2768        }
2769        let repo = self.state.repo.clone();
2770        // Includes rollback, config, refs, checkout creation and setup. No
2771        // repository mutation may precede the real shared lock acquisition.
2772        let _coordination = self.coordinate(&repo).await?;
2773        let base = self.state.base_commit.clone();
2774        let plan = self.state.sources.plan(&repo, &base).await?;
2775        self.rollback_prep(&repo).await;
2776        if !self.state.candidates.is_empty() {
2777            bail!(
2778                "preparation rollback retained worktrees; recover their uncommitted work before retrying"
2779            );
2780        }
2781        self.state.prep_complete = Some(false);
2782        self.state.status = RunStatus::Prep;
2783        self.state.save()?;
2784        let repo = self.state.repo.clone();
2785        let start = plan.start.clone().unwrap_or_else(|| base.clone());
2786        let root = self.state.worktree_root();
2787        let labels = blind::assign_labels(self.roles.implementers.len(), self.state.seed);
2788
2789        // The hook is the write-time half of the blindness contract; the
2790        // presentation filter in `blind` is the half that cannot be bypassed.
2791        let hooks_dir = self.state.dir().join("hooks");
2792        if self.state.config.blind.commit_msg_hook {
2793            std::fs::create_dir_all(&hooks_dir)
2794                .with_context(|| format!("create {}", hooks_dir.display()))?;
2795            let script = blind::commit_msg_hook(&self.state.config.blind.strip_lines);
2796            let path = hooks_dir.join("commit-msg");
2797            std::fs::write(&path, script).with_context(|| format!("write {}", path.display()))?;
2798            make_executable(&path)?;
2799            // Ref-counted rather than a plain idempotent set: with more than
2800            // one run able to be in flight in the same repository at once
2801            // (see `Config::daemon.max_concurrent_runs`), a bare "already
2802            // true?" check cannot tell "another run of mine still needs
2803            // this" from "nobody does", and the run that happens to finish
2804            // first would disable the hook out from under a sibling still
2805            // relying on it.
2806            git::acquire_worktree_config(&repo).await?;
2807            self.state.enabled_worktree_config = true;
2808        }
2809
2810        // `[worktree] setup` hides its products per worktree, which needs the
2811        // same per-worktree config the hook does. Held until fold, like it.
2812        ensure_setup_config(&mut self.state, &repo).await?;
2813
2814        for (index, (spec, label)) in self
2815            .roles
2816            .implementers
2817            .clone()
2818            .into_iter()
2819            .zip(labels)
2820            .enumerate()
2821        {
2822            let branch = self.state.branch_for(label);
2823            let worktree = root.join(format!("cand-{label}"));
2824            // Persist intent before Git can leave a partially created tree.
2825            // Candidate registration follows setup, so it cannot inventory
2826            // crashes or refusals during creation itself.
2827            self.state.event(
2828                "prep-intent",
2829                serde_json::json!({
2830                    "branch": branch,
2831                    "worktree": worktree,
2832                    "start": start,
2833                    "picks": plan.picks,
2834                })
2835                .to_string(),
2836            );
2837            self.state.save()?;
2838            git::worktree_add_branch(&repo, &worktree, &branch, &start).await?;
2839            if self.state.config.blind.commit_msg_hook {
2840                git::set_worktree_hooks_path(&worktree, &hooks_dir).await?;
2841            }
2842            git::local_exclude(&worktree, "/.magi/").await?;
2843            if let Err(e) = worktree_setup::prepare_with(
2844                &self.state.config,
2845                &repo,
2846                &worktree,
2847                crate::build_target::Coordination::Held(_coordination.as_ref()),
2848            )
2849            .await
2850            {
2851                // Nothing of this prep may survive: a resume must start over,
2852                // not find half the candidates and skip the rest.
2853                git::worktree_remove_clean(&repo, &worktree).await.ok();
2854                git::branch_delete(&repo, &branch).await.ok();
2855                self.rollback_prep(&repo).await;
2856                self.state.status = RunStatus::Blocked;
2857                self.state
2858                    .event("prep", format!("worktree setup failed: {e:#}"));
2859                if !e.is::<crate::repo_lock::ResourceBlocked>() {
2860                    self.state.prep_failure = Some(format!("worktree setup failed: {e:#}"));
2861                }
2862                self.state.save()?;
2863                return Err(e);
2864            }
2865            self.state.candidates.push(Candidate {
2866                index,
2867                label,
2868                agent: spec.id.clone(),
2869                branch,
2870                worktree,
2871                summary: String::new(),
2872                stat: String::new(),
2873                files: 0,
2874                commits: 0,
2875                empty: false,
2876                failed: None,
2877                verified_noop: None,
2878                duration_ms: 0,
2879                folded: false,
2880            });
2881            self.state.save()?;
2882            for pick in &plan.picks {
2883                if let Err(e) = git::cherry_pick(&self.state.candidates[index].worktree, pick).await
2884                {
2885                    self.state.status = RunStatus::Blocked;
2886                    self.state.prep_failure = Some(format!("cannot apply referenced commit: {e}"));
2887                    self.state
2888                        .event("prep", format!("cannot apply referenced commit: {e}"));
2889                    self.state.save()?;
2890                    return Err(e);
2891                }
2892            }
2893        }
2894
2895        for j in 1..=self.roles.judges.len() {
2896            let wt = root.join(format!("judge-{j}"));
2897            if !wt.exists() {
2898                git::worktree_add_detached(&repo, &wt, &base).await?;
2899                self.setup_seat_worktree(&repo, &wt, true, _coordination.as_ref())
2900                    .await?;
2901            }
2902        }
2903
2904        // Disposable, detached checkouts for the design-deliberation stage's
2905        // advisor seats — the same shape as the judges' above, at the same
2906        // base commit, since advisors also only ever read. Sized off the
2907        // configured count directly rather than a resolved roster: unlike
2908        // `implementers`/`judges`/`reviewers`, advisor seats are resolved
2909        // lazily inside `advise` itself (see `Config::advisors`'s doc), so
2910        // `prep` has no `ResolvedRoles` field to read a count from here.
2911        if self.state.config.graph.advise {
2912            for k in 1..=self.state.config.graph.advisors {
2913                let wt = root.join(format!("advisor-{k}"));
2914                if !wt.exists() {
2915                    git::worktree_add_detached(&repo, &wt, &base).await?;
2916                    self.setup_seat_worktree(&repo, &wt, true, _coordination.as_ref())
2917                        .await?;
2918                }
2919            }
2920        }
2921
2922        // A judge cannot tell it is looking at its own patch — the seats keep
2923        // separate conversations — but a panel that shares agents with the
2924        // field is less independent than it looks, and that is worth saying out
2925        // loud once per run rather than leaving it in the config.
2926        let authors: Vec<&str> = self
2927            .roles
2928            .implementers
2929            .iter()
2930            .map(|a| a.id.as_str())
2931            .collect();
2932        let overlap: Vec<String> = self
2933            .roles
2934            .judges
2935            .iter()
2936            .enumerate()
2937            .filter(|(_, j)| authors.contains(&j.id.as_str()))
2938            .map(|(i, j)| format!("judge {} = {}", i + 1, j.id))
2939            .collect();
2940        if !overlap.is_empty() {
2941            let note = format!(
2942                "{} also authored a candidate; blind, but the panel is less \
2943                 independent than {} distinct agents would be",
2944                overlap.join(", "),
2945                self.roles.judges.len()
2946            );
2947            self.state.event("prep", note);
2948        }
2949
2950        self.state.event(
2951            "prep",
2952            format!(
2953                "{} candidates, {} judges, base {} ({})",
2954                self.state.candidates.len(),
2955                self.roles.judges.len(),
2956                &self.state.base_commit[..7.min(self.state.base_commit.len())],
2957                self.state.base_branch
2958            ),
2959        );
2960        self.state.prep_complete = Some(true);
2961        self.state.status = RunStatus::Implementing;
2962        self.state.save()?;
2963        Ok(())
2964    }
2965
2966    // -------------------------------------------------------------- advise
2967
2968    /// The design-deliberation stage: independent, read-only advisor seats
2969    /// each sketch a design before any implementer touches the repository,
2970    /// and (when at least one produced a usable proposal) a synthesis seat
2971    /// blends them into a brief `implement` carries in every candidate's
2972    /// prompt.
2973    ///
2974    /// `[graph] advise` is the on/off switch, on by default; `[graph]
2975    /// advisors` is the proposal count. Everything here is best-effort and
2976    /// non-fatal to the run: a misconfigured `[roles] advisors`, a roster
2977    /// that cannot reach quota, or a synthesis seat that produced nothing
2978    /// usable all leave `implement` exactly as it was before this stage
2979    /// existed — the task instruction alone — rather than failing the whole
2980    /// competition over an enrichment stage. Every outcome is still recorded
2981    /// as an event, so a run that got nothing from this stage says why.
2982    ///
2983    /// [`RunState::advise_attempted`] is this node's idempotency marker, the
2984    /// same role [`RunState::judge_skipped`] plays for `judge`: without it a
2985    /// resumed run whose stage failed would re-run it, and re-spend the
2986    /// agent calls, on every reentry before `implement`.
2987    ///
2988    /// Also skipped once any candidate shows implementation progress — the
2989    /// exact predicate `implement` itself uses to decide a candidate is no
2990    /// longer "todo" (see its own `todo` filter). `advise_attempted` alone
2991    /// is not enough: a run created by an older binary that predates this
2992    /// field deserializes it as `false` (`#[serde(default)]`), so resuming
2993    /// an already-`Implementing`-or-later run under this build would
2994    /// otherwise walk straight back through `prep` (a no-op once candidates
2995    /// exist) into this node and spawn every advisor seat against worktrees
2996    /// `prep` never recreated — after implementation has already started,
2997    /// which is exactly the invariant this stage exists to guarantee.
2998    async fn advise(&mut self) -> Result<()> {
2999        let implement_untouched = self
3000            .state
3001            .candidates
3002            .iter()
3003            .all(|c| c.commits == 0 && c.failed.is_none() && !c.empty);
3004        if !self.state.config.graph.advise || self.state.advise_attempted {
3005            return Ok(());
3006        }
3007        if !implement_untouched {
3008            self.state.event(
3009                "advise",
3010                "skipping the design-deliberation stage: at least one \
3011                 candidate already shows implementation progress, so this \
3012                 run is past the point the stage exists to run before"
3013                    .to_owned(),
3014            );
3015            self.state.advise_attempted = true;
3016            self.state.save()?;
3017            return Ok(());
3018        }
3019        let run_id = self.state.id.clone();
3020        let prompts = self.state.config.prompts.clone();
3021        let instruction = self.state.instruction.clone();
3022        let language = self.state.config.graph.language.clone();
3023        let root = self.state.worktree_root();
3024        let n = self.state.config.graph.advisors;
3025        let where_recorded = self.state.dir().join("run.json");
3026
3027        let seats = match self.state.config.advisors() {
3028            Ok(seats) if !seats.is_empty() => seats,
3029            Ok(_) => {
3030                self.state.event(
3031                    "advise",
3032                    format!(
3033                        "[graph] advisors is 0; skipping the design-deliberation \
3034                         stage and continuing without a synthesis brief (see {})",
3035                        where_recorded.display()
3036                    ),
3037                );
3038                self.state.advise_attempted = true;
3039                self.state.save()?;
3040                return Ok(());
3041            }
3042            Err(e) => {
3043                self.state.event(
3044                    "advise",
3045                    format!(
3046                        "could not resolve advisor seats ({e:#}); continuing \
3047                         without a design-deliberation brief (see {})",
3048                        where_recorded.display()
3049                    ),
3050                );
3051                self.state.advise_attempted = true;
3052                self.state.save()?;
3053                return Ok(());
3054            }
3055        };
3056
3057        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
3058        let artifacts = agent::artifacts_dir(&self.state.dir());
3059        let worktrees: Vec<PathBuf> = (1..=n).map(|k| root.join(format!("advisor-{k}"))).collect();
3060
3061        let mut jobs = Vec::new();
3062        for (i, spec) in seats.iter().cloned().enumerate() {
3063            let seat_key = format!("advisor-{}", i + 1);
3064            let seat = self.seat(&seat_key, &spec.id);
3065            jobs.push(SeatJob {
3066                prompt: prompt::advisor(&instruction, i + 1, seats.len(), &language),
3067                spec,
3068                seat,
3069                cwd: worktrees[i % worktrees.len()].clone(),
3070                timeout,
3071                allow_write: false,
3072                sessions: false,
3073                artifacts: artifacts.clone(),
3074                stem: seat_key,
3075                handover: None,
3076            });
3077        }
3078
3079        self.state.event(
3080            "advise",
3081            format!(
3082                "{} advisor seat(s) sketching a design in parallel",
3083                jobs.len()
3084            ),
3085        );
3086        let mut quota_losses = Vec::new();
3087        let cache = self.state.config.cache_dir();
3088        let ctx = WaveCtx {
3089            carry_seats: false,
3090            pauses: Some((&self.pause, &self.interrupt)),
3091            run: &run_id,
3092            node: "advise",
3093            prompts: &prompts,
3094            cache: cache.as_deref(),
3095            round: None,
3096        };
3097        let advisor_roster = self.state.config.advisor_roster().unwrap_or_default();
3098        let results = ask_json_wave::<Proposal>(
3099            jobs,
3100            Arc::clone(&self.sem),
3101            self.state.config.graph.retries,
3102            &advisor_roster,
3103            &ctx,
3104            &mut quota_losses,
3105            &mut self.state,
3106            &|p: &Proposal| p.validate(),
3107        )
3108        .await;
3109        if self.state.resource_block.is_some() {
3110            return self.stop_for_resource();
3111        }
3112        self.state.quota.extend(quota_losses);
3113
3114        let mut records = Vec::with_capacity(results.len());
3115        for (i, (seat, res, _attempts)) in results.into_iter().enumerate() {
3116            let agent_id = seat.agent.clone();
3117            self.state.seats.insert(seat.key.clone(), seat);
3118            match res {
3119                Ok((proposal, out)) => {
3120                    self.state
3121                        .event("advise", format!("advisor-{} proposed a design", i + 1));
3122                    records.push(advise::AdvisorRecord::proposed(
3123                        i + 1,
3124                        agent_id,
3125                        proposal,
3126                        out.duration_ms,
3127                    ));
3128                }
3129                Err(e) => {
3130                    self.state.event(
3131                        "advise",
3132                        format!("advisor-{} produced no usable proposal: {e:#}", i + 1),
3133                    );
3134                    records.push(advise::AdvisorRecord::failed(
3135                        i + 1,
3136                        agent_id,
3137                        e.to_string(),
3138                    ));
3139                }
3140            }
3141        }
3142
3143        let mut advice = advise::Advice {
3144            records,
3145            synthesis: None,
3146        };
3147        if advice.proposals().is_empty() {
3148            self.state.event(
3149                "advise",
3150                "no advisor produced a usable proposal; continuing without a \
3151                 synthesis brief"
3152                    .to_owned(),
3153            );
3154        } else {
3155            match self
3156                .synthesize_brief(
3157                    &advice,
3158                    &instruction,
3159                    &language,
3160                    &worktrees[0],
3161                    &artifacts,
3162                    &run_id,
3163                    &prompts,
3164                    cache.as_deref(),
3165                )
3166                .await
3167            {
3168                Ok(Some(text)) => {
3169                    self.state.event(
3170                        "advise",
3171                        "synthesized a design brief for the implementer".to_owned(),
3172                    );
3173                    advice.synthesis = Some(text);
3174                }
3175                Ok(None) => {
3176                    self.state.event(
3177                        "advise",
3178                        "the synthesis seat produced nothing usable; continuing \
3179                         without a design brief"
3180                            .to_owned(),
3181                    );
3182                }
3183                Err(e) => {
3184                    if e.is::<crate::repo_lock::ResourceBlocked>() {
3185                        return Err(e);
3186                    }
3187                    self.state.event(
3188                        "advise",
3189                        format!("could not synthesize a design brief: {e:#}"),
3190                    );
3191                }
3192            }
3193        }
3194        advise::apply_reflection(&mut advice);
3195
3196        self.state.advice = Some(advice);
3197        self.state.advise_attempted = true;
3198        self.state.save()?;
3199        Ok(())
3200    }
3201
3202    /// The synthesis seat: reads every advisor's proposal and blends them
3203    /// into the design brief `advise` stores on [`RunState::advice`]. Split
3204    /// out of [`Runner::advise`] only for readability — it is not called
3205    /// anywhere else.
3206    ///
3207    /// Picked the same way [`crate::talk`]'s standing conversation and
3208    /// [`crate::bump`]'s release-bump decision are: [`agent::pick`], with
3209    /// `[roles] synthesizer` checked first and [`agent::pick`]'s own default
3210    /// order (a claude seat, else the first runnable agent in roster order)
3211    /// used when that field is unset — see `[roles] synthesizer`'s own doc
3212    /// in [`crate::config`] for why a dedicated field exists here at all.
3213    #[allow(clippy::too_many_arguments)]
3214    async fn synthesize_brief(
3215        &mut self,
3216        advice: &advise::Advice,
3217        instruction: &str,
3218        language: &str,
3219        cwd: &Path,
3220        artifacts: &Path,
3221        run_id: &str,
3222        prompts: &Prompts,
3223        cache: Option<&Path>,
3224    ) -> Result<Option<String>> {
3225        let chain = agent::pick_chain(
3226            &self.state.config.agents,
3227            self.state.config.roles.synthesizer.as_ref(),
3228            &agent::installed,
3229            "synthesizer",
3230        )?;
3231        let proposals = advice.proposals();
3232        let mut prompt = prompt::with_overlay(
3233            prompt::synthesize_brief(instruction, &proposals, language),
3234            prompts.overlay("advise"),
3235        );
3236        if cache.is_some() {
3237            // This seat never writes, so it is never handed `CARGO_TARGET_DIR`
3238            // below — see `prompt::build_cache_note`'s doc for why telling a
3239            // read-only seat to build through the shared cache is exactly how
3240            // a sandbox's write refusal gets misread as a defect.
3241            prompt.push('\n');
3242            prompt.push_str(&prompt::build_cache_note("advise", false));
3243        }
3244        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
3245        // Each id is tried once, in order; a quota hit, error or unusable
3246        // answer moves to the next. The seat is single-turn (`sessions:
3247        // false`) and the prompt is the whole context, so a fallback agent
3248        // needs nothing carried over.
3249        let mut last = None;
3250        for (n, spec) in chain.iter().enumerate() {
3251            if n > 0 {
3252                self.state
3253                    .event("advise", format!("synthesis falling back to {}", spec.id));
3254            }
3255            let mut seat = self.seat("advise-synthesis", &spec.id);
3256            let wait = self.repository_wait();
3257            let outcome = wait
3258                .scope(agent::invoke(
3259                    spec,
3260                    &mut seat,
3261                    &Invocation {
3262                        coordination: self.state.config.coordination.as_ref(),
3263                        fetched_base: None,
3264                        cwd,
3265                        prompt: &prompt,
3266                        timeout,
3267                        allow_write: false,
3268                        sessions: false,
3269                        artifacts,
3270                        stem: &if n == 0 {
3271                            "advise-synthesis".to_owned()
3272                        } else {
3273                            format!("advise-synthesis-{}", spec.id)
3274                        },
3275                        run: run_id,
3276                        node: "advise",
3277                        cache_dir: None,
3278                        attachments: &[],
3279                        writable: &[],
3280                    },
3281                ))
3282                .await;
3283            if outcome.is_ok() {
3284                self.state.seats.insert(seat.key.clone(), seat);
3285            }
3286            let advance = agent::chain_advances(&outcome);
3287            last = Some(outcome);
3288            if !advance {
3289                break;
3290            }
3291        }
3292        // Exhausted: the last attempt's result is what a single failed seat
3293        // would have produced.
3294        let out = last.expect("a chain holds at least one agent")?;
3295        if !out.usable() {
3296            return Ok(None);
3297        }
3298        let text =
3299            verdict::section(&out.text, "synthesis").unwrap_or_else(|| out.text.trim().to_owned());
3300        Ok((!text.trim().is_empty()).then_some(text))
3301    }
3302
3303    // ----------------------------------------------------------- implement
3304
3305    async fn implement(&mut self) -> Result<()> {
3306        self.persist_candidates().await?;
3307        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
3308        // agent files with `magi task add` name the run that paid for it. The
3309        // prompt overlay is cloned alongside it because the waves borrow it
3310        // while `self` is mutably borrowed by the node's own bookkeeping.
3311        let run_id = self.state.id.clone();
3312        let prompts = self.state.config.prompts.clone();
3313        let todo: Vec<usize> = self
3314            .state
3315            .candidates
3316            .iter()
3317            .enumerate()
3318            .filter(|(_, c)| {
3319                (c.commits == 0 || self.state.interrupted_implementations.contains(&c.label))
3320                    && c.failed.is_none()
3321                    && !c.empty
3322            })
3323            .map(|(i, _)| i)
3324            .collect();
3325        if todo.is_empty() {
3326            return self.after_implement();
3327        }
3328        self.state.status = RunStatus::Implementing;
3329
3330        let language = self.state.config.graph.language.clone();
3331        let github_language = self.state.config.graph.github_language.clone();
3332        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
3333        let sessions = self.state.config.graph.sessions;
3334        let artifacts = agent::artifacts_dir(&self.state.dir());
3335        // The design-deliberation stage's blended brief, when `advise` found
3336        // one — carried into every implementer's prompt the same way
3337        // regardless of which candidate it is.
3338        let brief = self
3339            .state
3340            .advice
3341            .as_ref()
3342            .and_then(|a| a.synthesis.as_deref())
3343            .map(str::to_owned);
3344        let attachments = self.state.attachments.clone();
3345
3346        let mut jobs = Vec::new();
3347        for &i in &todo {
3348            let (index, label, worktree) = {
3349                let c = &self.state.candidates[i];
3350                (c.index, c.label, c.worktree.clone())
3351            };
3352            let spec = self.roles.implementers[index].clone();
3353            let seat_key = format!("impl-{label}");
3354            let seat = self.seat(&seat_key, &spec.id);
3355            let instruction = seeded_instruction(&self.state);
3356            jobs.push(SeatJob {
3357                spec,
3358                seat,
3359                prompt: prompt::implement_in(
3360                    &instruction,
3361                    &worktree.to_string_lossy(),
3362                    &language,
3363                    &github_language,
3364                    brief.as_deref(),
3365                    &attachments,
3366                ),
3367                cwd: worktree,
3368                timeout,
3369                allow_write: true,
3370                sessions,
3371                artifacts: artifacts.clone(),
3372                stem: format!("impl-{label}"),
3373                handover: None,
3374            });
3375        }
3376
3377        self.state.event(
3378            "implement",
3379            format!("{} candidates in parallel", jobs.len()),
3380        );
3381        // Kept so a seat whose CLI hung up can be asked again from the same
3382        // job: `wave` consumes what it is given. Mutable so `resume_seat_handovers`
3383        // can update a seat's own entry once a fallback agent takes it over —
3384        // `resume_unconfirmed_commands`, which reads `sent` afterward, must see
3385        // whichever agent actually answered, not the one that quota'd out.
3386        let mut sent = jobs.clone();
3387        // Where each seat's checkout stood before its turn. A reply is judged
3388        // against this, never against the run's base: a tree that carries an
3389        // inherited patch is ahead of the base before the seat does anything.
3390        let mut baselines = Vec::with_capacity(sent.len());
3391        for (job, &i) in sent.iter().zip(&todo) {
3392            baselines.push((
3393                self.state.candidates[i].label,
3394                git::rev_parse(&job.cwd, "HEAD").await.ok(),
3395            ));
3396        }
3397        let cache = self.state.config.cache_dir();
3398        let ctx = WaveCtx {
3399            carry_seats: false,
3400            pauses: Some((&self.pause, &self.interrupt)),
3401            run: &run_id,
3402            node: "implement",
3403            prompts: &prompts,
3404            cache: cache.as_deref(),
3405            round: None,
3406        };
3407        let mut results = wave(jobs, Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
3408        if !wave_blocked(&results) {
3409            self.resume_undelivered(&mut results, &sent, &prompts, &run_id)
3410                .await;
3411            self.retry_unstarted(&mut results, &sent, &baselines, &prompts, &run_id)
3412                .await?;
3413            self.resume_seat_handovers(&mut results, &mut sent, &prompts, &run_id)
3414                .await?;
3415            self.resume_unconfirmed_commands(&mut results, &sent, &prompts, &run_id)
3416                .await;
3417        }
3418        // Do not finalize failed candidates when the entire wave needs machine
3419        // recovery: leaving them pending resumes this node with its work intact.
3420        if !results.is_empty()
3421            && results
3422                .iter()
3423                .all(|(_, _, out)| matches!(out, AgentOutcome::Quota(_)))
3424        {
3425            let losses: Vec<_> = results
3426                .iter()
3427                .map(|(_, seat, out)| {
3428                    let AgentOutcome::Quota(o) = out else {
3429                        unreachable!()
3430                    };
3431                    QuotaLoss::from_report(seat.key.clone(), "implement", o.quota.as_ref())
3432                })
3433                .collect();
3434            self.state.quota.extend(losses.clone());
3435            for (_, seat, _) in results {
3436                self.state.seats.insert(seat.key.clone(), seat);
3437            }
3438            for &i in &todo {
3439                let label = self.state.candidates[i].label;
3440                self.state.interrupted_implementations.insert(label);
3441                self.state
3442                    .candidate_preservation
3443                    .insert(label, "machine outage awaiting persistence".into());
3444            }
3445            // Preserve partial edits too, while keeping every interrupted seat
3446            // pending even when its tree already contains an inherited patch.
3447            block_machine_outage(&mut self.state, "implement", &losses);
3448            self.state.save()?;
3449            self.persist_candidates().await?;
3450            for &i in &todo {
3451                self.state
3452                    .interrupted_implementations
3453                    .insert(self.state.candidates[i].label);
3454            }
3455            return self.stop_for_resource();
3456        }
3457        let resource_blocked = self.state.resource_block.is_some() || wave_blocked(&results);
3458
3459        let selected_failed = self.state.config.graph.selected_implementer.is_some()
3460            && results
3461                .iter()
3462                .any(|(_, _, out)| FailClass::of(out).is_some());
3463        let base_commit = self.state.base_commit.clone();
3464        let blind_cfg = self.state.config.blind.clone();
3465        let mut rejected_noops: Vec<(char, String)> = Vec::new();
3466        for (&i, (_wi, seat, out)) in todo.iter().zip(results) {
3467            if matches!(out, AgentOutcome::ResourceBlocked(_)) {
3468                // Executed turns interrupted by disk pressure already carry
3469                // a preservation barrier from wave. Admission-only waits do
3470                // not. Keep the interrupted seat's session for recovery too.
3471                if self
3472                    .state
3473                    .candidate_preservation
3474                    .contains_key(&self.state.candidates[i].label)
3475                {
3476                    self.state.seats.insert(seat.key.clone(), seat);
3477                }
3478                continue;
3479            }
3480            let seat_key = seat.key.clone();
3481            // A quota fallback (`resume_seat_handovers`) may have handed this
3482            // seat to a different agent than the one `prep` recorded on the
3483            // candidate; the stats tables and any later fixer-defaults-to-
3484            // winner's-author lookup must credit whoever actually answered —
3485            // unless every fallback also quota'd out, in which case nobody
3486            // actually answered and crediting the last agent tried would
3487            // erase every earlier agent's own quota loss from the stats
3488            // tables instead of just this one seat's.
3489            let agent = seat.agent.clone();
3490            let exhausted_the_fallback_chain = FailClass::of(&out).is_some();
3491            self.state.seats.insert(seat.key.clone(), seat);
3492            let label = self.state.candidates[i].label;
3493            let worktree = self.state.candidates[i].worktree.clone();
3494            self.state.interrupted_implementations.remove(&label);
3495
3496            let (sanitized_summary, duration, failed, verified_claim) = match out {
3497                AgentOutcome::Ok(o) => {
3498                    let text = verdict::section(&o.text, "summary").unwrap_or(o.text.clone());
3499                    let failed = (!o.usable()).then(|| {
3500                        if o.timed_out {
3501                            "agent timed out".to_owned()
3502                        } else {
3503                            format!(
3504                                "agent exited with {}",
3505                                crate::notices::exit_status(o.exit_code)
3506                            )
3507                        }
3508                    });
3509                    let sanitized_summary = blind::sanitize_prose(&text, &blind_cfg);
3510                    let verified_claim = match verified_noop_claim_in_worktree(
3511                        failed.is_none(),
3512                        &o.commands,
3513                        &text,
3514                        &worktree,
3515                        &base_commit,
3516                    )
3517                    .await
3518                    {
3519                        NoopClaimVerdict::Accepted => {
3520                            if matches!(
3521                                verdict::parse_verified_noop(&sanitized_summary),
3522                                Some(Ok(_))
3523                            ) {
3524                                Some(sanitized_summary.clone())
3525                            } else {
3526                                rejected_noops.push((
3527                                    label,
3528                                    "structured NO CHANGE NEEDED summary became invalid after blind sanitization".to_owned(),
3529                                ));
3530                                None
3531                            }
3532                        }
3533                        NoopClaimVerdict::Rejected(reason) => {
3534                            rejected_noops.push((label, reason));
3535                            None
3536                        }
3537                        NoopClaimVerdict::Absent => None,
3538                    };
3539                    (sanitized_summary, o.duration_ms, failed, verified_claim)
3540                }
3541                // Left un-resumed by `resume_undelivered` (a dirty tree
3542                // already rescues the work, or there was no session left to
3543                // resume into) — reported like the ordinary failure it is,
3544                // never as if `o.text` (the CLI's raw error JSON) were an
3545                // answer.
3546                AgentOutcome::Dropped(o) => {
3547                    let why = o
3548                        .dropped
3549                        .as_ref()
3550                        .map(|d| d.why.as_str())
3551                        .unwrap_or("the CLI ended the stream without delivering its answer");
3552                    (
3553                        String::new(),
3554                        o.duration_ms,
3555                        Some(format!("the CLI dropped the stream ({why})")),
3556                        None,
3557                    )
3558                }
3559                AgentOutcome::Quota(o) => {
3560                    self.state.quota.push(QuotaLoss::from_report(
3561                        seat_key,
3562                        "implement",
3563                        o.quota.as_ref(),
3564                    ));
3565                    (
3566                        String::new(),
3567                        o.duration_ms,
3568                        Some("rate limited (quota); produced no change".to_owned()),
3569                        None,
3570                    )
3571                }
3572                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
3573                    (String::new(), 0, Some(e), None)
3574                }
3575            };
3576
3577            // Save every completed turn before any fallible Git operation. A failed
3578            // rescue must not erase the reply or prevent collection of other seats.
3579            let c = &mut self.state.candidates[i];
3580            if !exhausted_the_fallback_chain {
3581                c.agent = agent;
3582            }
3583            c.summary = sanitized_summary;
3584            c.duration_ms = duration;
3585            c.failed = failed;
3586            c.verified_noop = verified_claim;
3587            self.state
3588                .candidate_preservation
3589                .insert(label, "awaiting persistence".to_owned());
3590        }
3591        self.state.save()?;
3592        self.persist_candidates().await?;
3593
3594        let mut recorded_rejection = false;
3595        for (label, reason) in rejected_noops {
3596            if self.state.interrupted_implementations.contains(&label) {
3597                continue;
3598            }
3599            if let Some(c) = self.state.candidates.iter_mut().find(|c| c.label == label)
3600                && c.empty
3601            {
3602                c.verified_noop = None;
3603                c.failed
3604                    .get_or_insert_with(|| format!("no-op claim rejected: {reason}"));
3605                self.state.event(
3606                    "implement",
3607                    format!("candidate {label}: rejected NO CHANGE NEEDED claim: {reason}"),
3608                );
3609                recorded_rejection = true;
3610            }
3611        }
3612        if recorded_rejection {
3613            self.state.save()?;
3614        }
3615
3616        if resource_blocked {
3617            return self.stop_for_resource();
3618        }
3619        if selected_failed {
3620            self.state.status = RunStatus::Blocked;
3621            self.state.event("implement", "selected implementer failed or hit quota; holding without fallback, review or publication");
3622            self.state.save()?;
3623            bail!(
3624                "selected implementer unavailable or quota-limited; restore availability and explicitly release the task"
3625            );
3626        }
3627        self.after_implement()
3628    }
3629
3630    /// Retry only persistence after a completed implementation turn.
3631    async fn persist_candidates(&mut self) -> Result<()> {
3632        let labels: Vec<_> = self.state.candidate_preservation.keys().copied().collect();
3633        for label in labels {
3634            let i = self
3635                .state
3636                .candidates
3637                .iter()
3638                .position(|c| c.label == label)
3639                .context("pending candidate is missing")?;
3640            let c = self.state.candidates[i].clone();
3641            let interrupted = self.state.interrupted_implementations.contains(&label);
3642            let result = async {
3643                let wait = crate::repo_lock::WaitPolicy::new(
3644                    Duration::from_secs(self.state.config.graph.timeout_resource_wait),
3645                    || false,
3646                );
3647                let _coordination =
3648                    coordinate_operation(&mut self.state, &c.worktree, &wait).await?;
3649                // Best effort evidence requires no index writes. A successful snapshot
3650                // never authorizes removal of a tree whose rescue failed.
3651                if let Err(e) = git::snapshot_uncommitted(
3652                    &c.worktree,
3653                    &self
3654                        .state
3655                        .dir()
3656                        .join("artifacts")
3657                        .join(format!("candidate-{label}-recovery")),
3658                )
3659                .await
3660                {
3661                    self.state.event(
3662                        "preserve",
3663                        format!("candidate {label} snapshot incomplete: {e:#}"),
3664                    );
3665                }
3666                let rescued = git::rescue_commit(
3667                    &c.worktree,
3668                    &format!("magi: candidate {label} (uncommitted work)"),
3669                )
3670                .await?;
3671                self.state.note_withheld("implement", &rescued.withheld);
3672                let base = &self.state.base_commit;
3673                let commits = git::commits_ahead(&c.worktree, base, "HEAD").await?;
3674                let patch = git::diff(&c.worktree, base, "HEAD").await?;
3675                let stat = git::diff_stat(&c.worktree, base, "HEAD").await?;
3676                let files = git::changed_files(&c.worktree, base, "HEAD").await?.len();
3677                write_artifact(&self.state, &format!("cand-{label}.patch"), &patch)?;
3678                if c.empty && commits > 0 && !patch.trim().is_empty()
3679                    && (self.state.judge_skipped || !self.state.judgements.is_empty()
3680                        || !self.state.deliberation.is_empty() || !self.state.votes.is_empty()
3681                        || self.state.tally.is_some())
3682                {
3683                    // Keep the old classification and pending marker so every
3684                    // retry stops too. Retain decisions as recovery evidence;
3685                    // only a supported recovery operation may replace them.
3686                    bail!("candidate {label} changes the judged candidate set; supported recovery and fresh judging are required before continuing");
3687                }
3688                let c = &mut self.state.candidates[i];
3689                c.commits = commits;
3690                c.stat = stat;
3691                c.files = files;
3692                let no_changes = commits == 0 || patch.trim().is_empty();
3693                c.empty = no_changes && !interrupted;
3694                if interrupted && no_changes {
3695                    c.failed = None;
3696                    c.verified_noop = None;
3697                }
3698                if !c.empty {
3699                    c.failed = None;
3700                    c.verified_noop = None;
3701                }
3702                self.state.event(
3703                    "preserve",
3704                    format!("candidate {label}: {files} files, {commits} commits"),
3705                );
3706                Ok::<_, anyhow::Error>(())
3707            }
3708            .await;
3709            match result {
3710                Ok(()) => {
3711                    self.state.candidate_preservation.remove(&label);
3712                    if !interrupted || self.state.candidates[i].files > 0 {
3713                        self.state.interrupted_implementations.remove(&label);
3714                    }
3715                }
3716                Err(e) => {
3717                    let reason = format!("candidate {label} preservation failed: {e:#}");
3718                    self.state.event("preserve", &reason);
3719                    self.state.candidate_preservation.insert(label, reason);
3720                }
3721            }
3722            if self.state.candidate_preservation.is_empty()
3723                && self.state.status == RunStatus::Blocked
3724                && self.state.candidates.iter().all(|c| c.failed.is_none())
3725            {
3726                // Persist the recovered phase with the cleared pending marker;
3727                // a crash between saves must not turn this into a selected-seat
3728                // failure hold on the next resume.
3729                self.state.status = RunStatus::Implementing;
3730                self.state.event(
3731                    "preserve",
3732                    "candidate persistence recovered; implementation can continue",
3733                );
3734            }
3735            self.state.save()?;
3736        }
3737        if !self.state.candidate_preservation.is_empty() {
3738            self.state.status = RunStatus::Blocked;
3739            self.state.save()?;
3740            bail!(
3741                "candidate preservation incomplete; retain worktrees and artifacts, repair persistence and resume this run"
3742            );
3743        }
3744        Ok(())
3745    }
3746
3747    /// Ask again, once, for work a CLI did and then failed to hand over.
3748    ///
3749    /// [`agent::dropped_stream`] recognises the one shape observed: an error
3750    /// status with an empty response and a usage report showing output tokens,
3751    /// i.e. **billed work with nothing delivered**. Run 26c7's candidate B was
3752    /// seven minutes and 14,267 output tokens that arrived as an empty
3753    /// candidate, because `agy`'s own subscriber fell behind and hung up.
3754    ///
3755    /// Two conditions, and both matter:
3756    ///
3757    /// - **Only when the tree is untouched.** Often the agent has already
3758    ///   written its files and only the closing message was lost; the rescue
3759    ///   commit below picks that up and there is nothing to ask for. Re-asking
3760    ///   then would pay for a second implementation of work already on disk.
3761    /// - **Once.** A CLI that drops one stream can drop the next, and this
3762    ///   node is the most expensive in the graph.
3763    ///
3764    /// The re-ask is a resume, not a re-run: `has_context` is true because the
3765    /// dropped reply still carried its `conversation_id`, so the seat is asked
3766    /// to finish what it was doing rather than sent the whole task again. It
3767    /// therefore gets a nudge's budget ([`retry_budget`]) - a quarter of the
3768    /// node's - for the same reason a re-ranked judge does: restating finished
3769    /// work is not the work.
3770    ///
3771    /// Unlike a quota this is worth retrying at all: a rate limit fails the
3772    /// same way until it resets, while an abandoned conversation is still
3773    /// there to be picked up.
3774    async fn resume_undelivered(
3775        &mut self,
3776        results: &mut [(usize, SeatState, AgentOutcome)],
3777        sent: &[SeatJob],
3778        prompts: &Prompts,
3779        run_id: &str,
3780    ) {
3781        for (wi, seat, out) in results.iter_mut() {
3782            let Some(dropped) = (match &*out {
3783                AgentOutcome::Dropped(o) => o.dropped.clone(),
3784                _ => None,
3785            }) else {
3786                continue;
3787            };
3788            let Some(job) = sent.get(*wi) else { continue };
3789            // Already on disk? Then only the closing message was lost.
3790            if !git::is_clean(&job.cwd).await.unwrap_or(true) {
3791                self.state.event(
3792                    "implement",
3793                    format!(
3794                        "{}: the CLI dropped the stream after {} output tokens ({}), but the \
3795                         work is in the tree",
3796                        seat.key, dropped.output_tokens, dropped.why
3797                    ),
3798                );
3799                continue;
3800            }
3801            // The re-ask only makes sense as a resume: `resume_after_drop`
3802            // says nothing about the task, trusting the seat to still hold it.
3803            // Without a session to resume — sessions disabled, or this CLI's
3804            // drop shape happened not to carry a session id — that prompt
3805            // would open a brand-new conversation with no context at all,
3806            // which is worse than leaving this as the ordinary failure it
3807            // already is.
3808            if !has_context(&job.spec, seat, job.sessions) {
3809                self.state.event(
3810                    "implement",
3811                    format!(
3812                        "{}: the CLI dropped the stream after {} output tokens ({}), but there \
3813                         is no session left to resume",
3814                        seat.key, dropped.output_tokens, dropped.why
3815                    ),
3816                );
3817                continue;
3818            }
3819            self.state.event(
3820                "implement",
3821                format!(
3822                    "{}: the CLI dropped the stream after {} output tokens ({}); resuming the \
3823                     conversation",
3824                    seat.key, dropped.output_tokens, dropped.why
3825                ),
3826            );
3827            let mut retry = job.clone();
3828            retry.seat = seat.clone();
3829            retry.prompt = prompt::resume_after_drop(&dropped.why);
3830            retry.timeout = retry_budget(job.timeout, true);
3831            retry.stem = format!("{}-resume", job.stem);
3832            let cache = self.state.config.cache_dir();
3833            let ctx = WaveCtx {
3834                carry_seats: false,
3835                pauses: Some((&self.pause, &self.interrupt)),
3836                run: run_id,
3837                node: "implement",
3838                prompts,
3839                cache: cache.as_deref(),
3840                round: None,
3841            };
3842            let (resumed_seat, resumed) =
3843                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
3844            *seat = resumed_seat;
3845            *out = resumed;
3846        }
3847    }
3848
3849    /// Fall an implement seat through to the next untried agent in the
3850    /// implementer roster when it lost to quota — or, since the handover was
3851    /// generalised, to a timeout or an ordinary failure (see [`FailClass`] and
3852    /// [`should_hand_over`] for when a non-quota failure stops the chain), the
3853    /// quota path itself being unchanged — instead of leaving the
3854    /// seat's loss final the moment one agent's account runs dry.
3855    ///
3856    /// Solo runs (`graph.implementers = 1`, `daemon::apply_solo`'s forced shape)
3857    /// are the motivating case: `Config::resolve_roles`'s `implementers`
3858    /// truncates to the single slot rotation picked, so a solo task whose one
3859    /// implementer hits quota mid-run used to have nothing else to try. This
3860    /// walks [`ResolvedRoles::implementer_roster`] instead — the untruncated,
3861    /// unrotated roster — which is the only place the *other* candidates in
3862    /// the machine's roster still exist once `implementers` has been cut down
3863    /// to size.
3864    ///
3865    /// Walks forward from just past the seat's own original position in the
3866    /// roster, never wrapping back to the front: a later candidate slot (say
3867    /// `beta`, the roster's second entry) must fall through to the *next*
3868    /// entry (`gamma`) on its own quota loss, not back to `alpha`, which is
3869    /// almost certainly a different candidate's own agent already — and once
3870    /// the roster's tail is exhausted there is nothing left to fall through
3871    /// to for *this* seat, wrapping or not. Tried by `spec.id`, never the
3872    /// whole [`AgentSpec`]: a roster with the same id named twice must not
3873    /// let this retry that id forever. The loop keeps falling through until
3874    /// an attempt lands something other than `Quota` or the roster's tail
3875    /// runs out of untried ids, at which point the seat is left exactly as
3876    /// `implement`'s own `AgentOutcome::Quota` arm already handles it: one
3877    /// `QuotaLoss` recorded, the candidate failed/empty.
3878    ///
3879    /// `sent` is taken mutably and updated with the fallback agent's spec:
3880    /// `resume_unconfirmed_commands`, which runs after this and also reads
3881    /// `sent`, must see whichever agent actually ended up answering the seat
3882    /// — reading the stale, original spec there would check session
3883    /// eligibility against the wrong CLI and could hand a fallback agent's
3884    /// session id to the agent that just lost the seat to quota.
3885    ///
3886    /// Every fallback gets a fresh [`SeatState`], never the quota'd seat's own
3887    /// — `self.seat` only reuses state when the agent id is unchanged, so
3888    /// handing it a different id already gets this for free. Reusing the old
3889    /// seat would resume a different CLI's session as if it were a
3890    /// continuation of this one.
3891    ///
3892    /// Unlike [`Runner::resume_undelivered`], not gated on a clean worktree:
3893    /// a quota loss cuts an agent off mid-turn, so anything already in the
3894    /// tree is unfinished work, not a completed candidate a re-ask would pay
3895    /// for twice. A dirty tree is rescued into a commit first (the same
3896    /// neutral-identity rescue `implement`'s own outcome loop gives every
3897    /// candidate) so the next agent starts clean.
3898    ///
3899    /// The new agent gets the implementer's full prompt and full
3900    /// `timeout_implement` budget, not `resume_after_drop`'s nudge-sized one:
3901    /// it has no session and no context, and is implementing the task from
3902    /// nothing, unlike a resumed drop which is only restating work already
3903    /// done.
3904    ///
3905    /// Every intermediate `Quota` this loop absorbs is folded into a plain
3906    /// `implement` event, never into `self.state.quota` — that is what
3907    /// `daemon.rs`'s own backoff reads to decide a run's task attempt should
3908    /// go unspent, and a seat that ultimately recovered on its second or
3909    /// third agent is not the stalled panel that check exists to catch. Only
3910    /// the final, unrecovered `Quota` (once the roster runs out) ever reaches
3911    /// `self.state.quota`, via the ordinary `AgentOutcome::Quota` arm the
3912    /// outcome loop already has — this helper never pushes to it itself.
3913    async fn resume_seat_handovers(
3914        &mut self,
3915        results: &mut [(usize, SeatState, AgentOutcome)],
3916        sent: &mut [SeatJob],
3917        prompts: &Prompts,
3918        run_id: &str,
3919    ) -> Result<()> {
3920        let instruction = seeded_instruction(&self.state);
3921        let language = self.state.config.graph.language.clone();
3922        let github_language = self.state.config.graph.github_language.clone();
3923        let brief = self
3924            .state
3925            .advice
3926            .as_ref()
3927            .and_then(|a| a.synthesis.as_deref())
3928            .map(str::to_owned);
3929        let attachments = self.state.attachments.clone();
3930        for (wi, seat, out) in results.iter_mut() {
3931            // Who holds the other candidate seats of this wave right now
3932            // (earlier handovers already written back to `sent`).
3933            let others: BTreeSet<String> = sent
3934                .iter()
3935                .enumerate()
3936                .filter(|(j, _)| j != wi)
3937                .map(|(_, j)| j.spec.id.clone())
3938                .collect();
3939            let Some(job) = sent.get_mut(*wi) else {
3940                continue;
3941            };
3942            // Where the seat's own original agent sits in the roster — the
3943            // fallback walk starts just past here, never at the front, so a
3944            // later candidate slot's quota loss does not fall back onto an
3945            // earlier slot's own agent.
3946            let start = self
3947                .roles
3948                .implementer_roster
3949                .iter()
3950                .position(|s| s.id == job.spec.id)
3951                .unwrap_or(0);
3952            let mut tried: BTreeSet<String> = BTreeSet::from([job.spec.id.clone()]);
3953            let mut fallback_attempt = 0usize;
3954            let mut prev: Option<FailClass> = None;
3955            while let Some(cur) = FailClass::of(&*out) {
3956                if !should_hand_over(prev.as_ref(), &cur) {
3957                    break;
3958                }
3959                let Some(next) =
3960                    pick_successor(&self.roles.implementer_roster, start, &tried, None, &others)
3961                        .cloned()
3962                else {
3963                    break;
3964                };
3965                tried.insert(next.id.clone());
3966                fallback_attempt += 1;
3967
3968                let coordination = self.coordinate(&job.cwd).await?;
3969                if let Ok(r) = git::rescue_commit(
3970                    &job.cwd,
3971                    &format!(
3972                        "magi: candidate {} (uncommitted work before {} fallback)",
3973                        seat.key,
3974                        if cur == FailClass::Quota {
3975                            "quota"
3976                        } else {
3977                            "handover"
3978                        }
3979                    ),
3980                )
3981                .await
3982                {
3983                    self.state.note_withheld("implement", &r.withheld);
3984                }
3985                drop(coordination);
3986
3987                record_handover(
3988                    &mut self.state,
3989                    "implement",
3990                    &seat.key,
3991                    &seat.agent,
3992                    &next.id,
3993                    &cur,
3994                    &fail_reason(&*out),
3995                );
3996                prev = Some(cur.clone());
3997
3998                let new_seat = handover_seat(&seat.key, &next.id, self.state.next_seat_seed());
3999                self.state.seats.insert(seat.key.clone(), new_seat.clone());
4000                // Kept in sync on `sent` itself, not just the local retry: a
4001                // later helper (`resume_unconfirmed_commands`) reads `sent`
4002                // after this one returns and must see whichever agent is now
4003                // occupying the seat, not the one that just quota'd out —
4004                // otherwise it would judge session/continuation eligibility
4005                // by the wrong CLI and could resend a fallback's session id
4006                // to the agent that lost it the seat in the first place.
4007                job.spec = next.clone();
4008                let mut retry = job.clone();
4009                retry.seat = new_seat;
4010                retry.prompt = prompt::implement_in(
4011                    &instruction,
4012                    &job.cwd.to_string_lossy(),
4013                    &language,
4014                    &github_language,
4015                    brief.as_deref(),
4016                    &attachments,
4017                );
4018                retry.stem = format!("{}-{}-{}", job.stem, cur.stem_word(), next.id);
4019                let cache = self.state.config.cache_dir();
4020                let ctx = WaveCtx {
4021                    carry_seats: false,
4022                    pauses: Some((&self.pause, &self.interrupt)),
4023                    run: run_id,
4024                    node: "implement",
4025                    prompts,
4026                    cache: cache.as_deref(),
4027                    round: None,
4028                };
4029                let (fallback_seat, fallback_out) = run_one(
4030                    retry,
4031                    Arc::clone(&self.sem),
4032                    &ctx,
4033                    &mut self.state,
4034                    fallback_attempt,
4035                )
4036                .await;
4037                *seat = fallback_seat;
4038                *out = fallback_out;
4039            }
4040        }
4041        Ok(())
4042    }
4043
4044    /// Ask an implement seat's own CLI to confirm what it started, once, when
4045    /// its reply reported a command whose completion status it never
4046    /// confirmed — see [`has_unconfirmed_command`]'s own doc for exactly what
4047    /// that does and does not mean.
4048    ///
4049    /// The completion contract this task asks for, extended to `implement`
4050    /// with the same signal `continue_fix_report` reads for the fixer,
4051    /// rather than a keyword search over the reply or a hard requirement on
4052    /// `## SUMMARY`'s presence — the shape behind fb35, 9566 and e185, where
4053    /// a candidate's CLI turn ended cleanly while a test run it had started
4054    /// had not. A short, ordinary reply with no `## SUMMARY` and no commands
4055    /// named in it at all is untouched by this: `commands` is empty, so
4056    /// there is nothing to be unconfirmed.
4057    ///
4058    /// Unlike `resume_undelivered`, not gated on the tree being untouched:
4059    /// this is not about recovering edits that might already be on disk, it
4060    /// is about a result the seat itself never vouched for, which resuming
4061    /// asks for regardless of what the tree already holds. Bounded to one
4062    /// attempt for the same reason `resume_undelivered` is — this is the
4063    /// most expensive node in the graph — and a seat that still cannot
4064    /// confirm on that attempt is left as whatever its (possibly still
4065    /// unconfirmed) reply says; this does not invent a new "failed" reason
4066    /// for a candidate that otherwise produced a real, committed change.
4067    async fn resume_unconfirmed_commands(
4068        &mut self,
4069        results: &mut [(usize, SeatState, AgentOutcome)],
4070        sent: &[SeatJob],
4071        prompts: &Prompts,
4072        run_id: &str,
4073    ) {
4074        for (wi, seat, out) in results.iter_mut() {
4075            let AgentOutcome::Ok(o) = &*out else {
4076                continue;
4077            };
4078            if !has_unconfirmed_command(&o.commands) {
4079                continue;
4080            }
4081            let Some(job) = sent.get(*wi) else { continue };
4082            if !has_context(&job.spec, seat, job.sessions) {
4083                self.state.event(
4084                    "implement",
4085                    format!(
4086                        "{}: the reply named a command whose own CLI never confirmed the exit \
4087                         status of, but there is no session left to resume",
4088                        seat.key
4089                    ),
4090                );
4091                continue;
4092            }
4093            self.state.event(
4094                "implement",
4095                format!(
4096                    "{}: the reply named a command whose own CLI never confirmed the exit \
4097                     status of; resuming the conversation",
4098                    seat.key
4099                ),
4100            );
4101            let mut retry = job.clone();
4102            retry.seat = seat.clone();
4103            retry.prompt = prompt::resume_incomplete(
4104                "a command in your last reply had no confirmed exit status",
4105            );
4106            retry.timeout = retry_budget(job.timeout, true);
4107            retry.stem = format!("{}-confirm", job.stem);
4108            let cache = self.state.config.cache_dir();
4109            let ctx = WaveCtx {
4110                carry_seats: false,
4111                pauses: Some((&self.pause, &self.interrupt)),
4112                run: run_id,
4113                node: "implement",
4114                prompts,
4115                cache: cache.as_deref(),
4116                round: None,
4117            };
4118            let (resumed_seat, resumed) =
4119                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
4120            *seat = resumed_seat;
4121            *out = resumed;
4122        }
4123    }
4124
4125    /// Ask an implement seat again, once per candidate and run, when its
4126    /// turn ended cleanly without starting the work.
4127    ///
4128    /// The shape behind 86f0, 3ce0 and eca7: the model's first response was a
4129    /// final answer ("Implementation incomplete. No files were changed...")
4130    /// after six to twelve seconds, with no tool call and no change. That is
4131    /// a usable exit-0 reply, so none of the other recoveries sees it — it is
4132    /// not a dropped stream, not a failure and names no unconfirmed command —
4133    /// and the candidate was recorded as an ordinary empty one.
4134    ///
4135    /// Decided on evidence, never on the reply's wording (see
4136    /// [`ended_unstarted`]), and never for a reply whose `NO CHANGE NEEDED`
4137    /// claim verifies: that one did answer the task.
4138    ///
4139    /// The seat's own conversation is resumed with [`prompt::resume_unstarted`]
4140    /// when it has one; without a session the whole prompt goes out again.
4141    /// Either way the budget is the full `timeout_implement`, not a nudge's
4142    /// quarter: nothing was done yet, so this is the job itself.
4143    ///
4144    /// Bounded by [`RunState::unstarted_retries`], saved before the agent is
4145    /// asked so a restart cannot grant a second retry. A seat that ends the
4146    /// same way again becomes an ordinary failure with [`UNSTARTED_TWICE`] as
4147    /// its reason, which `resume_seat_handovers` (run next) may hand to the
4148    /// next roster agent like any other failure.
4149    async fn retry_unstarted(
4150        &mut self,
4151        results: &mut [(usize, SeatState, AgentOutcome)],
4152        sent: &[SeatJob],
4153        baselines: &[(char, Option<String>)],
4154        prompts: &Prompts,
4155        run_id: &str,
4156    ) -> Result<()> {
4157        for (wi, seat, out) in results.iter_mut() {
4158            let (Some(job), Some((label, before))) = (sent.get(*wi), baselines.get(*wi)) else {
4159                continue;
4160            };
4161            if !self.unstarted(out, before.as_deref(), &job.cwd).await {
4162                continue;
4163            }
4164            if !self.state.unstarted_retries.insert(*label) {
4165                self.state
4166                    .event("implement", format!("{}: {UNSTARTED_TWICE}", seat.key));
4167                *out = AgentOutcome::Failed(UNSTARTED_TWICE.to_owned());
4168                continue;
4169            }
4170            let resumed = has_context(&job.spec, seat, job.sessions);
4171            self.state.event(
4172                "implement",
4173                format!(
4174                    "{}: the turn ended without starting the work (no tool call, worktree \
4175                     unchanged); {}",
4176                    seat.key,
4177                    if resumed {
4178                        "resuming the conversation once"
4179                    } else {
4180                        "sending the task once more"
4181                    }
4182                ),
4183            );
4184            self.state.save()?;
4185            let mut retry = job.clone();
4186            retry.seat = seat.clone();
4187            if resumed {
4188                retry.prompt = prompt::resume_unstarted();
4189            }
4190            retry.stem = format!("{}-unstarted", job.stem);
4191            let cache = self.state.config.cache_dir();
4192            let ctx = WaveCtx {
4193                carry_seats: false,
4194                pauses: Some((&self.pause, &self.interrupt)),
4195                run: run_id,
4196                node: "implement",
4197                prompts,
4198                cache: cache.as_deref(),
4199                round: None,
4200            };
4201            let (answered_seat, answer) =
4202                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
4203            *seat = answered_seat;
4204            *out = answer;
4205            if matches!(out, AgentOutcome::ResourceBlocked(_)) {
4206                // No agent was spawned, so the retry was not spent.
4207                self.state.unstarted_retries.remove(label);
4208                continue;
4209            }
4210            if self.unstarted(out, before.as_deref(), &job.cwd).await {
4211                self.state
4212                    .event("implement", format!("{}: {UNSTARTED_TWICE}", seat.key));
4213                *out = AgentOutcome::Failed(UNSTARTED_TWICE.to_owned());
4214            }
4215        }
4216        Ok(())
4217    }
4218
4219    /// Whether `out` is a clean reply from a seat that never started the
4220    /// work in `cwd`, and whose reply does not verify as a no-op either.
4221    async fn unstarted(&self, out: &AgentOutcome, before: Option<&str>, cwd: &Path) -> bool {
4222        let AgentOutcome::Ok(o) = out else {
4223            return false;
4224        };
4225        // The CLI's own record first: most replies stop here without git.
4226        if o.tool_calls != Some(0) {
4227            return false;
4228        }
4229        let after = git::rev_parse(cwd, "HEAD").await.ok();
4230        let clean = git::is_clean(cwd).await.ok();
4231        if !ended_unstarted(o, before, after.as_deref(), clean) {
4232            return false;
4233        }
4234        let text = verdict::section(&o.text, "summary").unwrap_or(o.text.clone());
4235        verified_noop_claim_in_worktree(true, &o.commands, &text, cwd, &self.state.base_commit)
4236            .await
4237            != NoopClaimVerdict::Accepted
4238    }
4239
4240    /// Ask the fixer's own seat again, up to [`MAX_FIX_CONTINUATIONS`] times,
4241    /// when its CLI turn ended cleanly (`AgentOutcome::Ok`) but the reply held
4242    /// no [`FixReport`] — see [`MAX_FIX_CONTINUATIONS`]'s own doc for the run
4243    /// that motivated this.
4244    ///
4245    /// Not the same gap as an unparsable *shape*, which [`ask_json_wave`]'s
4246    /// own nudge loop already covers for judge/review/vote seats, and not a
4247    /// dropped stream, which [`Runner::resume_undelivered`] covers for
4248    /// implement seats: here the CLI turn genuinely finished while the node's
4249    /// own work — the fixer's account of what it did — had not. Gated purely
4250    /// on `extract_json::<FixReport>` having failed on an otherwise-usable
4251    /// reply, never on any wording in it, so a fixer whose valid, first-try
4252    /// `FixReport` happens to mention having waited on a background test is
4253    /// never resumed — the `Ok(report)` branch at the call site returns
4254    /// before this is ever invoked.
4255    ///
4256    /// Same discipline as `resume_undelivered`: a nudge-sized timeout per
4257    /// attempt ([`retry_budget`]), nothing attempted once the session is
4258    /// gone, and a quota hit ends the loop immediately rather than retrying a
4259    /// rate limit that fails the same way again.
4260    async fn continue_fix_report(
4261        &mut self,
4262        mut seat: SeatState,
4263        parse_err: String,
4264        job: &SeatJob,
4265        prompts: &Prompts,
4266        run_id: &str,
4267        round: usize,
4268    ) -> (
4269        SeatState,
4270        Option<FixReport>,
4271        Option<String>,
4272        ContinuationRecord,
4273    ) {
4274        let mut last_err = parse_err;
4275        let mut cumulative_wait_ms = 0u64;
4276        let mut attempts = 0usize;
4277        loop {
4278            if !has_context(&job.spec, &seat, job.sessions) {
4279                self.state.event(
4280                    "fix",
4281                    format!(
4282                        "round {round}: fixer's reply had no adoption report ({last_err}); no \
4283                         session left to resume into"
4284                    ),
4285                );
4286                let outcome = if attempts == 0 {
4287                    ContinuationOutcome::NoSession
4288                } else {
4289                    ContinuationOutcome::Exhausted
4290                };
4291                return (
4292                    seat,
4293                    None,
4294                    Some(format!("unparsable fix report: {last_err}")),
4295                    ContinuationRecord {
4296                        attempts,
4297                        cumulative_wait_ms,
4298                        outcome,
4299                    },
4300                );
4301            }
4302            if attempts >= MAX_FIX_CONTINUATIONS {
4303                self.state.event(
4304                    "fix",
4305                    format!(
4306                        "round {round}: fixer's reply still had no adoption report after \
4307                         {attempts} continuation(s) ({last_err}); giving up"
4308                    ),
4309                );
4310                return (
4311                    seat,
4312                    None,
4313                    Some(format!(
4314                        "unparsable fix report after {attempts} continuation(s): {last_err}"
4315                    )),
4316                    ContinuationRecord {
4317                        attempts,
4318                        cumulative_wait_ms,
4319                        outcome: ContinuationOutcome::Exhausted,
4320                    },
4321                );
4322            }
4323            attempts += 1;
4324            self.state.event(
4325                "fix",
4326                format!(
4327                    "round {round}: fixer's reply had no adoption report ({last_err}); resuming \
4328                     the conversation (attempt {attempts}/{MAX_FIX_CONTINUATIONS})"
4329                ),
4330            );
4331            let mut retry = job.clone();
4332            retry.seat = seat.clone();
4333            retry.prompt = prompt::resume_incomplete(&last_err);
4334            retry.timeout = retry_budget(job.timeout, true);
4335            retry.stem = format!("{}-continue{attempts}", job.stem);
4336            let cache = self.state.config.cache_dir();
4337            let ctx = WaveCtx {
4338                carry_seats: false,
4339                pauses: Some((&self.pause, &self.interrupt)),
4340                run: run_id,
4341                node: "fix",
4342                prompts,
4343                cache: cache.as_deref(),
4344                round: Some(round),
4345            };
4346            let (resumed_seat, resumed_out) = run_one(
4347                retry,
4348                Arc::clone(&self.sem),
4349                &ctx,
4350                &mut self.state,
4351                attempts,
4352            )
4353            .await;
4354            seat = resumed_seat;
4355            match resumed_out {
4356                AgentOutcome::Ok(o) => {
4357                    cumulative_wait_ms += o.duration_ms;
4358                    match verdict::extract_json::<FixReport>(&o.text) {
4359                        Ok(report) if !has_unconfirmed_command(&o.commands) => {
4360                            self.state.event(
4361                                "fix",
4362                                format!(
4363                                    "round {round}: fixer's adoption report recovered after \
4364                                     {attempts} continuation(s)"
4365                                ),
4366                            );
4367                            return (
4368                                seat,
4369                                Some(report),
4370                                None,
4371                                ContinuationRecord {
4372                                    attempts,
4373                                    cumulative_wait_ms,
4374                                    outcome: ContinuationOutcome::Resumed,
4375                                },
4376                            );
4377                        }
4378                        // The report parsed, but this same reply's own
4379                        // CommandEvidence — the identical record `state.jobs`
4380                        // renders — names a command whose CLI never
4381                        // confirmed an exit status. Read together, that is
4382                        // not a resolved answer: keep nudging rather than
4383                        // accept a report standing next to a command the
4384                        // seat's own CLI cannot vouch for.
4385                        Ok(_) => {
4386                            last_err = "the reply parsed, but it reported a command whose own CLI \
4387                                 never confirmed an exit status"
4388                                .to_owned();
4389                        }
4390                        Err(e) => last_err = e.to_string(),
4391                    }
4392                }
4393                AgentOutcome::Quota(o) => {
4394                    cumulative_wait_ms += o.duration_ms;
4395                    let loss = QuotaLoss::from_report(seat.key.clone(), "fix", o.quota.as_ref());
4396                    block_machine_outage(&mut self.state, "fix", std::slice::from_ref(&loss));
4397                    self.state.quota.push(loss);
4398                    self.state.event(
4399                        "fix",
4400                        format!(
4401                            "round {round}: continuation rate limited (quota); not retrying now"
4402                        ),
4403                    );
4404                    return (
4405                        seat,
4406                        None,
4407                        Some("rate limited (quota) while recovering the fix report".to_owned()),
4408                        ContinuationRecord {
4409                            attempts,
4410                            cumulative_wait_ms,
4411                            outcome: ContinuationOutcome::QuotaLost,
4412                        },
4413                    );
4414                }
4415                AgentOutcome::Dropped(o) => {
4416                    cumulative_wait_ms += o.duration_ms;
4417                    let why = o
4418                        .dropped
4419                        .as_ref()
4420                        .map(|d| d.why.as_str())
4421                        .unwrap_or("the CLI ended the stream without delivering its answer");
4422                    last_err = format!("the CLI dropped the stream ({why})");
4423                }
4424                AgentOutcome::Failed(e) => last_err = e,
4425                // The continuation was never started; the report stays lost
4426                // and the caller records that, without any handover.
4427                AgentOutcome::ResourceBlocked(e) => {
4428                    return (
4429                        seat,
4430                        None,
4431                        Some(format!("the continuation was not started: {e}")),
4432                        ContinuationRecord {
4433                            attempts: attempts.saturating_sub(1),
4434                            cumulative_wait_ms,
4435                            outcome: ContinuationOutcome::NoSession,
4436                        },
4437                    );
4438                }
4439            }
4440        }
4441    }
4442
4443    fn after_implement(&mut self) -> Result<()> {
4444        if !self.state.candidate_preservation.is_empty() {
4445            bail!("candidate preservation incomplete; judging is unsafe");
4446        }
4447        // Scan every candidate patch once the set is complete.
4448        if self.state.leaks.is_empty() {
4449            let cfg = self.state.config.blind.clone();
4450            let mut leaks = Vec::new();
4451            for c in &self.state.candidates {
4452                let Some(patch) =
4453                    crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
4454                else {
4455                    continue;
4456                };
4457                leaks.extend(blind::scan(
4458                    &format!("candidate {} patch", c.label),
4459                    &patch,
4460                    &cfg.vendor_tokens,
4461                ));
4462            }
4463            if !leaks.is_empty() {
4464                let summary = leaks
4465                    .iter()
4466                    .map(|l| format!("{}×{} in {}", l.token, l.count, l.site))
4467                    .collect::<Vec<_>>()
4468                    .join(", ");
4469                match cfg.on_leak {
4470                    LeakPolicy::Fail => {
4471                        self.state.status = RunStatus::Failed;
4472                        self.state
4473                            .event("blind", format!("vendor text in a patch: {summary}"));
4474                        self.state.leaks = leaks;
4475                        self.state.save()?;
4476                        self.settle_questions();
4477                        bail!(
4478                            "blind.on_leak = \"fail\" and vendor text reached a \
4479                             judged patch: {summary}"
4480                        );
4481                    }
4482                    LeakPolicy::Redact => self.state.event(
4483                        "blind",
4484                        format!("redacting vendor text for judging: {summary}"),
4485                    ),
4486                    LeakPolicy::Warn => self.state.event(
4487                        "blind",
4488                        format!("vendor text present in a judged patch (shown as-is): {summary}"),
4489                    ),
4490                }
4491                self.state.leaks = leaks;
4492            }
4493        }
4494
4495        // Re-verify any saved `verified_noop` claim on active/resumed runs so an
4496        // incomplete or inconsistent saved state cannot bypass the strict contract.
4497        let mut invalidated = Vec::new();
4498        for c in &mut self.state.candidates {
4499            if c.verified_noop.is_some() && !c.has_valid_verified_noop() {
4500                c.verified_noop = None;
4501                if c.empty && c.failed.is_none() {
4502                    c.failed = Some(
4503                        "no-op claim rejected: saved candidate does not satisfy structured verification requirements"
4504                            .to_owned(),
4505                    );
4506                }
4507                invalidated.push(c.label);
4508            }
4509        }
4510        for label in invalidated {
4511            self.state.event(
4512                "implement",
4513                format!("candidate {label}: invalidated inconsistent saved NO CHANGE NEEDED claim"),
4514            );
4515        }
4516
4517        if self.state.viable().is_empty() {
4518            if self.state.all_candidates_verified_noop() {
4519                // Every candidate agreed, with evidence the adoption guard
4520                // accepted, that nothing belongs in this worktree. That is
4521                // not the same fact as a candidate that simply failed to
4522                // write anything, and settling it as an ordinary `Failed`
4523                // (see `SCHEMA`'s doc for schema 10) is what let two of
4524                // task 391f's attempts burn a retry each re-discovering the
4525                // same already-landed fix. Terminal either way, so `judge`
4526                // must never run over an empty candidate set — unlike the
4527                // `Failed` branch below this returns `Ok`, not an error:
4528                // nothing here failed.
4529                self.state.status = RunStatus::VerifiedNoop;
4530                self.state.save()?;
4531                self.settle_questions();
4532                return Ok(());
4533            }
4534            self.state.status = RunStatus::Failed;
4535            self.state.save()?;
4536            self.settle_questions();
4537            bail!("no candidate produced a change; nothing to judge");
4538        }
4539        self.state.status = RunStatus::Judging;
4540        self.state.save()?;
4541        Ok(())
4542    }
4543
4544    // --------------------------------------------------------------- judge
4545
4546    async fn judge(&mut self) -> Result<()> {
4547        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4548        // agent files with `magi task add` name the run that paid for it. The
4549        // prompt overlay is cloned alongside it because the waves borrow it
4550        // while `self` is mutably borrowed by the node's own bookkeeping.
4551        let run_id = self.state.id.clone();
4552        let prompts = self.state.config.prompts.clone();
4553        if !self.state.judgements.is_empty() || self.state.judge_skipped {
4554            return Ok(());
4555        }
4556        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4557        if viable.len() == 1 {
4558            // Recorded so this is a one-time event: `judgements` stays empty
4559            // either way, which without this flag is indistinguishable from
4560            // "not yet judged" on the next reentry — and status is left
4561            // untouched, so a later node's conclusion (e.g. `Blocked` after
4562            // the review budget ran out) survives a resume instead of being
4563            // clobbered back to `Judging` by this node running again.
4564            self.state.judge_skipped = true;
4565            self.state.event(
4566                "judge",
4567                format!(
4568                    "only candidate {} produced a change; judging skipped",
4569                    viable[0].label
4570                ),
4571            );
4572            self.state.save()?;
4573            return Ok(());
4574        }
4575        self.state.status = RunStatus::Judging;
4576
4577        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
4578        let language = self.state.config.graph.language.clone();
4579        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4580        let sessions = self.state.config.graph.sessions;
4581        let artifacts = agent::artifacts_dir(&self.state.dir());
4582        let root = self.state.worktree_root();
4583        let base_short = short(&self.state.base_commit);
4584
4585        let mut jobs = Vec::new();
4586        let mut orders = Vec::new();
4587        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4588            let order = blind::presentation_order(viable.len(), j, self.state.seed);
4589            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
4590            orders.push(order.iter().map(|&k| viable[k].index).collect::<Vec<_>>());
4591            let seat_key = format!("judge-{}", j + 1);
4592            let seat = self.seat(&seat_key, &spec.id);
4593            jobs.push(SeatJob {
4594                prompt: prompt::judge(
4595                    &self.state.instruction,
4596                    &views,
4597                    self.roles.judges.len(),
4598                    &base_short,
4599                    &language,
4600                ),
4601                spec,
4602                seat,
4603                cwd: root.join(format!("judge-{}", j + 1)),
4604                timeout,
4605                allow_write: false,
4606                sessions,
4607                artifacts: artifacts.clone(),
4608                stem: format!("judge-{}", j + 1),
4609                handover: None,
4610            });
4611        }
4612
4613        self.state.event(
4614            "judge",
4615            format!(
4616                "{} judges ranking {} candidates blind",
4617                jobs.len(),
4618                viable.len()
4619            ),
4620        );
4621        let labels_for_check = labels.clone();
4622        let mut quota_losses = Vec::new();
4623        let cache = self.state.config.cache_dir();
4624        let ctx = WaveCtx {
4625            carry_seats: false,
4626            pauses: Some((&self.pause, &self.interrupt)),
4627            run: &run_id,
4628            node: "judge",
4629            prompts: &prompts,
4630            cache: cache.as_deref(),
4631            round: None,
4632        };
4633        let results = ask_json_wave::<Ranking>(
4634            jobs,
4635            Arc::clone(&self.sem),
4636            self.state.config.graph.retries,
4637            &self.roles.judge_roster,
4638            &ctx,
4639            &mut quota_losses,
4640            &mut self.state,
4641            &move |r: &Ranking| r.validate(&labels_for_check),
4642        )
4643        .await;
4644        if self.state.resource_block.is_some() {
4645            return self.stop_for_resource();
4646        }
4647        self.state.quota.extend(quota_losses);
4648
4649        for (j, (seat, res, _attempts)) in results.into_iter().enumerate() {
4650            let agent_id = seat.agent.clone();
4651            self.state.seats.insert(seat.key.clone(), seat);
4652            let mut record = Judgement {
4653                judge: j + 1,
4654                seat: format!("judge-{}", j + 1),
4655                agent: agent_id,
4656                ranking: Vec::new(),
4657                reasons: BTreeMap::new(),
4658                confidence: None,
4659                strengths: BTreeMap::new(),
4660                order: orders[j].clone(),
4661                failed: None,
4662                duration_ms: 0,
4663            };
4664            match res {
4665                Ok((ranking, out)) => {
4666                    record.ranking = ranking.normalized();
4667                    record.reasons = ranking.reasons;
4668                    record.strengths = ranking.strengths;
4669                    record.confidence = ranking.confidence;
4670                    record.duration_ms = out.duration_ms;
4671                    self.state.event(
4672                        "judge",
4673                        format!(
4674                            "judge {} ranked {}",
4675                            j + 1,
4676                            record.ranking.iter().collect::<String>()
4677                        ),
4678                    );
4679                }
4680                Err(e) => {
4681                    record.failed = Some(e.to_string());
4682                    self.state
4683                        .event("judge", format!("judge {} produced no ranking: {e}", j + 1));
4684                }
4685            }
4686            self.state.judgements.push(record);
4687            self.state.save()?;
4688        }
4689        Ok(())
4690    }
4691
4692    // ---------------------------------------------------------- deliberate
4693
4694    async fn deliberate(&mut self) -> Result<()> {
4695        if self.hold_base_sync().await? {
4696            return Ok(());
4697        }
4698        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4699        // agent files with `magi task add` name the run that paid for it. The
4700        // prompt overlay is cloned alongside it because the waves borrow it
4701        // while `self` is mutably borrowed by the node's own bookkeeping.
4702        let run_id = self.state.id.clone();
4703        let prompts = self.state.config.prompts.clone();
4704        let rounds = self.state.config.graph.deliberate_rounds;
4705        // Resume unfinished rounds after an outage, but never reopen a tally.
4706        if self.state.deliberation.len() >= rounds || self.state.tally.is_some() {
4707            return Ok(());
4708        }
4709        let tops: Vec<char> = self
4710            .state
4711            .judgements
4712            .iter()
4713            .filter_map(|j| j.ranking.first().copied())
4714            .collect();
4715        if tops.len() < 2 || tops.iter().all(|t| *t == tops[0]) || rounds == 0 {
4716            if tops.len() >= 2 && tops.iter().all(|t| *t == tops[0]) {
4717                self.state.event(
4718                    "deliberate",
4719                    format!("judges agreed on {} outright; no deliberation", tops[0]),
4720                );
4721            }
4722            self.state.status = RunStatus::Voting;
4723            self.state.save()?;
4724            return Ok(());
4725        }
4726
4727        self.state.status = RunStatus::Deliberating;
4728        self.state.event(
4729            "deliberate",
4730            format!(
4731                "split: first choices were {} — opening {rounds} round(s)",
4732                tops.iter().collect::<String>()
4733            ),
4734        );
4735
4736        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4737        let language = self.state.config.graph.language.clone();
4738        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4739        let sessions = self.state.config.graph.sessions;
4740        let artifacts = agent::artifacts_dir(&self.state.dir());
4741        let root = self.state.worktree_root();
4742        let base_short = short(&self.state.base_commit);
4743
4744        // Judges argue in sequence so that a turn can answer the one before it;
4745        // that is the difference between deliberation and three parallel
4746        // monologues.
4747        for round in self.state.deliberation.len() + 1..=rounds {
4748            let mut turns: Vec<DeliberationTurn> = Vec::new();
4749            let mut round_losses = Vec::new();
4750            let mut asked = 0;
4751            for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4752                if self.state.judgements[j].failed.is_some() {
4753                    continue;
4754                }
4755                let seat_key = format!("judge-{}", j + 1);
4756                let spec = self.occupant(&seat_key, spec);
4757                let mut seat = self.seat(&seat_key, &spec.id);
4758                let transcript = self.transcript(&turns, j);
4759                let build = |context: Option<&str>| {
4760                    prompt::deliberate(
4761                        &self.state.instruction,
4762                        context,
4763                        &transcript,
4764                        round,
4765                        rounds,
4766                        &language,
4767                    )
4768                };
4769                let block = self.candidate_block(&viable, &base_short);
4770                let full = build(Some(&block));
4771                let text = if has_context(&spec, &seat, sessions) {
4772                    build(None)
4773                } else {
4774                    full.clone()
4775                };
4776                let job = SeatJob {
4777                    spec,
4778                    seat: seat.clone(),
4779                    prompt: text,
4780                    cwd: root.join(format!("judge-{}", j + 1)),
4781                    timeout,
4782                    allow_write: false,
4783                    sessions,
4784                    artifacts: artifacts.clone(),
4785                    stem: format!("delib-{round}-judge-{}", j + 1),
4786                    handover: Some(full),
4787                };
4788                let cache = self.state.config.cache_dir();
4789                let ctx = WaveCtx {
4790                    carry_seats: false,
4791                    pauses: Some((&self.pause, &self.interrupt)),
4792                    run: &run_id,
4793                    node: "deliberate",
4794                    prompts: &prompts,
4795                    cache: cache.as_deref(),
4796                    round: None,
4797                };
4798                // A turn is never nudged (`retries` 0): a failed seat is
4799                // handed to the next roster agent, which gets the full
4800                // context. An empty answer is a turn, not a failure.
4801                let mut losses = Vec::new();
4802                asked += 1;
4803                let mut results = ask_wave_with::<String>(
4804                    vec![job],
4805                    Arc::clone(&self.sem),
4806                    0,
4807                    &self.roles.judge_roster,
4808                    &ctx,
4809                    &mut losses,
4810                    &mut self.state,
4811                    &|text: &str| {
4812                        Ok(verdict::section(text, "position").unwrap_or_else(|| text.to_owned()))
4813                    },
4814                )
4815                .await;
4816                if self.state.resource_block.is_some() {
4817                    return self.stop_for_resource();
4818                }
4819                round_losses.extend(losses.iter().cloned());
4820                self.state.quota.extend(losses);
4821                let (updated, res, _) = results.pop().expect("one job in, one result out");
4822                seat = updated;
4823                let agent_id = seat.agent.clone();
4824                self.state.seats.insert(seat.key.clone(), seat);
4825                let body = match res {
4826                    Ok((body, _)) => body,
4827                    // Skip the seat; a CLI's raw error JSON is never read as
4828                    // this judge's position.
4829                    Err(e) => {
4830                        self.state
4831                            .event("deliberate", format!("judge {} skipped: {e}", j + 1));
4832                        continue;
4833                    }
4834                };
4835                let tentative = verdict::extract_json::<Position>(&body)
4836                    .ok()
4837                    .and_then(|p| p.tentative)
4838                    .and_then(|s| s.trim().chars().next())
4839                    .map(|c| c.to_ascii_uppercase());
4840                self.state.event(
4841                    "deliberate",
4842                    format!(
4843                        "round {round}: judge {} now favours {}",
4844                        j + 1,
4845                        tentative.map_or("—".to_owned(), |c| c.to_string())
4846                    ),
4847                );
4848                turns.push(DeliberationTurn {
4849                    judge: j + 1,
4850                    agent: agent_id,
4851                    body: blind::sanitize_prose(&body, &self.state.config.blind),
4852                    tentative,
4853                });
4854            }
4855            if asked > 0 && turns.is_empty() && round_losses.len() == asked {
4856                block_machine_outage(&mut self.state, "deliberate", &round_losses);
4857                return self.stop_for_resource();
4858            }
4859            self.state
4860                .deliberation
4861                .push(DeliberationRound { round, turns });
4862            self.state.save()?;
4863        }
4864
4865        self.state.status = RunStatus::Voting;
4866        self.state.save()?;
4867        Ok(())
4868    }
4869
4870    // ---------------------------------------------------------------- vote
4871
4872    async fn vote(&mut self) -> Result<()> {
4873        if self.hold_base_sync().await? {
4874            return Ok(());
4875        }
4876        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4877        // agent files with `magi task add` name the run that paid for it. The
4878        // prompt overlay is cloned alongside it because the waves borrow it
4879        // while `self` is mutably borrowed by the node's own bookkeeping.
4880        let run_id = self.state.id.clone();
4881        let prompts = self.state.config.prompts.clone();
4882        if !self.state.votes.is_empty() || self.state.tally.is_some() {
4883            return Ok(());
4884        }
4885        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
4886        if viable.len() == 1 {
4887            return Ok(());
4888        }
4889        self.state.status = RunStatus::Voting;
4890
4891        let language = self.state.config.graph.language.clone();
4892        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4893        let sessions = self.state.config.graph.sessions;
4894        let artifacts = agent::artifacts_dir(&self.state.dir());
4895        let root = self.state.worktree_root();
4896        let base_short = short(&self.state.base_commit);
4897        let candidates: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4898
4899        let mut jobs = Vec::new();
4900        let mut seats_at = Vec::new();
4901        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4902            if self
4903                .state
4904                .judgements
4905                .get(j)
4906                .is_some_and(|r| r.failed.is_some())
4907            {
4908                continue;
4909            }
4910            let seat_key = format!("judge-{}", j + 1);
4911            let spec = self.occupant(&seat_key, spec);
4912            let seat = self.seat(&seat_key, &spec.id);
4913            let full = self.vote_prompt_full(j, &viable, &language, &candidates, &base_short);
4914            let text = if has_context(&spec, &seat, sessions) {
4915                prompt::final_vote(&viable, &language)
4916            } else {
4917                full.clone()
4918            };
4919            jobs.push(SeatJob {
4920                spec,
4921                seat,
4922                prompt: text,
4923                cwd: root.join(format!("judge-{}", j + 1)),
4924                timeout,
4925                allow_write: false,
4926                sessions,
4927                artifacts: artifacts.clone(),
4928                stem: format!("vote-judge-{}", j + 1),
4929                handover: Some(full),
4930            });
4931            seats_at.push(j);
4932        }
4933
4934        self.state.event(
4935            "vote",
4936            format!(
4937                "collecting {} final votes one by one, privately",
4938                jobs.len()
4939            ),
4940        );
4941        let allowed = viable.clone();
4942        let mut quota_losses = Vec::new();
4943        let cache = self.state.config.cache_dir();
4944        let ctx = WaveCtx {
4945            carry_seats: false,
4946            pauses: Some((&self.pause, &self.interrupt)),
4947            run: &run_id,
4948            node: "vote",
4949            prompts: &prompts,
4950            cache: cache.as_deref(),
4951            round: None,
4952        };
4953        let results = ask_json_wave::<FinalVote>(
4954            jobs,
4955            Arc::clone(&self.sem),
4956            self.state.config.graph.retries,
4957            &self.roles.judge_roster,
4958            &ctx,
4959            &mut quota_losses,
4960            &mut self.state,
4961            &move |v: &FinalVote| match v.label() {
4962                Some(c) if allowed.contains(&c) => Ok(()),
4963                other => bail!("vote {other:?} is not one of {allowed:?}"),
4964            },
4965        )
4966        .await;
4967        if self.state.resource_block.is_some() {
4968            return self.stop_for_resource();
4969        }
4970        self.state.quota.extend(quota_losses);
4971
4972        for (&j, (seat, res, _attempts)) in seats_at.iter().zip(results) {
4973            let agent_id = seat.agent.clone();
4974            self.state.seats.insert(seat.key.clone(), seat);
4975            let initial = self
4976                .state
4977                .judgements
4978                .get(j)
4979                .and_then(|r| r.ranking.first().copied());
4980            let mut record = VoteRecord {
4981                judge: j + 1,
4982                agent: agent_id,
4983                vote: None,
4984                reason: String::new(),
4985                changed: false,
4986            };
4987            match res {
4988                Ok((v, _)) => {
4989                    record.vote = v.label();
4990                    record.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
4991                    record.changed = matches!((record.vote, initial), (Some(a), Some(b)) if a != b);
4992                    self.state.event(
4993                        "vote",
4994                        format!(
4995                            "judge {} voted {}{}",
4996                            j + 1,
4997                            record.vote.unwrap_or('?'),
4998                            if record.changed { " (changed)" } else { "" }
4999                        ),
5000                    );
5001                }
5002                Err(e) => {
5003                    self.state
5004                        .event("vote", format!("judge {} cast no vote: {e}", j + 1));
5005                }
5006            }
5007            self.state.votes.push(record);
5008            self.state.save()?;
5009        }
5010        Ok(())
5011    }
5012
5013    // --------------------------------------------------------------- tally
5014
5015    fn tally(&mut self) -> Result<()> {
5016        if self.state.tally.is_some() {
5017            return Ok(());
5018        }
5019        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
5020        let tops: Vec<char> = self
5021            .state
5022            .judgements
5023            .iter()
5024            .filter_map(|j| j.ranking.first().copied())
5025            .collect();
5026        let unanimous_initial = tops.len() > 1 && tops.iter().all(|t| *t == tops[0]);
5027
5028        // A judge whose private vote failed still counted once, in the initial
5029        // ranking; using it beats discarding a whole seat.
5030        let mut first_choice: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
5031        let mut cast: Vec<char> = Vec::new();
5032        for (i, j) in self.state.judgements.iter().enumerate() {
5033            let vote = self
5034                .state
5035                .votes
5036                .iter()
5037                .find(|v| v.judge == i + 1)
5038                .and_then(|v| v.vote)
5039                .or_else(|| j.ranking.first().copied());
5040            if let Some(v) = vote {
5041                *first_choice.entry(v).or_insert(0) += 1;
5042                cast.push(v);
5043            }
5044        }
5045
5046        let mut borda: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
5047        for j in &self.state.judgements {
5048            let n = j.ranking.len();
5049            for (pos, label) in j.ranking.iter().enumerate() {
5050                *borda.entry(*label).or_insert(0) += n.saturating_sub(pos + 1);
5051            }
5052        }
5053
5054        let best = first_choice.values().copied().max().unwrap_or(0);
5055        let mut leaders: Vec<char> = first_choice
5056            .iter()
5057            .filter(|(_, v)| **v == best)
5058            .map(|(k, _)| *k)
5059            .collect();
5060        let mut tie_break = None;
5061        if leaders.len() > 1 {
5062            let top_borda = leaders.iter().map(|l| borda[l]).max().unwrap_or(0);
5063            let borda_leaders: Vec<char> = leaders
5064                .iter()
5065                .copied()
5066                .filter(|l| borda[l] == top_borda)
5067                .collect();
5068            tie_break = Some(if borda_leaders.len() == 1 {
5069                format!(
5070                    "{} way tie on first-choice votes, broken by Borda points from the initial rankings",
5071                    leaders.len()
5072                )
5073            } else {
5074                format!(
5075                    "{} way tie on both first-choice votes and Borda points, broken by label order",
5076                    leaders.len()
5077                )
5078            });
5079            leaders = borda_leaders;
5080            leaders.sort_unstable();
5081        }
5082        let winner = *leaders
5083            .first()
5084            .or(viable.first())
5085            .context("no candidate to declare a winner from")?;
5086
5087        let changed_votes = self.state.votes.iter().filter(|v| v.changed).count();
5088        let unanimous_final = !cast.is_empty() && cast.iter().all(|c| *c == cast[0]);
5089        let deliberated = !self.state.deliberation.is_empty();
5090
5091        // Whose verdict is this? A rate-limited seat is absent even if it
5092        // ranked before the limit hit, so presence is measured against the
5093        // recorded losses, not just "did a ranking ever appear".
5094        let quota_seats: std::collections::BTreeSet<&str> =
5095            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
5096        let mut present = 0usize;
5097        for (i, j) in self.state.judgements.iter().enumerate() {
5098            if quota_seats.contains(j.seat.as_str()) {
5099                continue;
5100            }
5101            let ranked = !j.ranking.is_empty() && j.failed.is_none();
5102            let voted = self
5103                .state
5104                .votes
5105                .iter()
5106                .any(|v| v.judge == i + 1 && v.vote.is_some());
5107            if ranked || voted {
5108                present += 1;
5109            }
5110        }
5111        // Strict majority of the configured panel. A bare majority is real
5112        // signal we can act on, while a minority verdict must never stand in
5113        // for a healthy one. A one-candidate run needs no panel at all, and
5114        // `judges` stays `0` rather than the roster size a panel that never
5115        // sat would otherwise be credited with.
5116        let needs_quorum = viable.len() > 1;
5117        let judges_total = if needs_quorum {
5118            self.roles.judges.len()
5119        } else {
5120            0
5121        };
5122        let quorum = if needs_quorum {
5123            judges_total / 2 + 1
5124        } else {
5125            0
5126        };
5127        let met_quorum = !needs_quorum || present >= quorum;
5128        let uncontested = (!needs_quorum).then(|| {
5129            format!("only one candidate ({winner}) produced a usable change; no panel was asked")
5130        });
5131
5132        self.state.event(
5133            "tally",
5134            match &uncontested {
5135                Some(reason) => format!("winner {winner} — {reason}"),
5136                None => format!(
5137                    "winner {winner} — votes {} | initial {} | {} changed | \
5138                     {present}/{judges_total} judges{}",
5139                    first_choice
5140                        .iter()
5141                        .map(|(k, v)| format!("{k}:{v}"))
5142                        .collect::<Vec<_>>()
5143                        .join(" "),
5144                    if unanimous_initial {
5145                        "unanimous"
5146                    } else {
5147                        "split"
5148                    },
5149                    changed_votes,
5150                    if met_quorum {
5151                        String::new()
5152                    } else {
5153                        format!(" — below quorum ({quorum} required)")
5154                    },
5155                ),
5156            },
5157        );
5158        if !met_quorum {
5159            self.state.event(
5160                "stall",
5161                format!(
5162                    "verdict rests on {present} of {judges_total} judges (quorum {quorum}); \
5163                     the run stops here, resumable"
5164                ),
5165            );
5166        }
5167        self.state.tally = Some(Tally {
5168            first_choice,
5169            borda,
5170            winner,
5171            rankings: tops.len(),
5172            unanimous_initial,
5173            deliberated,
5174            changed_votes,
5175            unanimous_final,
5176            tie_break,
5177            judges: judges_total,
5178            present,
5179            quorum,
5180            met_quorum,
5181            uncontested,
5182        });
5183        self.state.status = if met_quorum {
5184            RunStatus::Reviewing
5185        } else {
5186            RunStatus::Stalled
5187        };
5188        self.state.save()?;
5189        Ok(())
5190    }
5191
5192    // ------------------------------------------------------------- recover
5193
5194    /// Re-ask the judge seats `tally` counts as absent, so a `Stalled` run can be
5195    /// resumed toward completion once the transient cause clears.
5196    ///
5197    /// A seat is absent — and therefore re-asked — when `tally` refuses to count
5198    /// it toward the quorum, which is exactly the set of seats whose absence
5199    /// collapsed the panel: struck by a rate limit at *any* node (the quorum must
5200    /// not depend on which node happened to hit the limit), or an ordinary
5201    /// failure (`failed = Some`) that never produced a usable ranking. A healthy
5202    /// seat is never disturbed.
5203    ///
5204    /// A seat that now answers with a usable ranking is "recovered": its
5205    /// `Judgement` is refreshed, its `QuotaLoss`/`failed` state cleared (so
5206    /// `tally` counts it present again), and its vote re-collected. A seat that
5207    /// still fails keeps its loss and stays absent.
5208    ///
5209    /// Returns `true` when the re-tally restores the quorum (the run may proceed
5210    /// to review/gate/merge), `false` when it is still below quorum (the run
5211    /// stays `Stalled`, still resumable for a later retry).
5212    #[allow(clippy::too_many_lines)]
5213    async fn recover_stall(&mut self) -> Result<bool> {
5214        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
5215        // agent files with `magi task add` name the run that paid for it. The
5216        // prompt overlay is cloned alongside it because the waves borrow it
5217        // while `self` is mutably borrowed by the node's own bookkeeping.
5218        let run_id = self.state.id.clone();
5219        let prompts = self.state.config.prompts.clone();
5220        // Absent seats = quota-lost at any node, or failed outright. Mirroring
5221        // `tally`'s presence test (rather than the old quota-judge/vote filter)
5222        // is what keeps a non-quota collapse — or a quota loss recorded at the
5223        // deliberate node — from being a permanent dead-end on `--resume`.
5224        let quota_seats: BTreeSet<&str> =
5225            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
5226        let absent: Vec<String> = self
5227            .state
5228            .judgements
5229            .iter()
5230            .filter(|j| quota_seats.contains(j.seat.as_str()) || j.failed.is_some())
5231            .map(|j| j.seat.clone())
5232            .collect();
5233        if absent.is_empty() {
5234            return Ok(false);
5235        }
5236        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
5237        if viable.len() <= 1 {
5238            return Ok(false);
5239        }
5240        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
5241        let language = self.state.config.graph.language.clone();
5242        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
5243        let sessions = self.state.config.graph.sessions;
5244        let artifacts = agent::artifacts_dir(&self.state.dir());
5245        let root = self.state.worktree_root();
5246        let base_short = short(&self.state.base_commit);
5247        let candidates: Vec<Candidate> = viable.clone();
5248
5249        // Map each absent seat key to its 0-based position in `roles.judges`.
5250        let mut positions: Vec<usize> = absent
5251            .iter()
5252            .filter_map(|k| self.state.judgements.iter().position(|r| &r.seat == k))
5253            .collect();
5254        if positions.is_empty() {
5255            return Ok(false);
5256        }
5257        positions.sort_unstable();
5258        positions.dedup();
5259
5260        // Re-rank the lost seats, one blind prompt each.
5261        let mut judge_jobs = Vec::new();
5262        for &j in &positions {
5263            let order = blind::presentation_order(viable.len(), j, self.state.seed);
5264            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
5265            let seat_key = format!("judge-{}", j + 1);
5266            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
5267            let seat = self.seat(&seat_key, &spec.id);
5268            judge_jobs.push(SeatJob {
5269                spec,
5270                seat,
5271                prompt: prompt::judge(
5272                    &self.state.instruction,
5273                    &views,
5274                    self.roles.judges.len(),
5275                    &base_short,
5276                    &language,
5277                ),
5278                cwd: root.join(seat_key),
5279                timeout,
5280                allow_write: false,
5281                sessions,
5282                artifacts: artifacts.clone(),
5283                stem: format!("judge-{}-recover", j + 1),
5284                handover: None,
5285            });
5286        }
5287
5288        let labels_for_check = labels.clone();
5289        let mut judge_losses = Vec::new();
5290        let retries = self.state.config.graph.retries;
5291        let cache = self.state.config.cache_dir();
5292        let ctx = WaveCtx {
5293            carry_seats: false,
5294            pauses: Some((&self.pause, &self.interrupt)),
5295            run: &run_id,
5296            node: "judge",
5297            prompts: &prompts,
5298            cache: cache.as_deref(),
5299            round: None,
5300        };
5301        let results = ask_json_wave::<Ranking>(
5302            judge_jobs,
5303            Arc::clone(&self.sem),
5304            retries,
5305            &self.roles.judge_roster,
5306            &ctx,
5307            &mut judge_losses,
5308            &mut self.state,
5309            &move |r: &Ranking| r.validate(&labels_for_check),
5310        )
5311        .await;
5312        if self.state.resource_block.is_some() {
5313            self.stop_for_resource()?;
5314            return Ok(false);
5315        }
5316
5317        // Refresh the judgement of every seat that ranked again.
5318        let mut recovered: BTreeSet<usize> = BTreeSet::new();
5319        for (&j, (seat, res, _attempts)) in positions.iter().zip(results) {
5320            let agent_id = seat.agent.clone();
5321            self.state.seats.insert(seat.key.clone(), seat);
5322            let record = &mut self.state.judgements[j];
5323            match res {
5324                Ok((ranking, out)) => {
5325                    record.agent = agent_id;
5326                    record.ranking = ranking.normalized();
5327                    record.reasons = ranking.reasons;
5328                    record.strengths = ranking.strengths;
5329                    record.confidence = ranking.confidence;
5330                    record.failed = None;
5331                    record.duration_ms = out.duration_ms;
5332                    recovered.insert(j);
5333                    self.state.event(
5334                        "recover",
5335                        format!("judge {} ranked again after the limit", j + 1),
5336                    );
5337                }
5338                Err(e) => {
5339                    self.state
5340                        .event("recover", format!("judge {} still cannot rank: {e}", j + 1));
5341                }
5342            }
5343        }
5344
5345        // Re-ask the votes of the seats that recovered a ranking.
5346        let mut vote_jobs = Vec::new();
5347        let mut vote_pos: Vec<usize> = Vec::new();
5348        for &j in &recovered {
5349            let seat_key = format!("judge-{}", j + 1);
5350            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
5351            let seat = self.seat(&seat_key, &spec.id);
5352            let full = self.vote_prompt_full(j, &labels, &language, &candidates, &base_short);
5353            let text = if has_context(&spec, &seat, sessions) {
5354                prompt::final_vote(&labels, &language)
5355            } else {
5356                full.clone()
5357            };
5358            vote_jobs.push(SeatJob {
5359                spec,
5360                seat,
5361                prompt: text,
5362                cwd: root.join(seat_key),
5363                timeout,
5364                allow_write: false,
5365                sessions,
5366                artifacts: artifacts.clone(),
5367                stem: format!("vote-judge-{}-recover", j + 1),
5368                handover: Some(full),
5369            });
5370            vote_pos.push(j);
5371        }
5372        let allowed = labels.clone();
5373        let mut vote_losses = Vec::new();
5374        let vote_retries = self.state.config.graph.retries;
5375        let vote_cache = self.state.config.cache_dir();
5376        let ctx = WaveCtx {
5377            carry_seats: false,
5378            pauses: Some((&self.pause, &self.interrupt)),
5379            run: &run_id,
5380            node: "vote",
5381            prompts: &prompts,
5382            cache: vote_cache.as_deref(),
5383            round: None,
5384        };
5385        let votes = ask_json_wave::<FinalVote>(
5386            vote_jobs,
5387            Arc::clone(&self.sem),
5388            vote_retries,
5389            &self.roles.judge_roster,
5390            &ctx,
5391            &mut vote_losses,
5392            &mut self.state,
5393            &move |v: &FinalVote| match v.label() {
5394                Some(c) if allowed.contains(&c) => Ok(()),
5395                other => bail!("vote {other:?} is not one of {allowed:?}"),
5396            },
5397        )
5398        .await;
5399        if self.state.resource_block.is_some() {
5400            self.stop_for_resource()?;
5401            return Ok(false);
5402        }
5403        for (&j, (seat, res, _attempts)) in vote_pos.iter().zip(votes) {
5404            let agent_id = seat.agent.clone();
5405            self.state.seats.insert(seat.key.clone(), seat);
5406            match res {
5407                Ok((v, _)) => {
5408                    if let Some(rec) = self.state.votes.iter_mut().find(|r| r.judge == j + 1) {
5409                        rec.vote = v.label();
5410                        rec.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
5411                    } else {
5412                        self.state.votes.push(VoteRecord {
5413                            judge: j + 1,
5414                            agent: agent_id,
5415                            vote: v.label(),
5416                            reason: blind::sanitize_prose(&v.reason, &self.state.config.blind),
5417                            changed: false,
5418                        });
5419                    }
5420                    self.state.event(
5421                        "recover",
5422                        format!("judge {} voted again after the limit", j + 1),
5423                    );
5424                }
5425                Err(e) => {
5426                    self.state
5427                        .event("recover", format!("judge {} still cannot vote: {e}", j + 1));
5428                }
5429            }
5430        }
5431
5432        // A seat that ranked again is present even if its re-vote failed —
5433        // `tally` falls back to the initial ranking's first choice — so clear
5434        // its quota loss. Seats that still fail keep theirs and stay absent.
5435        let recovered_keys: BTreeSet<String> = recovered
5436            .iter()
5437            .map(|&j| format!("judge-{}", j + 1))
5438            .collect();
5439        self.state
5440            .quota
5441            .retain(|q| !recovered_keys.contains(&q.seat));
5442        // A seat that hit the limit again is a fresh loss, not the old one:
5443        // replace the stale entry so the history stays one-per-seat and the
5444        // daemon can tell this attempt's loss from a previous session's.
5445        for loss in judge_losses.into_iter().chain(vote_losses) {
5446            if recovered_keys.contains(&loss.seat) {
5447                continue;
5448            }
5449            self.state.quota.retain(|q| q.seat != loss.seat);
5450            self.state.quota.push(loss);
5451        }
5452
5453        // Recompute the verdict from the refreshed panel.
5454        self.state.tally = None;
5455        self.tally()?;
5456        Ok(self
5457            .state
5458            .tally
5459            .as_ref()
5460            .map(|t| t.met_quorum)
5461            .unwrap_or(false))
5462    }
5463
5464    // ---------------------------------------------------------------- graft
5465
5466    /// Port the strengths the judges attributed to the losing candidates onto
5467    /// the winner, once, between the tally and the review loop.
5468    ///
5469    /// Best-effort by construction: it returns nothing and fails nothing. A
5470    /// skip, a fixer that failed or hit quota, or a round that changed nothing
5471    /// all leave the winner at its previous commit (`GraftRecord::pre`), and
5472    /// the run carries on as if the phase were off. See [`graft`] for the
5473    /// decisions and `AGENTS.md` for the invariants.
5474    ///
5475    /// The one exception is a rollback that could not be confirmed: the
5476    /// rejected commit may still be the winner's tip, so the run is blocked
5477    /// (resumable; the record stays `Running`, which makes a resume retry the
5478    /// restore) instead of reviewing, gating and merging it.
5479    async fn graft(&mut self) -> Result<()> {
5480        let Err(e) = self.graft_inner().await else {
5481            return Ok(());
5482        };
5483        if e.is::<crate::repo_lock::ResourceBlocked>() {
5484            return Err(e);
5485        }
5486        if e.downcast_ref::<GraftRestoreFailed>().is_some() {
5487            self.state.status = RunStatus::Blocked;
5488            self.state.event("graft", format!("blocked: {e:#}"));
5489            self.state.save()?;
5490            return Err(e);
5491        }
5492        // An error after the `Running` record was saved may have left the
5493        // fixer's work in the tree: the record must not stay unsettled
5494        // (a later resume would reset past the review fixes), so confirm the
5495        // restore now, or block.
5496        if let Some(rec) = self.state.graft.clone()
5497            && !rec.outcome.settled()
5498        {
5499            if let Some(winner) = self.state.winner().cloned() {
5500                if let Err(re) = self.graft_restore(&winner.worktree, &rec.pre).await {
5501                    if re.is::<crate::repo_lock::ResourceBlocked>() {
5502                        return Err(re);
5503                    }
5504                    self.state.status = RunStatus::Blocked;
5505                    self.state.event("graft", format!("blocked: {re:#}"));
5506                    self.state.save()?;
5507                    return Err(re);
5508                }
5509            }
5510            if let Some(g) = self.state.graft.as_mut() {
5511                g.outcome = GraftOutcome::RolledBack(format!("{e:#}"));
5512            }
5513        }
5514        self.state.event("graft", format!("skipped: {e:#}"));
5515        if let Err(e) = self.state.save() {
5516            tracing::warn!("save after graft: {e:#}");
5517        }
5518        Ok(())
5519    }
5520
5521    /// Put the winner back on `pre` and confirm it: a failed `reset` (a stale
5522    /// `index.lock`, say) or a tip that is not `pre` afterwards is an error.
5523    async fn graft_restore(&mut self, wt: &Path, pre: &str) -> Result<()> {
5524        let _coordination = self.coordinate(wt).await?;
5525        crate::recovery::restore_repair(wt, pre)
5526            .await
5527            .map_err(|e| GraftRestoreFailed(format!("{e:#}")).into())
5528    }
5529
5530    /// A skip is a run event, recorded once however often the node is re-entered.
5531    fn graft_skipped(&mut self, why: &str) {
5532        let message = format!("skipped: {why}");
5533        if !self
5534            .state
5535            .events
5536            .iter()
5537            .any(|e| e.node == "graft" && e.message == message)
5538        {
5539            self.state.event("graft", message);
5540        }
5541    }
5542
5543    async fn graft_inner(&mut self) -> Result<()> {
5544        // A round that was started and never finished (crash, kill): the
5545        // fixer may have left anything in the tree, so put the winner back.
5546        if let Some(rec) = self.state.graft.clone()
5547            && !rec.outcome.settled()
5548        {
5549            // Reviews exist only if the graft ended without its record being
5550            // settled (a swallowed error): the tree has moved on since, and
5551            // a reset to `pre` would discard the review fixes.
5552            if self.state.reviews.is_empty()
5553                && let Some(winner) = self.state.winner().cloned()
5554            {
5555                self.graft_restore(&winner.worktree, &rec.pre).await?;
5556            }
5557            if rec.outcome == GraftOutcome::WaitingForRestore {
5558                self.state.graft = None;
5559                self.state.save()?;
5560            } else {
5561                if let Some(g) = self.state.graft.as_mut() {
5562                    g.outcome = GraftOutcome::RolledBack(graft::INTERRUPTED.to_owned());
5563                }
5564                self.state.event(
5565                    "graft",
5566                    "rolled back: the previous round was interrupted; the winner is untouched",
5567                );
5568                self.state.save()?;
5569                return Ok(());
5570            }
5571        }
5572        let plan = match graft::plan(&self.state) {
5573            Ok(plan) => plan,
5574            Err(skip) => {
5575                if skip != graft::Skip::AlreadyDone {
5576                    self.graft_skipped(skip.reason());
5577                    self.state.save()?;
5578                }
5579                return Ok(());
5580            }
5581        };
5582        let Some(winner) = self.state.winner().cloned() else {
5583            return Ok(());
5584        };
5585        let wt = winner.worktree.clone();
5586        if !git::is_clean(&wt).await? {
5587            self.graft_skipped("the winner's worktree has uncommitted changes");
5588            self.state.save()?;
5589            return Ok(());
5590        }
5591        let pre = git::rev_parse(&wt, "HEAD").await?;
5592        // Saved before the fixer is called: a stop from here on is repaired
5593        // by the branch above on the next entry.
5594        self.state.graft = Some(GraftRecord {
5595            pre: pre.clone(),
5596            post: None,
5597            lines: None,
5598            limit: None,
5599            agent: None,
5600            outcome: GraftOutcome::Running,
5601            requested: graft::requested(&plan),
5602            adoption: None,
5603            adoption_error: None,
5604        });
5605        self.state.event(
5606            "graft",
5607            format!(
5608                "porting strengths of candidate(s) {} onto {}",
5609                plan.strengths
5610                    .iter()
5611                    .map(|(l, _, _)| l.to_string())
5612                    .collect::<Vec<_>>()
5613                    .join(", "),
5614                plan.winner
5615            ),
5616        );
5617        self.state.save()?;
5618
5619        let fix_prompt = prompt::graft(
5620            &self.state.instruction,
5621            plan.winner,
5622            &plan.strengths,
5623            &self.state.config.graph.language,
5624        );
5625        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
5626        let sessions = self.state.config.graph.sessions;
5627        let artifacts = agent::artifacts_dir(&self.state.dir());
5628        let attempts = fixer::graft_attempts(&self.state, &self.roles, &winner);
5629        let (_, seat, out) = self
5630            .ask_fixer_among(attempts, "graft", None, Some((&wt, &pre)), |spec, seat| {
5631                SeatJob {
5632                    prompt: fix_prompt.clone(),
5633                    spec,
5634                    seat,
5635                    cwd: wt.clone(),
5636                    timeout,
5637                    allow_write: true,
5638                    sessions,
5639                    artifacts: artifacts.clone(),
5640                    stem: "graft".to_owned(),
5641                    handover: None,
5642                }
5643            })
5644            .await;
5645        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
5646            // Preserve the need to restore earlier fallback edits without
5647            // confusing an unstarted seat with an interrupted invocation.
5648            self.state.graft.as_mut().expect("graft record").outcome =
5649                GraftOutcome::WaitingForRestore;
5650            return self.stop_for_resource();
5651        }
5652        let mut why: Option<String> = None;
5653        match &out {
5654            AgentOutcome::Ok(o) if agent::output_advances(o) => {
5655                why = Some("the fixer produced nothing usable".to_owned());
5656            }
5657            AgentOutcome::Ok(_) => {}
5658            AgentOutcome::Dropped(_) => why = Some("the CLI dropped the stream".to_owned()),
5659            AgentOutcome::Quota(o) => {
5660                self.state.quota.push(QuotaLoss::from_report(
5661                    seat.key.clone(),
5662                    "graft",
5663                    o.quota.as_ref(),
5664                ));
5665                why = Some("rate limited (quota)".to_owned());
5666            }
5667            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
5668                why = Some(format!(
5669                    "the fixer failed: {}",
5670                    e.lines()
5671                        .next()
5672                        .unwrap_or("")
5673                        .chars()
5674                        .take(160)
5675                        .collect::<String>()
5676                ));
5677            }
5678        }
5679        let agent_id = seat.agent.clone();
5680        self.state.seats.insert(seat.key.clone(), seat);
5681
5682        let mut post = None;
5683        let mut lines = None;
5684        let _coordination = self.coordinate(&wt).await?;
5685        if why.is_none() {
5686            let rescued = git::rescue_commit(&wt, "magi: graft (uncommitted work)").await;
5687            if let Ok(r) = &rescued {
5688                self.state.note_withheld("graft", &r.withheld);
5689            }
5690            let head = git::rev_parse(&wt, "HEAD").await?;
5691            // What is measured must be what gets reviewed and gated: a failed
5692            // rescue, or anything still uncommitted (withheld lockfiles
5693            // aside, which are never part of the tree), rejects the graft.
5694            let dirty = match &rescued {
5695                Ok(r) => git::status_porcelain(&wt)
5696                    .await
5697                    .map(|st| {
5698                        st.lines().any(|l| {
5699                            !r.withheld
5700                                .iter()
5701                                .any(|w| l.trim_end().ends_with(w.path.as_str()))
5702                        })
5703                    })
5704                    .unwrap_or(true),
5705                Err(_) => true,
5706            };
5707            if dirty {
5708                why = Some("the fixer left changes that could not be committed".to_owned());
5709            } else if head == pre {
5710                why = Some("the fixer changed nothing".to_owned());
5711            } else {
5712                lines = git::changed_lines(&wt, &pre, &head).await;
5713                post = Some(head);
5714            }
5715        }
5716        let (adoption, adoption_error) = match &out {
5717            AgentOutcome::Ok(o) => crate::graft_report::adoption_of(&o.text),
5718            _ => (None, None),
5719        };
5720        let requested = graft::requested(&plan);
5721        let outcome = match why {
5722            None => {
5723                self.state.event(
5724                    "graft",
5725                    format!(
5726                        "applied: {}",
5727                        lines.map_or_else(
5728                            || "changed lines unavailable".to_owned(),
5729                            |n| format!("{n} changed lines")
5730                        )
5731                    ),
5732                );
5733                GraftOutcome::Applied
5734            }
5735            Some(why) => {
5736                // Not settled until the restore is confirmed: the record
5737                // stays `Running`, so a resume retries it.
5738                crate::recovery::restore_repair(&wt, &pre)
5739                    .await
5740                    .map_err(|e| GraftRestoreFailed(format!("{e:#}")))?;
5741                self.state.event(
5742                    "graft",
5743                    format!("rolled back: {why}; the winner is untouched"),
5744                );
5745                GraftOutcome::RolledBack(why)
5746            }
5747        };
5748        self.state.graft = Some(GraftRecord {
5749            pre,
5750            post,
5751            lines,
5752            limit: None,
5753            agent: Some(agent_id),
5754            outcome,
5755            requested,
5756            adoption,
5757            adoption_error,
5758        });
5759        self.state.save()?;
5760        Ok(())
5761    }
5762
5763    // ----------------------------------------------------------------- fold
5764
5765    async fn fold_losers(&mut self) -> Result<()> {
5766        let Some(winner) = self.state.tally.as_ref().map(|t| t.winner) else {
5767            return Ok(());
5768        };
5769        if !self.state.candidate_preservation.is_empty() {
5770            bail!("candidate preservation incomplete; refusing cleanup");
5771        }
5772        let repo = self.state.repo.clone();
5773        let _coordination = self.coordinate(&repo).await?;
5774        let home = crate::run::home();
5775        let root = self.state.worktree_root();
5776        let isolated = crate::build_target::isolated(&self.state.config);
5777        let mut folded = Vec::new();
5778        for i in 0..self.state.candidates.len() {
5779            let c = &self.state.candidates[i];
5780            if c.label == winner || c.folded {
5781                continue;
5782            }
5783            let (wt, branch, label) = (c.worktree.clone(), c.branch.clone(), c.label);
5784            let target = fold_target(&home, &root, &wt, isolated);
5785            remove_preserved_worktree(&repo, &wt).await?;
5786            reclaim_fold_target(&home, target);
5787            if git::branch_exists(&repo, &branch).await?
5788                && !git::branch_delete(&repo, &branch).await?
5789            {
5790                bail!("candidate branch removal refused");
5791            }
5792            self.state.candidates[i].folded = true;
5793            self.state.save()?;
5794            folded.push(label.to_string());
5795        }
5796        // The judges are finished; their checkouts are pure cost from here.
5797        for j in 1..=self.roles.judges.len() {
5798            let wt = root.join(format!("judge-{j}"));
5799            if wt.exists() {
5800                let target = fold_target(&home, &root, &wt, isolated);
5801                remove_read_seat_worktree(&mut self.state, &wt).await?;
5802                reclaim_fold_target(&home, target);
5803                self.state.save()?;
5804            }
5805        }
5806        // The design-deliberation stage is finished by the time a tally
5807        // exists — same reasoning as the judges above.
5808        if self.state.config.graph.advise {
5809            for k in 1..=self.state.config.graph.advisors {
5810                let wt = root.join(format!("advisor-{k}"));
5811                if wt.exists() {
5812                    let target = fold_target(&home, &root, &wt, isolated);
5813                    remove_read_seat_worktree(&mut self.state, &wt).await?;
5814                    reclaim_fold_target(&home, target);
5815                    self.state.save()?;
5816                }
5817            }
5818        }
5819        if !folded.is_empty() {
5820            self.state
5821                .event("fold", format!("folded candidates {}", folded.join(", ")));
5822            self.state.save()?;
5823        }
5824        Ok(())
5825    }
5826
5827    // ------------------------------------------------------------ base sync
5828
5829    async fn hold_base_sync(&mut self) -> Result<bool> {
5830        self.hold_base_sync_as(None).await
5831    }
5832
5833    async fn hold_base_sync_kind(
5834        &mut self,
5835        kind: crate::base_sync_recovery::StopKind,
5836    ) -> Result<()> {
5837        self.hold_base_sync_as(Some(kind)).await?;
5838        Ok(())
5839    }
5840
5841    async fn hold_base_sync_as(
5842        &mut self,
5843        kind: Option<crate::base_sync_recovery::StopKind>,
5844    ) -> Result<bool> {
5845        if !self.state.base_sync_blocked() {
5846            self.state.base_sync_recovery.stop = None;
5847            return Ok(false);
5848        }
5849        let head = match self.state.winner() {
5850            Some(w) => git::rev_parse(&w.worktree, "HEAD")
5851                .await
5852                .unwrap_or_default(),
5853            None => String::new(),
5854        };
5855        if let Some(authorization) = self.state.base_sync_recovery.authorizations.last_mut()
5856            && !authorization.consumed
5857            && authorization.stop.head != head
5858        {
5859            authorization.refuse(format!(
5860                "retained HEAD changed from {} to {head}; inspect it and authorize again with --recover-base",
5861                authorization.stop.head
5862            ));
5863        }
5864        self.state.record_base_sync_stop(&head);
5865        if let Some(kind) = kind {
5866            self.state.base_sync_recovery.stop.as_mut().unwrap().kind = kind.clone();
5867            if let Some(stop) = self.state.base_sync_recovery.stops.last_mut() {
5868                stop.kind = kind;
5869            }
5870        }
5871        self.state.save()?;
5872        Ok(true)
5873    }
5874
5875    async fn resume_legacy_sequencer_stop(
5876        &mut self,
5877        winner: &Candidate,
5878        scratch: &Path,
5879        head: &str,
5880    ) -> Result<()> {
5881        use crate::repair_budget::legacy::{legacy_sequencer_head, resumable_sequencer_stop};
5882
5883        if !resumable_sequencer_stop(&self.state)
5884            || legacy_sequencer_head(&self.state) != Some(head)
5885            || self.state.base_recovery_pending()
5886            || self
5887                .state
5888                .repair_grants
5889                .iter()
5890                .any(|grant| !grant.succeeded)
5891        {
5892            return Ok(());
5893        }
5894        let Some(task) = self.state.origin.as_ref().and_then(|o| o.task.as_deref()) else {
5895            return Ok(());
5896        };
5897        let owner = crate::queue::Queue::open().get(task)?;
5898        if owner.execution_runs().last() != Some(&self.state.id)
5899            || owner.status == crate::queue::TaskStatus::Done
5900            || owner.fresh_start
5901            || owner.review_branch.is_some()
5902            || !crate::daemon::compatible_run_instruction(&self.state, &owner)
5903        {
5904            return Ok(());
5905        }
5906
5907        let repo = self.state.repo.clone();
5908        let wait = repository_wait(&self.state, None);
5909        let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
5910        let common = crate::repo_lock::common_dir(&repo).await?;
5911        let op = self.state.base_sync_recovery.operations.last().unwrap();
5912        if git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
5913            || git::rev_parse(&winner.worktree, "HEAD").await? != head
5914            || git::current_branch(&winner.worktree).await?.as_deref()
5915                != Some(winner.branch.as_str())
5916            || common.is_none()
5917            || crate::repo_lock::common_dir(&winner.worktree).await? != common
5918            || crate::repo_lock::common_dir(&owner.repo).await? != common
5919            || !git::is_clean(&winner.worktree).await?
5920        {
5921            return Ok(());
5922        }
5923        if scratch.try_exists()? {
5924            let admin = git::rebase_scratch_admin(&repo, scratch).await?;
5925            if admin.join("locked").try_exists()?
5926                || !git::git(
5927                    scratch,
5928                    &[
5929                        "status",
5930                        "--porcelain",
5931                        "--untracked-files=all",
5932                        "--ignored",
5933                    ],
5934                )
5935                .await?
5936                .is_empty()
5937            {
5938                return Ok(());
5939            }
5940            if git::checked_rebase_in_progress(scratch).await? {
5941                if crate::rebase::saved_base_identity(scratch, &winner.branch).await? != head
5942                    || crate::rebase::rebase_target(scratch).await? != op.tip
5943                    || !git::unmerged_paths(scratch).await?.is_empty()
5944                {
5945                    return Ok(());
5946                }
5947            } else if git::current_branch(scratch).await?.as_deref() != Some(winner.branch.as_str())
5948                || git::rev_parse(scratch, "HEAD").await? != head
5949            {
5950                return Ok(());
5951            }
5952        }
5953
5954        self.state
5955            .base_sync_recovery
5956            .operations
5957            .last_mut()
5958            .unwrap()
5959            .finished = false;
5960        let diagnostic = self
5961            .state
5962            .base_sync
5963            .as_mut()
5964            .unwrap()
5965            .conflict
5966            .take()
5967            .unwrap();
5968        self.state.base_sync_recovery.stop = None;
5969        self.state.event(
5970            "rebase",
5971            format!("reopened the original reservation for a legacy sequencer infrastructure stop: {diagnostic}"),
5972        );
5973        self.state.save()
5974    }
5975
5976    /// Land the winner's tree on the current tip of `<remote>/<base>` before
5977    /// anything verifies it.
5978    ///
5979    /// `verify.e2e`, `verify.gate` and every reviewer in [`Self::review_loop`]
5980    /// read whatever is checked out in the winner's worktree. Left alone that
5981    /// tree stays rooted at `base_commit` - the base as [`resolve_base`] saw
5982    /// it when the run *branched* - and a run takes long enough that the base
5983    /// has usually moved by the time it gets here. A gate that ran there
5984    /// answers "green on the commit this run started from", not "green on
5985    /// what is about to land", and the difference showed up three times in
5986    /// one day as a green run whose merge would have reverted a file another
5987    /// pull request had already landed.
5988    ///
5989    /// Reuses [`crate::rebase::rebase_with_fixer`], the same routine
5990    /// `land::Step::Rebase` calls, rather than a second implementation of the
5991    /// same idea: a throwaway worktree, nothing runs in the primary tree, and
5992    /// a second rebase path is exactly the kind of drift `resolve_base`'s own
5993    /// doc warns about ("two answers to a question nobody notices until a
5994    /// diff is wrong").
5995    ///
5996    /// Foreign-checkout reviews instead merge the base into the owned shadow
5997    /// worktree, preserving the ancestry required for fast-forward delivery.
5998    /// A conflicting merge is aborted and held for operator resolution.
5999    ///
6000    /// A conflict is not the end of the road: the standing rebase is handed
6001    /// to the fixer seat, at most `graph.review_rounds` times, counted in
6002    /// `state.rebase_fixes` (so it survives a park/resume and is shared with
6003    /// land). Once it finishes, review and the gate run as usual on the
6004    /// rebased tree, which is where a breakage the new base caused is caught
6005    /// by the ordinary gate-fix round. magi resolves nothing itself.
6006    ///
6007    /// Two different bounds, easy to confuse: [`BASE_SYNC_ROUNDS`], counted in
6008    /// the current durable recovery interval, bounds how often the base is
6009    /// synchronized during active recovery (lifetime attempts remain evidence).
6010    /// `rebase_fixes` is how many times a *conflict* was given to a fixer. When the fixer cannot finish the
6011    /// rebase the branch is restored, `state.base_sync.conflict` is set with
6012    /// what was tried (rounds spent, paths still conflicted) and the branch
6013    /// and worktree stay exactly as they were - untouched, for a person to
6014    /// look at - which is also what makes re-entering this function
6015    /// afterwards a no-op instead of a second attempt at the same wall. A
6016    /// push failure ends the same way.
6017    async fn sync_to_base(&mut self) -> Result<()> {
6018        if self.state.status == RunStatus::AlreadyInBase {
6019            return Ok(());
6020        }
6021        self.hold_base_sync().await?;
6022        let Some(winner) = self.state.winner().cloned() else {
6023            return Ok(());
6024        };
6025
6026        crate::worktree_clean::resume_pending(&mut self.state, &winner.worktree).await?;
6027
6028        let repo = self.state.repo.clone();
6029        let remote = self.state.config.merge.remote.clone();
6030        let base_branch = self.state.base_branch.clone();
6031        let tracking = format!("{remote}/{base_branch}");
6032
6033        let fetched_base =
6034            matches!(git::fetch(&repo, &remote, &base_branch).await, Ok(o) if o.ok());
6035        if !fetched_base
6036            && self
6037                .state
6038                .base_sync_recovery
6039                .stop
6040                .as_ref()
6041                .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Divergence)
6042        {
6043            self.state.event(
6044                "land",
6045                "cannot recheck recorded public branch divergence without a fresh base",
6046            );
6047            self.state.save()?;
6048            return Ok(());
6049        }
6050        // No network, or the remote never had this branch: the run already
6051        // started from a fetched `<remote>/<base>` (`resolve_base` refuses
6052        // otherwise), and one that got this far is not blocked by a fetch
6053        // that fails now. It just has no newer tip to compare against.
6054        let Ok(mut tip) = git::rev_parse(&repo, &tracking).await else {
6055            return Ok(());
6056        };
6057
6058        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
6059        self.state.ensure_base_episode();
6060        let scratch = self.state.dir().join("base-sync");
6061        self.resume_legacy_sequencer_stop(&winner, &scratch, &head)
6062            .await?;
6063        let conflicted = self
6064            .state
6065            .base_sync
6066            .as_ref()
6067            .is_some_and(|s| s.conflict.is_some());
6068        let mut pending = self.state.pending_base_operation().cloned();
6069        let in_progress = match crate::rebase::checked_progress(&mut self.state, &scratch, "").await
6070        {
6071            Ok(active) => active,
6072            Err(error) if error.is::<crate::repo_lock::ResourceBlocked>() => return Ok(()),
6073            Err(error) => return Err(error),
6074        };
6075        if in_progress {
6076            // Older resource stops predate operation reservations. Import the
6077            // standing Git operation, never retarget it to today's main.
6078            if pending.is_none()
6079                && self.state.base_sync_recovery.operations.is_empty()
6080                && !conflicted
6081                && crate::rebase::saved_base_identity(&scratch, &winner.branch)
6082                    .await
6083                    .ok()
6084                    .as_deref()
6085                    == Some(head.as_str())
6086                && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
6087                && git::is_clean(&winner.worktree).await?
6088            {
6089                let saved_tip = crate::rebase::rebase_target(&scratch).await?;
6090                if self.state.base_sync.is_none() {
6091                    self.state.base_sync = Some(BaseSync {
6092                        tip: saved_tip.clone(),
6093                        behind: 0,
6094                        attempts: 0,
6095                        conflict: None,
6096                        already_in: None,
6097                    });
6098                }
6099                self.state.reserve_base_operation(&head, &saved_tip);
6100                self.state.event(
6101                    "base-recovery",
6102                    "imported standing legacy rebase as a spent synchronization reservation",
6103                );
6104                self.state.save()?;
6105                pending = self.state.base_sync_recovery.operations.last().cloned();
6106            }
6107            let expected = pending.as_ref().map(|op| op.tip.as_str());
6108            if expected.is_none()
6109                || crate::rebase::rebase_target(&scratch).await.as_deref().ok() != expected
6110            {
6111                let why = "saved scratch rebase targets a different base; inspect the retained rebase before resuming";
6112                if self.state.base_sync.is_none() {
6113                    self.state.base_sync = Some(BaseSync {
6114                        tip: tip.clone(),
6115                        behind: 0,
6116                        attempts: 0,
6117                        conflict: None,
6118                        already_in: None,
6119                    });
6120                }
6121                self.state.base_sync.as_mut().unwrap().conflict = Some(why.into());
6122                self.state.event("land", why);
6123                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Unknown)
6124                    .await?;
6125                return Ok(());
6126            }
6127        }
6128        if let Some(op) = &pending {
6129            // A replay may add the pinned base's commits, never foreign work.
6130            let mut replay_proven =
6131                head == op.head || op.validated_head.as_deref() == Some(head.as_str());
6132            if !replay_proven && !in_progress && scratch.try_exists()? {
6133                let wait = repository_wait(&self.state, None);
6134                let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
6135                match crate::rebase::recover_completed_base(&self.state, &scratch, &winner.branch, op, &head).await {
6136                    Ok(true) => {
6137                        self.state.base_sync_recovery.operations.last_mut().unwrap().validated_head = Some(head.clone());
6138                        self.state.save()?;
6139                        git::worktree_remove(&repo, &scratch).await.ok();
6140                        replay_proven = true;
6141                    }
6142                    Ok(false) => self.state.event("base-recovery", "completed scratch failed result validation; retained for inspection"),
6143                    Err(error) => self.state.event("base-recovery", format!("completed scratch could not be validated; retained for inspection: {error:#}")),
6144                }
6145            }
6146            if !replay_proven && git::is_ancestor(&repo, &op.tip, &head).await {
6147                if self.state.foreign_checkout.is_some() {
6148                    replay_proven = git::rev_parse(&repo, &format!("{head}^1"))
6149                        .await
6150                        .ok()
6151                        .as_deref()
6152                        == Some(op.head.as_str())
6153                        && git::rev_parse(&repo, &format!("{head}^2"))
6154                            .await
6155                            .ok()
6156                            .as_deref()
6157                            == Some(op.tip.as_str());
6158                } else if crate::reconcile::origin_missing(&repo, &head, &op.head)
6159                    .await
6160                    .is_ok_and(|m| m.is_empty())
6161                    && let Ok(added) =
6162                        crate::reconcile::origin_missing(&repo, &op.head, &head).await
6163                {
6164                    replay_proven = true;
6165                    for commit in added {
6166                        if !git::is_ancestor(&repo, &commit, &op.tip).await {
6167                            replay_proven = false;
6168                            break;
6169                        }
6170                    }
6171                    replay_proven &= git::commits_ahead(&repo, &op.tip, &head).await?
6172                        <= git::commits_ahead(&repo, &op.tip, &op.head).await?;
6173                }
6174            }
6175            // Never retarget an operation across a crash, even if main moved.
6176            // sync_to_head resets and cleans with -x, so even ignored untracked
6177            // files must stop recovery independently of the old tracked tree.
6178            if git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
6179                || (head != op.head
6180                    && !git::git(&winner.worktree, &["ls-files", "--others", "-z"])
6181                        .await?
6182                        .is_empty())
6183                || (!git::is_clean(&winner.worktree).await?
6184                    && !git::git_raw(&winner.worktree, &["diff", "--quiet", &op.head])
6185                        .await
6186                        .is_ok_and(|o| o.ok()))
6187                || !replay_proven
6188            {
6189                let why = format!(
6190                    "unfinished base synchronization {} has unrecognized branch/worktree state; inspect the retained branch and scratch rebase before resuming",
6191                    op.id
6192                );
6193                let sync = self
6194                    .state
6195                    .base_sync
6196                    .as_mut()
6197                    .context("reserved synchronization has no lifetime accounting")?;
6198                sync.conflict = Some(why.clone());
6199                self.state.event("land", why);
6200                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Unknown)
6201                    .await?;
6202                return Ok(());
6203            }
6204            if head != op.head {
6205                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6206            }
6207            tip = op.tip.clone();
6208        }
6209        let behind = git::commits_ahead(&repo, &head, &tip).await.unwrap_or(0);
6210        let attempts = self.state.base_sync.as_ref().map_or(0, |s| s.attempts);
6211        if pending.is_none()
6212            && !conflicted
6213            && fetched_base
6214            && self
6215                .state
6216                .base_sync_recovery
6217                .episodes
6218                .last()
6219                .is_some_and(|e| e.boundary.is_some())
6220            && let Some(task) = self.state.origin.as_ref().and_then(|o| o.task.clone())
6221            && let Ok(owner) = crate::queue::Queue::open().get(&task)
6222            && owner.execution_runs().last() == Some(&self.state.id)
6223            && owner.status != crate::queue::TaskStatus::Done
6224            && !owner.fresh_start
6225            && owner.review_branch.is_none()
6226            && crate::daemon::compatible_run_instruction(&self.state, &owner)
6227            && let Some(approval) = owner.resumption.as_ref()
6228            && approval.instruction == owner.instruction
6229            && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
6230            && git::is_clean(&winner.worktree).await?
6231            && self.state.renew_base_episode(&task, approval, &head, &tip)
6232        {
6233            self.state.event("base-recovery", "opened bounded synchronization interval after owner-approved infrastructure recovery");
6234            self.state.save()?;
6235        }
6236
6237        // Before any rebase, and before a recorded conflict is honoured: a
6238        // branch whose change reached the base under other commit ids has
6239        // nothing to rebase and nothing to conflict with, and a run that
6240        // already stopped on that phantom conflict recovers here on resume.
6241        // `behind == 0` with head == tip is a branch the base has since taken
6242        // in whole, whether or not a conflict was ever recorded: the ancestry
6243        // proof must still run (`classify` ignores a head still on the start
6244        // commit).
6245        if (behind > 0 || conflicted || head == tip)
6246            && self
6247                .settle_already_in(&winner.branch, &tip, &head, attempts, behind)
6248                .await?
6249        {
6250            return Ok(());
6251        }
6252        if conflicted && self.state.base_recovery_pending() {
6253            let authorization = self.state.base_sync_recovery.authorizations.last().unwrap();
6254            let owner =
6255                crate::queue::Queue::at(crate::run::home().join("queue")).get(&authorization.task);
6256            let owner_valid = owner.as_ref().is_ok_and(|t| {
6257                t.execution_runs().last() == Some(&self.state.id)
6258                    && t.assignment_accepts(&self.state)
6259                    && t.status != crate::queue::TaskStatus::Done
6260                    && !t.fresh_start
6261                    && t.review_branch.is_none()
6262            });
6263            let invalidation = if !owner_valid {
6264                Some("latest task ownership changed")
6265            } else if !owner.as_ref().is_ok_and(|t| {
6266                authorization
6267                    .generation
6268                    .is_none_or(|g| t.resumption.as_ref().is_some_and(|r| r.generation == g))
6269            }) {
6270                Some("owner approval generation changed")
6271            } else if authorization.question.as_ref().is_some_and(|question| {
6272                !crate::base_recovery_control::decision_current(
6273                    &crate::queue::Queue::at(crate::run::home().join("queue")),
6274                    &self.state,
6275                    &authorization.task,
6276                    question,
6277                )
6278            }) {
6279                Some("recovery decision ownership, routing or stop evidence changed")
6280            } else if authorization.request.is_some()
6281                && !owner
6282                    .as_ref()
6283                    .is_ok_and(|t| t.operator_decided_at == authorization.decision)
6284            {
6285                Some("owner decision changed")
6286            } else if authorization.stop.kind == crate::base_sync_recovery::StopKind::Unknown
6287                && !authorization.scope.as_ref().is_some_and(|scope| {
6288                    scope.preparation_digest.is_some()
6289                        && scope.preparation_digest == self.state.preparation_digest(&head)
6290                })
6291            {
6292                Some("scratch preparation stop evidence changed")
6293            } else if let Some(scope) = &authorization.scope {
6294                if scope.tip != tip {
6295                    Some("fetched base changed")
6296                } else if !self
6297                    .state
6298                    .base_sync_recovery
6299                    .episodes
6300                    .last()
6301                    .is_some_and(|e| e.id == scope.episode)
6302                {
6303                    Some("active synchronization interval changed")
6304                } else if !owner
6305                    .as_ref()
6306                    .is_ok_and(|t| t.instruction == scope.instruction)
6307                {
6308                    Some("task instruction changed")
6309                } else {
6310                    None
6311                }
6312            } else {
6313                None
6314            };
6315            if let Some(reason) = invalidation {
6316                let authorization = self
6317                    .state
6318                    .base_sync_recovery
6319                    .authorizations
6320                    .last_mut()
6321                    .unwrap();
6322                authorization.refuse(format!("{reason}; authorize again with --recover-base"));
6323                self.state.save()?;
6324                return Ok(());
6325            }
6326            if !fetched_base
6327                || git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
6328                || !git::is_clean(&winner.worktree).await?
6329                || !owner.is_ok_and(|t| t.execution_runs().last() == Some(&self.state.id))
6330            {
6331                return Ok(());
6332            }
6333            if authorization.stop.kind == crate::base_sync_recovery::StopKind::Unknown {
6334                git::check_rebase_preparation(&self.state, &head, &self.state.dir()).await?;
6335            }
6336        }
6337        let recovery = conflicted && self.state.consume_base_recovery(&head);
6338        if conflicted {
6339            // Consumption (including a refused changed HEAD) is durable before Git.
6340            self.state.save()?;
6341            if !recovery {
6342                return Ok(());
6343            }
6344        }
6345
6346        if behind == 0 {
6347            // A fixer-finished rebase moves the branch ref before the
6348            // winner's worktree is told (`sync_to_head` below). A run that
6349            // died in between resumes here with `behind == 0` and a tree still
6350            // holding the pre-rebase files, which review and the gate would
6351            // then read. That state is exactly: HEAD moved off the tip the
6352            // rebase started from, yet the tree is still identical to that
6353            // tip. A tree with edits of its own differs from it, so nothing
6354            // is thrown away.
6355            if let Some(from) = self
6356                .state
6357                .rebase_fixes
6358                .iter()
6359                .rev()
6360                .find_map(|r| r.from.clone())
6361                && from != head
6362                && git::git_raw(&winner.worktree, &["diff", "--quiet", &from])
6363                    .await
6364                    .is_ok_and(|o| o.ok())
6365            {
6366                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6367            }
6368            // An earlier attempt may have rebased the branch locally and died
6369            // before pushing it (only the fresh-rebase arm below pushes).
6370            // Publish it now, so the plain push at PR time is not refused as
6371            // a non-fast-forward. A run already holding a recorded conflict
6372            // never reaches here; that case is out of scope.
6373            let conflict = self.publish_resumed_rebase(&winner.branch, &head).await;
6374            if let Some(why) = &conflict {
6375                self.state.status = RunStatus::Blocked;
6376                self.state.event("land", why.clone());
6377            }
6378            self.state.base_sync = Some(BaseSync {
6379                tip,
6380                behind: 0,
6381                attempts,
6382                conflict,
6383                already_in: None,
6384            });
6385            if pending.is_some() {
6386                self.state.finish_base_operation(Some(&head));
6387            }
6388            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Publication)
6389                .await?;
6390            self.state.save()?;
6391            return Ok(());
6392        }
6393
6394        if self.state.base_episode_used() >= BASE_SYNC_ROUNDS && pending.is_none() && !recovery {
6395            let why = format!(
6396                "{base_branch} moved {behind} commit(s) ahead of {} after {BASE_SYNC_ROUNDS} \
6397                 synchronization(s); synchronizing again would only race it",
6398                winner.branch
6399            );
6400            self.state.status = RunStatus::Blocked;
6401            self.state.base_sync = Some(BaseSync {
6402                tip,
6403                behind,
6404                attempts,
6405                conflict: Some(why.clone()),
6406                already_in: None,
6407            });
6408            self.state.event("land", why);
6409            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Exhausted)
6410                .await?;
6411            self.state.save()?;
6412            return Ok(());
6413        }
6414
6415        if self.state.foreign_checkout.is_some() {
6416            // Delivery to the operator's checkout is fast-forward only. A
6417            // rebase here would discard its saved head from our ancestry.
6418            let wait = repository_wait(&self.state, None);
6419            let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
6420            if self.state.base_sync.is_none() {
6421                self.state.base_sync = Some(BaseSync {
6422                    tip: tip.clone(),
6423                    behind,
6424                    attempts: 0,
6425                    conflict: None,
6426                    already_in: None,
6427                });
6428            }
6429            self.state.reserve_base_operation(&head, &tip);
6430            self.state.save()?;
6431            let merged = git::git_raw(
6432                &winner.worktree,
6433                &[
6434                    "-c",
6435                    "core.hooksPath=/dev/null",
6436                    "merge",
6437                    "--no-ff",
6438                    "--no-autostash",
6439                    "--no-edit",
6440                    "-m",
6441                    &format!("Merge {tracking} before verifying"),
6442                    &tip,
6443                ],
6444            )
6445            .await?;
6446            let conflict = if merged.ok() {
6447                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
6448                self.state.event(
6449                    "land",
6450                    format!("merged {tracking} into {} before verifying", winner.branch),
6451                );
6452                None
6453            } else {
6454                if git::rev_exists(&winner.worktree, "MERGE_HEAD").await {
6455                    git::git(&winner.worktree, &["merge", "--abort"]).await?;
6456                }
6457                let why = format!(
6458                    "could not merge {tracking} into {} without rewriting foreign checkout history: {}",
6459                    winner.branch,
6460                    merged.stderr.chars().take(600).collect::<String>()
6461                );
6462                self.state.status = RunStatus::Blocked;
6463                self.state.event("land", &why);
6464                Some(why)
6465            };
6466            let synced = conflict.is_none();
6467            let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
6468            self.state
6469                .finish_base_operation(synced.then_some(fresh.as_str()));
6470            let attempts = self.state.base_sync.as_ref().unwrap().attempts;
6471            self.state.base_sync = Some(BaseSync {
6472                tip,
6473                behind: if synced { 0 } else { behind },
6474                attempts,
6475                conflict,
6476                already_in: None,
6477            });
6478            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Conflict)
6479                .await?;
6480            self.state.save()?;
6481            return Ok(());
6482        }
6483
6484        self.state.event(
6485            "land",
6486            format!(
6487                "{base_branch} moved {behind} commit(s) ahead of {}; rebasing before verifying",
6488                winner.branch
6489            ),
6490        );
6491        self.state.save()?;
6492
6493        // The remote's copy of the branch, read now and only if the fetch
6494        // really succeeded (a stale tracking ref must never pin a lease). It is
6495        // pushed over after a rebase only when it is a commit this branch
6496        // already contains, by ancestry or by patch (an earlier rebase of ours
6497        // that never reached the remote): anything else is somebody else's work.
6498        let branch_tracking = format!("{remote}/{}", winner.branch);
6499        let fetched_branch = git::fetch(&repo, &remote, &winner.branch).await;
6500        let remote_tip = if self.state.task_pr_branch().is_none()
6501            && matches!(&fetched_branch, Ok(o) if o.ok())
6502        {
6503            git::rev_parse(&repo, &branch_tracking).await.ok()
6504        } else {
6505            None
6506        };
6507        // A remote tip this branch does not contain is somebody else's work:
6508        // rebasing would leave a local tip that can never be pushed. Stop
6509        // before touching anything and say so.
6510        if let Some(theirs) = &remote_tip
6511            && !git::is_ancestor(&repo, theirs, &head).await
6512            && !crate::reconcile::origin_missing(&repo, &head, theirs)
6513                .await
6514                .is_ok_and(|missing| missing.is_empty())
6515        {
6516            let why = format!(
6517                "{branch_tracking} ({}) has commits {} does not contain; not rebasing over \
6518                 them",
6519                short(theirs),
6520                winner.branch
6521            );
6522            self.state.status = RunStatus::Blocked;
6523            self.state.base_sync = Some(BaseSync {
6524                tip,
6525                behind,
6526                attempts,
6527                conflict: Some(why.clone()),
6528                already_in: None,
6529            });
6530            self.state.event("land", why);
6531            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Divergence)
6532                .await?;
6533            self.state.save()?;
6534            return Ok(());
6535        }
6536
6537        if self.state.base_sync.is_none() {
6538            self.state.base_sync = Some(BaseSync {
6539                tip: tip.clone(),
6540                behind,
6541                attempts: 0,
6542                conflict: None,
6543                already_in: None,
6544            });
6545        }
6546        let scratch = self.state.dir().join("base-sync");
6547        if let Err(error) = crate::rebase::prepare(&mut self.state, &scratch, &winner.branch).await
6548        {
6549            if error.is::<crate::repo_lock::ResourceBlocked>() {
6550                return Ok(());
6551            }
6552            return Err(error);
6553        }
6554        self.state.reserve_base_operation(&head, &tip);
6555        self.state.save()?;
6556        let rebased =
6557            match crate::rebase::rebase_prepared(&mut self.state, &scratch, &winner.branch, &tip)
6558                .await
6559            {
6560                Ok(crate::rebase::Rebased::Applied) => Ok(None),
6561                Ok(crate::rebase::Rebased::Stopped(why)) => Ok(Some(why)),
6562                Err(e) => Err(e),
6563            };
6564        let attempts = self.state.base_sync.as_ref().unwrap().attempts;
6565        let stop_kind = match &rebased {
6566            Ok(None) => crate::base_sync_recovery::StopKind::Publication,
6567            Ok(Some(_)) => crate::base_sync_recovery::StopKind::Conflict,
6568            Err(_) => crate::base_sync_recovery::StopKind::Unknown,
6569        };
6570        match rebased {
6571            Ok(None) => {
6572                // The branch ref moved, but a worktree that already had it
6573                // checked out (the winner's) was not told; sync its index and
6574                // files before anything reads them.
6575                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6576                let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
6577                self.state.finish_base_operation(Some(&fresh));
6578                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
6579                let mut conflict = None;
6580                if let Some(pinned) = &remote_tip {
6581                    let pushed = git::push_pinned(&repo, &remote, &winner.branch, pinned).await;
6582                    match pushed {
6583                        Ok(o) if o.ok() => self.state.event(
6584                            "land",
6585                            format!("pushed rebased {} to {remote}", winner.branch),
6586                        ),
6587                        Ok(o) => {
6588                            conflict = Some(format!(
6589                                "rebased {} locally but {remote} refused the push (it moved                                  since {}; someone may have pushed): {}",
6590                                winner.branch,
6591                                short(pinned),
6592                                o.stderr.chars().take(600).collect::<String>()
6593                            ));
6594                        }
6595                        Err(e) => {
6596                            conflict = Some(format!(
6597                                "rebased {} locally but could not push it: {e:#}",
6598                                winner.branch
6599                            ));
6600                        }
6601                    }
6602                }
6603                if let Some(why) = &conflict {
6604                    self.state.status = RunStatus::Blocked;
6605                    self.state.event("land", why.clone());
6606                }
6607                self.state.base_sync = Some(BaseSync {
6608                    tip: tip.clone(),
6609                    behind: 0,
6610                    attempts,
6611                    conflict,
6612                    already_in: None,
6613                });
6614                self.state
6615                    .event("land", format!("rebased {} onto {tracking}", winner.branch));
6616            }
6617            Ok(Some(conflict)) => {
6618                self.state.finish_base_operation(None);
6619                let why = format!(
6620                    "{} conflicts with {tracking} and did not rebase: {}",
6621                    winner.branch,
6622                    conflict.chars().take(600).collect::<String>()
6623                );
6624                self.state.status = RunStatus::Blocked;
6625                self.state.base_sync = Some(BaseSync {
6626                    tip,
6627                    behind,
6628                    attempts,
6629                    conflict: Some(why.clone()),
6630                    already_in: None,
6631                });
6632                self.state.event("land", why);
6633            }
6634            // A refused Git write or a busy repository: nothing is wrong with
6635            // the branch. The scratch rebase stays standing and the run
6636            // resumes into it (`base_sync` must not claim a conflict).
6637            Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
6638                self.state.save()?;
6639                return Ok(());
6640            }
6641            Err(e) => {
6642                self.state.finish_base_operation(None);
6643                let why = format!("could not rebase {} onto {tracking}: {e:#}", winner.branch);
6644                self.state.status = RunStatus::Blocked;
6645                self.state.base_sync = Some(BaseSync {
6646                    tip,
6647                    behind,
6648                    attempts,
6649                    conflict: Some(why.clone()),
6650                    already_in: None,
6651                });
6652                self.state.event("land", why);
6653            }
6654        }
6655        if !self.state.base_sync_blocked() {
6656            self.state.base_sync_recovery.stop = None;
6657        }
6658        self.hold_base_sync_kind(stop_kind).await?;
6659        self.state.save()?;
6660        Ok(())
6661    }
6662
6663    /// Push a branch an earlier attempt rebased locally but never published,
6664    /// pinned to the remote tip read right after a successful fetch. Returns
6665    /// the reason when the run must stop; `None` when there was nothing to do
6666    /// (no remote copy, the same tip, or a remote copy this branch already
6667    /// contains, which the PR-time push fast-forwards) or the push succeeded.
6668    async fn publish_resumed_rebase(&mut self, branch: &str, head: &str) -> Option<String> {
6669        // Task competitions publish only after the PR text gate, to their
6670        // public head; never resurrect a candidate branch on the remote.
6671        if self.state.task_pr_branch().is_some() {
6672            return None;
6673        }
6674        let repo = self.state.repo.clone();
6675        let remote = self.state.config.merge.remote.clone();
6676        let fetched = git::fetch(&repo, &remote, branch).await;
6677        if !matches!(&fetched, Ok(o) if o.ok()) {
6678            return None;
6679        }
6680        let branch_tracking = format!("{remote}/{branch}");
6681        let theirs = git::rev_parse(&repo, &branch_tracking).await.ok()?;
6682        if theirs == head || git::is_ancestor(&repo, &theirs, head).await {
6683            return None;
6684        }
6685        if !crate::reconcile::origin_missing(&repo, head, &theirs)
6686            .await
6687            .is_ok_and(|missing| missing.is_empty())
6688        {
6689            return Some(format!(
6690                "{branch_tracking} ({}) has commits {branch} does not contain; not pushing over \
6691                 them",
6692                short(&theirs)
6693            ));
6694        }
6695        match git::push_pinned(&repo, &remote, branch, &theirs).await {
6696            Ok(o) if o.ok() => {
6697                self.state
6698                    .event("land", format!("pushed rebased {branch} to {remote}"));
6699                None
6700            }
6701            Ok(o) => Some(format!(
6702                "{branch} is rebased locally but {remote} refused the push (it moved since {}; \
6703                 someone may have pushed): {}",
6704                short(&theirs),
6705                o.stderr.chars().take(600).collect::<String>()
6706            )),
6707            Err(e) => Some(format!(
6708                "{branch} is rebased locally but could not be pushed: {e:#}"
6709            )),
6710        }
6711    }
6712
6713    /// End the run as [`RunStatus::AlreadyInBase`] when `head`'s whole change
6714    /// is already on `tip` under other commit ids ([`crate::already`]); returns
6715    /// whether it did.
6716    ///
6717    /// Checked only when the base is ahead of the branch. A failing check is
6718    /// "not proven" - the ordinary rebase path then decides - never a reason to
6719    /// stop the run.
6720    ///
6721    /// The remote copy of the branch is held to the same standard as the local
6722    /// one: if it carries a tip this worktree does not, that tip must itself be
6723    /// proven in the base, or nothing is settled (a pull request would
6724    /// otherwise be closed over commits nobody checked). The pull request is
6725    /// closed *before* the terminal status is saved; if that fails for a
6726    /// reason other than a refusal (no network, a `gh` error) the run is left
6727    /// `Blocked` with the reason as its conflict, which a resume retries -
6728    /// the same recovery a phantom conflict gets.
6729    async fn settle_already_in(
6730        &mut self,
6731        branch: &str,
6732        tip: &str,
6733        head: &str,
6734        attempts: usize,
6735        behind: usize,
6736    ) -> Result<bool> {
6737        let repo = self.state.repo.clone();
6738        let remote = self.state.config.merge.remote.clone();
6739        let start = self.state.base_commit.clone();
6740        let evidence = match crate::already::classify(&repo, tip, head, Some(&start)).await {
6741            Ok(Some(e)) => e,
6742            Ok(None) => return Ok(false),
6743            Err(e) => {
6744                tracing::warn!("already-in-base check for {branch}: {e:#}");
6745                return Ok(false);
6746            }
6747        };
6748        let mut verified = vec![head.to_owned()];
6749        let public_branch = self.state.pr_branch().unwrap_or(branch).to_owned();
6750        let fetched = git::fetch(&repo, &remote, &public_branch).await;
6751        let divergence = self
6752            .state
6753            .base_sync_recovery
6754            .stop
6755            .as_ref()
6756            .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Divergence);
6757        if matches!(&fetched, Ok(o) if o.ok()) {
6758            match git::rev_parse(&repo, &format!("{remote}/{public_branch}")).await {
6759                Ok(theirs) if theirs != head => {
6760                    match crate::already::classify(&repo, tip, &theirs, Some(&start)).await {
6761                        Ok(Some(_)) => verified.push(theirs),
6762                        _ => return Ok(false),
6763                    }
6764                }
6765                Err(_) if divergence => return Ok(false),
6766                _ => {}
6767            }
6768        } else if divergence
6769            && !matches!(
6770                git::remote_has_branch(&repo, &remote, &public_branch).await,
6771                Ok(false)
6772            )
6773        {
6774            // A failed fetch cannot discharge a recorded divergence.
6775            return Ok(false);
6776        }
6777        let base_branch = self.state.base_branch.clone();
6778        let message = format!(
6779            "{branch} is already in {remote}/{base_branch} as {} ({} match); nothing left to \
6780             land",
6781            evidence.names(),
6782            evidence.proof.as_str()
6783        );
6784        let closed =
6785            crate::land::close_superseded_pr(&mut self.state, &public_branch, &evidence, &verified)
6786                .await;
6787        match closed {
6788            Ok(Ok(url)) => self
6789                .state
6790                .event("land", format!("closed {url}: superseded on {base_branch}")),
6791            Ok(Err(why)) => self
6792                .state
6793                .event("land", format!("did not close a pull request: {why}")),
6794            Err(e) => {
6795                let why = format!(
6796                    "{branch} is already in {remote}/{base_branch}, but its pull request could \
6797                     not be closed ({e:#}); resume to retry"
6798                );
6799                self.state.status = RunStatus::Blocked;
6800                self.state.base_sync = Some(BaseSync {
6801                    tip: tip.to_owned(),
6802                    behind,
6803                    attempts,
6804                    conflict: Some(why.clone()),
6805                    already_in: None,
6806                });
6807                self.state.event("land", why);
6808                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::ClosingIntegratedPr)
6809                    .await?;
6810                self.state.save()?;
6811                return Ok(true);
6812            }
6813        }
6814        self.state.status = RunStatus::AlreadyInBase;
6815        self.state.base_sync_recovery.stop = None;
6816        self.state.base_sync = Some(BaseSync {
6817            tip: tip.to_owned(),
6818            behind,
6819            attempts,
6820            conflict: None,
6821            already_in: Some(evidence),
6822        });
6823        self.state.event("land", message);
6824        self.state.save()?;
6825        self.settle_questions();
6826        Ok(true)
6827    }
6828
6829    /// The commit review and gate diff against: the tip [`Self::sync_to_base`]
6830    /// last landed the winner on, once it has run, else the commit the run
6831    /// branched from.
6832    ///
6833    /// Only [`Self::review_loop`] reads this. `prep`, `judge`, `deliberate`
6834    /// and `vote` all happen before there is a winner to rebase, so they
6835    /// compare every candidate against the branch point on purpose, and a
6836    /// base that moves after they are already done cannot change an answer
6837    /// they already gave.
6838    fn landing_base(&self) -> String {
6839        self.state
6840            .base_sync
6841            .as_ref()
6842            .map_or_else(|| self.state.base_commit.clone(), |s| s.tip.clone())
6843    }
6844
6845    // ------------------------------------------------------- operator fix
6846
6847    /// Route specific, already-recorded review findings to a fixer for a
6848    /// targeted, out-of-band fix on the winning branch — `magi fix`'s own
6849    /// entry point.
6850    ///
6851    /// Distinct from `review_loop`'s own fix step in three ways: it never
6852    /// runs a reviewer wave, it never spends review-round budget, and what
6853    /// happened is recorded as an [`OperatorFixRequest`] appended to
6854    /// [`RunState::operator_fixes`], never folded into a [`ReviewRound`] —
6855    /// see `run::SCHEMA`'s doc for schema 9 on why a reviewer's own severity
6856    /// and vote must never be rewritten to look like a manufactured blocking
6857    /// verdict.
6858    ///
6859    /// Only meaningful once review has actually concluded: `Ready` (handed
6860    /// off with findings still open, or simply concluded clean while minor
6861    /// findings sat unaddressed) or `Blocked` (round budget spent, or the
6862    /// gate failed). Everything else is refused: a run still in progress
6863    /// should simply be resumed, and a `Merged` run's branch has already
6864    /// landed — reopening *this* run's own record cannot change that, so the
6865    /// answer there is a fresh `magi review <branch>`.
6866    ///
6867    /// A real commit here re-verifies through a fresh, ordinary review-only
6868    /// run on the same branch ([`Self::review`]) rather than reopening this
6869    /// run's own `review_loop`: once any round in this run's history went
6870    /// clean, `review_conclusion` treats that as permanent by design (the
6871    /// same purity `gate`/`merge` rely on for safe reentry), so there is no
6872    /// way to force one more genuine reviewer wave out of *this* run without
6873    /// either rewriting history or weakening that guarantee for every other
6874    /// caller. A review-only run costs nothing extra — no implementation, no
6875    /// judging, no vote — and exercises the exact same review → verify →
6876    /// gate → (human) merge path, unmodified.
6877    pub async fn fix_selected(
6878        &mut self,
6879        ids: &[String],
6880        reason: &str,
6881        allow_stale: bool,
6882    ) -> Result<()> {
6883        let reason = reason.trim();
6884        if reason.is_empty() {
6885            bail!("a fix request needs a reason — that is the operator's own record of why");
6886        }
6887        if ids.is_empty() {
6888            bail!("no finding id given");
6889        }
6890        if !matches!(self.state.status, RunStatus::Ready | RunStatus::Blocked) {
6891            bail!(
6892                "run {} is `{}`; only a `ready` or `blocked` run — one whose review \
6893                 has already concluded — can be given a targeted fix. A run still \
6894                 in progress should simply be resumed; a `merged` run's branch has \
6895                 already landed, so its answer is a fresh `magi review <branch>`, \
6896                 not reopening this run's own record",
6897                self.state.id,
6898                self.state.status.as_str()
6899            );
6900        }
6901        // Reassignment shares this claim through its atomic task save. Check
6902        // the canonical run identity inside it, before preflight or any await.
6903        let _claim = FixClaim::acquire(&self.state.dir())?;
6904        crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &self.state.id)?;
6905        let home = crate::run::home();
6906        // The ordinary driver takes these same locks at admission. Keep the
6907        // execution lease through the fix, but never the owner lock across Git
6908        // or agent awaits.
6909        let execution = {
6910            let _owner = crate::pr_head::owner_lock(&home, &self.state.id)?;
6911            let disk = RunState::load(&self.state.id)?;
6912            crate::pr_head::ensure_owner(&disk)?;
6913            anyhow::ensure!(
6914                disk.status == self.state.status && disk.released_to.is_none(),
6915                "run changed since it was loaded; reload before fixing"
6916            );
6917            let claimed = crate::daemon::is_working_on(&home, &disk.id, Timestamp::now());
6918            anyhow::ensure!(
6919                disk.liveness_under(&home, claimed) == crate::run::Liveness::Dead,
6920                "run {} is currently being worked on or its ownership is unknown",
6921                disk.id
6922            );
6923            let lease = crate::driver::maintenance(&home, &disk.id).context(
6924                "run is currently being worked on or its execution lease is unavailable",
6925            )?;
6926            self.state = disk;
6927            lease
6928        };
6929        let Some(winner) = self.state.winner().cloned() else {
6930            bail!("run {} has no winning candidate to fix", self.state.id);
6931        };
6932        if !git::branch_exists(&self.state.repo, &winner.branch).await? {
6933            bail!(
6934                "branch `{}` no longer exists; this run cannot be extended",
6935                winner.branch
6936            );
6937        }
6938        // Resolve every id before spending anything — an unknown id refuses
6939        // the whole request rather than silently dropping it — and dedup
6940        // while keeping the operator's own order.
6941        let mut seen = BTreeSet::new();
6942        let mut findings = Vec::new();
6943        let mut missing = Vec::new();
6944        for id in ids {
6945            if !seen.insert(id.clone()) {
6946                continue;
6947            }
6948            match self.state.finding(id) {
6949                Some((round, rec, f)) => findings.push(OperatorFixFinding {
6950                    id: f.id.clone(),
6951                    severity: f.severity,
6952                    reviewer_vote: rec.vote,
6953                    round: round.round,
6954                    round_head: round.head.clone(),
6955                    reviewer: rec.reviewer,
6956                    agent: rec.agent.clone(),
6957                    file: f.file.clone(),
6958                    line: f.line,
6959                    title: f.title.clone(),
6960                    detail: f.detail.clone(),
6961                    outcome: OperatorFixOutcome::Pending,
6962                }),
6963                None => missing.push(id.clone()),
6964            }
6965        }
6966        if !missing.is_empty() {
6967            bail!(
6968                "unknown finding id(s): {}; nothing was changed",
6969                missing.join(", ")
6970            );
6971        }
6972
6973        let head_at_request = git::rev_parse(&self.state.repo, &winner.branch).await?;
6974        let stale_details: Vec<(String, String)> = findings
6975            .iter()
6976            .filter(|f| f.round_head != head_at_request)
6977            .map(|f| (f.id.clone(), f.round_head.clone()))
6978            .collect();
6979        let stale = !stale_details.is_empty();
6980        if stale && !allow_stale {
6981            bail!(
6982                "the branch has moved since some finding(s) were raised — {} — now \
6983                 at {}; pass --allow-stale to fix anyway, or re-run review first",
6984                stale_details
6985                    .iter()
6986                    .map(|(id, head)| format!("{id} (raised against {})", short(head)))
6987                    .collect::<Vec<_>>()
6988                    .join(", "),
6989                short(&head_at_request)
6990            );
6991        }
6992
6993        let request = OperatorFixRequest {
6994            requested_at: Timestamp::now(),
6995            reason: reason.to_owned(),
6996            findings,
6997            head_at_request: head_at_request.clone(),
6998            allow_stale,
6999            stale,
7000            fix: None,
7001            result_head: None,
7002            follow_up_review_run: None,
7003        };
7004        self.state.event(
7005            "fix",
7006            format!(
7007                "operator requested a targeted fix on {} finding(s) ({}): {reason}",
7008                request.findings.len(),
7009                request
7010                    .findings
7011                    .iter()
7012                    .map(|f| f.id.as_str())
7013                    .collect::<Vec<_>>()
7014                    .join(", "),
7015            ),
7016        );
7017        // Recorded now, before any worktree work or the fixer call itself —
7018        // and re-saved at each checkpoint below: a crash at any point after
7019        // this (mid fixer call, mid follow-up review) must not lose the fact
7020        // that this was requested, for which findings, and why. Everything
7021        // past this point reads and writes through `request_index` rather
7022        // than a local variable, since `request` itself is moved here.
7023        self.state.operator_fixes.push(request);
7024        self.state.save()?;
7025        let request_index = self.state.operator_fixes.len() - 1;
7026
7027        // A fresh, dedicated worktree for this one call, never the winner's
7028        // own worktree in place: that one may already be gone (folded away),
7029        // and reusing it in place would leave the branch checked out there
7030        // when the follow-up review below tries to check it out again. Freed
7031        // immediately after, either way — but only once confirmed clean:
7032        // `worktree_remove` is a `git worktree remove --force`, which would
7033        // otherwise discard uncommitted work left there by the operator or
7034        // another process before this had a chance to even look at it.
7035        let repo = self.state.repo.clone();
7036        let coordination = self.coordinate(&repo).await?;
7037        if winner.worktree.exists() {
7038            // Lockfiles a rescue commit withheld stay untracked on purpose and
7039            // are already recorded; they are not the operator's work to protect.
7040            let dirty = git::git(
7041                &winner.worktree,
7042                &["status", "--porcelain", "--untracked-files=all"],
7043            )
7044            .await?;
7045            let only_withheld = dirty.lines().all(|l| {
7046                l.strip_prefix("?? ")
7047                    .is_some_and(|p| self.state.withheld.iter().any(|w| w.path == p))
7048            });
7049            if !only_withheld {
7050                bail!(
7051                    "`{}` has uncommitted changes; refusing to touch it — commit or \
7052                     discard them first",
7053                    winner.worktree.display()
7054                );
7055            }
7056            git::worktree_remove(&self.state.repo, &winner.worktree)
7057                .await
7058                .ok();
7059        }
7060        let fix_worktree = self.state.worktree_root().join("operator-fix");
7061        let fix_worktree_s = fix_worktree.to_string_lossy().to_string();
7062        git::git(
7063            &self.state.repo,
7064            &["worktree", "add", &fix_worktree_s, winner.branch.as_str()],
7065        )
7066        .await
7067        .with_context(|| format!("checking out `{}` for the fix", winner.branch))?;
7068        if !git::is_clean(&fix_worktree).await? {
7069            git::worktree_remove(&self.state.repo, &fix_worktree)
7070                .await
7071                .ok();
7072            bail!(
7073                "`{}` has uncommitted changes; refusing to start a fix on a dirty tree",
7074                winner.branch
7075            );
7076        }
7077        let repo_for_setup = self.state.repo.clone();
7078        let setup = match ensure_setup_config(&mut self.state, &repo_for_setup).await {
7079            Ok(()) => {
7080                worktree_setup::prepare_with(
7081                    &self.state.config,
7082                    &repo_for_setup,
7083                    &fix_worktree,
7084                    crate::build_target::Coordination::Held(coordination.as_ref()),
7085                )
7086                .await
7087            }
7088            Err(e) => Err(e),
7089        };
7090        if let Err(e) = setup {
7091            git::worktree_remove(&self.state.repo, &fix_worktree)
7092                .await
7093                .ok();
7094            return Err(e);
7095        }
7096
7097        // This explicit operator request retries availability independently
7098        // of execute(); the previous call has already saved and cleaned up.
7099        self.state.resource_block = None;
7100
7101        let run_id = self.state.id.clone();
7102        let prompts = self.state.config.prompts.clone();
7103        let language = self.state.config.graph.language.clone();
7104        let sessions = self.state.config.graph.sessions;
7105        let artifacts = agent::artifacts_dir(&self.state.dir());
7106        let finding_list: Vec<Finding> = self.state.operator_fixes[request_index]
7107            .findings
7108            .iter()
7109            .map(|f| Finding {
7110                id: f.id.clone(),
7111                severity: f.severity,
7112                file: f.file.clone(),
7113                line: f.line,
7114                title: f.title.clone(),
7115                detail: f.detail.clone(),
7116            })
7117            .collect();
7118        let fix_prompt = prompt::operator_fix_in(
7119            &self.state.instruction,
7120            &finding_list,
7121            reason,
7122            &stale_details,
7123            &head_at_request,
7124            &language,
7125            &self.state.config.graph.github_language,
7126        );
7127        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
7128        drop(coordination);
7129        let (job, seat, out) = self
7130            .ask_fixer(&winner, "fix", None, |spec, seat| SeatJob {
7131                prompt: fix_prompt.clone(),
7132                spec,
7133                seat,
7134                cwd: fix_worktree.clone(),
7135                timeout,
7136                allow_write: true,
7137                sessions,
7138                artifacts: artifacts.clone(),
7139                stem: "operator-fix".to_owned(),
7140                handover: None,
7141            })
7142            .await;
7143        let agent_id = seat.agent.clone();
7144
7145        let mut fix = FixRecord {
7146            agent: agent_id,
7147            addressed: Vec::new(),
7148            rejected: Vec::new(),
7149            notes: String::new(),
7150            committed: false,
7151            failed: None,
7152            duration_ms: 0,
7153            continuation: None,
7154        };
7155        let mut final_seat = seat.clone();
7156        match out {
7157            AgentOutcome::Ok(o) => {
7158                fix.duration_ms = o.duration_ms;
7159                let parsed = verdict::extract_json::<FixReport>(&o.text);
7160                let incomplete_reason = match &parsed {
7161                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
7162                        "the reply parsed, but it reported a command whose own CLI \
7163                         never confirmed an exit status"
7164                            .to_owned(),
7165                    ),
7166                    Ok(_) => None,
7167                    Err(e) => Some(e.to_string()),
7168                };
7169                match incomplete_reason {
7170                    None => {
7171                        let report = parsed.expect("checked Ok above");
7172                        fix.addressed = report.addressed;
7173                        fix.rejected = report.rejected;
7174                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
7175                    }
7176                    Some(reason) => {
7177                        let (resumed_seat, resolved, failure, cont) = self
7178                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, 0)
7179                            .await;
7180                        fix.duration_ms += cont.cumulative_wait_ms;
7181                        fix.continuation = Some(cont);
7182                        final_seat = resumed_seat;
7183                        match resolved {
7184                            Some(report) => {
7185                                fix.addressed = report.addressed;
7186                                fix.rejected = report.rejected;
7187                                fix.notes =
7188                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
7189                            }
7190                            None => fix.failed = failure,
7191                        }
7192                    }
7193                }
7194            }
7195            AgentOutcome::Dropped(o) => {
7196                fix.duration_ms = o.duration_ms;
7197                let why = o
7198                    .dropped
7199                    .as_ref()
7200                    .map(|d| d.why.as_str())
7201                    .unwrap_or("the CLI ended the stream without delivering its answer");
7202                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
7203            }
7204            AgentOutcome::Quota(o) => {
7205                self.state.quota.push(QuotaLoss::from_report(
7206                    final_seat.key.clone(),
7207                    "fix",
7208                    o.quota.as_ref(),
7209                ));
7210                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
7211            }
7212            AgentOutcome::Failed(e) => fix.failed = Some(e),
7213            AgentOutcome::ResourceBlocked(e) => {
7214                fix.failed = Some(format!("the fixer was not started: {e}"));
7215            }
7216        }
7217        // Even a deferred call must rescue edits, release the worktree and
7218        // finalize its record below so an explicit `magi fix` can retry.
7219        if fix.continuation.is_none() {
7220            fix.continuation = Some(ContinuationRecord::not_needed());
7221        }
7222        self.state.seats.insert(final_seat.key.clone(), final_seat);
7223
7224        let rescue_message = format!(
7225            "magi: operator-selected fix ({}) (uncommitted work)",
7226            self.state.operator_fixes[request_index]
7227                .findings
7228                .iter()
7229                .map(|f| f.id.as_str())
7230                .collect::<Vec<_>>()
7231                .join(", ")
7232        );
7233        let repo = self.state.repo.clone();
7234        let coordination = self.coordinate(&repo).await?;
7235        if let Ok(r) = git::rescue_commit(&fix_worktree, &rescue_message).await {
7236            self.state.note_withheld("fix", &r.withheld);
7237        }
7238        let after = git::rev_parse(&fix_worktree, "HEAD").await?;
7239        fix.committed = after != head_at_request;
7240        git::worktree_remove(&self.state.repo, &fix_worktree)
7241            .await
7242            .ok();
7243        drop(coordination);
7244
7245        self.state.event(
7246            "fix",
7247            match &fix.failed {
7248                Some(reason) => format!(
7249                    "operator fix: adoption report was lost ({reason}); {}",
7250                    if fix.committed {
7251                        "committed"
7252                    } else {
7253                        "NO new commit"
7254                    }
7255                ),
7256                None => format!(
7257                    "operator fix: {} addressed, {} rejected, {}",
7258                    fix.addressed.len(),
7259                    fix.rejected.len(),
7260                    if fix.committed {
7261                        "committed"
7262                    } else {
7263                        "NO new commit"
7264                    }
7265                ),
7266            },
7267        );
7268
7269        // Every selected finding gets an outcome — never left `Pending` once
7270        // the fixer's own turn is over. A report that never came back at all
7271        // marks every one of them `Unreported`, not silently "not addressed":
7272        // quota, a dropped stream, or an exhausted continuation are gaps in
7273        // the report, not evidence about the finding itself (see [`SCHEMA`]'s
7274        // doc for schema 9 and [`OperatorFixOutcome::Unreported`]).
7275        for f in &mut self.state.operator_fixes[request_index].findings {
7276            f.outcome = if fix.failed.is_some() {
7277                OperatorFixOutcome::Unreported
7278            } else if fix.addressed.contains(&f.id) {
7279                OperatorFixOutcome::Addressed
7280            } else if let Some(r) = fix.rejected.iter().find(|r| r.id == f.id) {
7281                OperatorFixOutcome::Rejected { why: r.why.clone() }
7282            } else {
7283                OperatorFixOutcome::Unreported
7284            };
7285        }
7286
7287        let committed = fix.committed;
7288        if committed {
7289            self.state.operator_fixes[request_index].result_head = Some(after.clone());
7290        }
7291        self.state.operator_fixes[request_index].fix = Some(fix);
7292        // Saved again now that the fixer's own outcome is final, on top of
7293        // the save right after the request was first pushed above.
7294        self.state.save()?;
7295        if self.state.resource_block.is_some() {
7296            return self.stop_for_resource();
7297        }
7298
7299        if committed {
7300            self.state.event(
7301                "fix",
7302                format!(
7303                    "operator fix committed {}; opening a follow-up review-only run",
7304                    short(&after)
7305                ),
7306            );
7307            self.state.save()?;
7308            drop(execution);
7309            // The new review owns its own execution. Update only its audit link
7310            // afterwards, since publication may have changed the old record.
7311            let event_count = self.state.events.len();
7312            let save_follow_up = |state: &mut RunState| -> Result<()> {
7313                let _owner = crate::pr_head::owner_lock(&home, &state.id)?;
7314                let _execution = crate::driver::maintenance(&home, &state.id)?;
7315                let mut disk = RunState::load(&state.id)?;
7316                disk.events.extend(state.events.drain(event_count..));
7317                let follow_up = state.operator_fixes[request_index]
7318                    .follow_up_review_run
7319                    .clone();
7320                disk.operator_fixes[request_index].follow_up_review_run = follow_up;
7321                disk.save()?;
7322                *state = disk;
7323                Ok(())
7324            };
7325            // The operator asked for the fix, and the follow-up serves whatever
7326            // task the run it follows served.
7327            let origin =
7328                Origin::operator().serving(self.state.origin.as_ref().and_then(|o| o.task.clone()));
7329            match Self::review(
7330                &self.state.repo,
7331                &winner.branch,
7332                self.state.config.clone(),
7333                origin,
7334            )
7335            .await
7336            {
7337                Ok(mut follow_up) => {
7338                    follow_up.state.event(
7339                        "start",
7340                        format!(
7341                            "requested by an operator fix on run {} for finding(s) {}",
7342                            self.state.id,
7343                            self.state.operator_fixes[request_index]
7344                                .findings
7345                                .iter()
7346                                .map(|f| f.id.as_str())
7347                                .collect::<Vec<_>>()
7348                                .join(", "),
7349                        ),
7350                    );
7351                    follow_up.state.save()?;
7352                    let follow_up_id = follow_up.state.id.clone();
7353                    // The follow-up is a run like any other: it belongs to the
7354                    // task of the run it follows, or to one filed for it.
7355                    let adopted = match crate::direct::adopt(
7356                        &follow_up.state,
7357                        self.state.origin.as_ref().and_then(|o| o.task.as_deref()),
7358                    ) {
7359                        Ok(a) => a,
7360                        Err(e) => {
7361                            // An ownerless run must not spend agent calls; it
7362                            // stays saved, and `magi run --resume` adopts it.
7363                            self.state.event(
7364                                "fix",
7365                                format!(
7366                                    "follow-up review {follow_up_id} got no owning task and was not executed: {e:#}"
7367                                ),
7368                            );
7369                            save_follow_up(&mut self.state)?;
7370                            return Ok(());
7371                        }
7372                    };
7373                    let executed = follow_up.execute().await;
7374                    let failure = executed.as_ref().err().map(|e| format!("{e:#}"));
7375                    if let Some(a) = adopted {
7376                        a.finish(&follow_up.state, executed);
7377                    }
7378                    if let Some(e) = failure {
7379                        self.state.event(
7380                            "fix",
7381                            format!(
7382                                "follow-up review {follow_up_id} did not complete cleanly: {e:#}"
7383                            ),
7384                        );
7385                    }
7386                    self.state.operator_fixes[request_index].follow_up_review_run =
7387                        Some(follow_up_id);
7388                }
7389                Err(e) => {
7390                    self.state.event(
7391                        "fix",
7392                        format!("committed the fix but could not open a follow-up review: {e:#}"),
7393                    );
7394                }
7395            }
7396            save_follow_up(&mut self.state)?;
7397        }
7398
7399        Ok(())
7400    }
7401
7402    // --------------------------------------------------------------- review
7403
7404    /// Ask the fixer chain once for one fix call: the agents [`fixer::attempts`]
7405    /// names, in order, each at most once, moving on only when the call
7406    /// advances (an error, a quota hit or nothing usable - the same decision
7407    /// point `agent::chain_advances` is for the other chained roles).
7408    ///
7409    /// Each agent gets its own seat from `Runner::seat`: the same agent
7410    /// continues its conversation (the winner's own implementer seat when it
7411    /// is the winner's author, now that the competition is over), another
7412    /// takes a fresh one so the full prompt is sent again. A handover is
7413    /// recorded under `node`, which is what makes the fallback stick for the
7414    /// rest of the run (see `crate::fixer`). Only the last attempt's outcome
7415    /// is returned, so an exhausted chain reads exactly like a single failed
7416    /// fixer: one quota loss, the same wording, the same refund. An earlier
7417    /// attempt's edits are left in the tree and judged, with the final
7418    /// attempt's, by what git says afterwards.
7419    ///
7420    /// Returns the job that produced the outcome, for `continue_fix_report`.
7421    async fn ask_fixer(
7422        &mut self,
7423        winner: &Candidate,
7424        node: &'static str,
7425        round: Option<usize>,
7426        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
7427    ) -> (SeatJob, SeatState, AgentOutcome) {
7428        let attempts = fixer::attempts(&self.state, &self.roles, winner);
7429        self.ask_fixer_among(attempts, node, round, None, build)
7430            .await
7431    }
7432
7433    /// [`Self::ask_fixer`] over an explicit attempt list. `restore` is a
7434    /// worktree and a commit: before the next agent is asked after one that
7435    /// did not satisfy the call, the worktree is put back on that commit, so
7436    /// a failed agent's partial edits are not carried into the next one.
7437    async fn ask_fixer_among(
7438        &mut self,
7439        attempts: Vec<(AgentSpec, String)>,
7440        node: &'static str,
7441        round: Option<usize>,
7442        restore: Option<(&Path, &str)>,
7443        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
7444    ) -> (SeatJob, SeatState, AgentOutcome) {
7445        let run_id = self.state.id.clone();
7446        let prompts = self.state.config.prompts.clone();
7447        let cache = self.state.config.cache_dir();
7448        let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
7449        let mut last = None;
7450        for (i, (spec, key)) in attempts.into_iter().enumerate() {
7451            let seat = self.seat(&key, &spec.id);
7452            let mut job = build(spec.clone(), seat);
7453            if i > 0 {
7454                job.stem = format!("{}-{}", job.stem, spec.id);
7455            }
7456            let ctx = WaveCtx {
7457                carry_seats: false,
7458                pauses: Some((&self.pause, &self.interrupt)),
7459                run: &run_id,
7460                node,
7461                prompts: &prompts,
7462                cache: cache.as_deref(),
7463                round,
7464            };
7465            let (seat, out) =
7466                run_one(job.clone(), Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
7467            // A resource block never advances the chain: the chosen agent
7468            // was not asked, so it must be the one asked again on resume.
7469            let advances = match &out {
7470                AgentOutcome::Ok(o) => agent::output_advances(o),
7471                AgentOutcome::ResourceBlocked(_) => false,
7472                _ => true,
7473            };
7474            if let Some(next) = ids.get(i + 1)
7475                && advances
7476            {
7477                self.state.seats.insert(seat.key.clone(), seat.clone());
7478                let class =
7479                    FailClass::of(&out).unwrap_or_else(|| FailClass::Other("unusable".to_owned()));
7480                let reason = match &out {
7481                    AgentOutcome::Ok(_) => "nothing usable".to_owned(),
7482                    other => fail_reason(other),
7483                };
7484                // A failed agent's edits must not reach the next one, and a
7485                // restore that did not work ends the chain: the call fails
7486                // and the caller's own (confirmed) restore decides.
7487                if let Some((wt, rev)) = restore
7488                    && let Err(e) = self.graft_restore(wt, rev).await
7489                {
7490                    let why =
7491                        format!("could not restore the worktree before the next fixer: {e:#}");
7492                    tracing::warn!("{why}");
7493                    let out = if e.is::<crate::repo_lock::ResourceBlocked>() {
7494                        AgentOutcome::ResourceBlocked(why)
7495                    } else {
7496                        AgentOutcome::Failed(why)
7497                    };
7498                    last = Some((job, seat, out));
7499                    break;
7500                }
7501                record_handover(
7502                    &mut self.state,
7503                    node,
7504                    &seat.key,
7505                    &spec.id,
7506                    next,
7507                    &class,
7508                    &reason,
7509                );
7510                continue;
7511            }
7512            last = Some((job, seat, out));
7513            break;
7514        }
7515        let (job, seat, out) = last.expect("the fixer chain always has an entry");
7516        if let AgentOutcome::Quota(output) = &out
7517            && node != "graft"
7518        {
7519            // Graft is best effort: its caller records the loss and restores
7520            // the pre-graft tree, then proceeds to review and gate.
7521            // Every fallback was tried. Machine outages cannot be repaired by
7522            // spending a fix round; use each caller's resumable resource path.
7523            let loss = QuotaLoss::from_report(seat.key.clone(), node, output.quota.as_ref());
7524            block_machine_outage(&mut self.state, node, std::slice::from_ref(&loss));
7525            self.state.quota.push(loss);
7526            self.state.seats.insert(seat.key.clone(), seat.clone());
7527            self.state.status = RunStatus::Blocked;
7528            return (
7529                job,
7530                seat,
7531                AgentOutcome::ResourceBlocked(
7532                    "fixer unavailable; restore agent availability and resume".into(),
7533                ),
7534            );
7535        }
7536        (job, seat, out)
7537    }
7538
7539    /// The one repair a verification-only failure earns (see
7540    /// [`crate::recovery`]), before the first review round of a run that took
7541    /// a branch over.
7542    ///
7543    /// Saved as started *before* the fixer is called, so a resume never
7544    /// repairs twice; a start found on re-entry is rolled back to the commit
7545    /// it began from. A failed or unusable fixer leaves the tree as it was and
7546    /// the review goes on over it, so the first round's own verification
7547    /// reports the failure again. The failure is never carried into a round as
7548    /// a result: verification is re-run on whatever commit this leaves.
7549    async fn recovery_repair(&mut self, winner: &Candidate) -> Result<()> {
7550        use crate::recovery::{Mode, Repair};
7551        if !self.state.reviews.is_empty() {
7552            return Ok(());
7553        }
7554        let Some(mut rec) = self.state.recovery.clone() else {
7555            return Ok(());
7556        };
7557        if rec.mode != Mode::VerifyRepair {
7558            return Ok(());
7559        }
7560        let wt = winner.worktree.clone();
7561        let mut head = git::rev_parse(&wt, "HEAD").await?;
7562        match rec.repair.clone() {
7563            Repair::Done { .. } => return Ok(()),
7564            Repair::WaitingForRestore { before } => {
7565                self.graft_restore(&wt, &before).await?;
7566                head = before;
7567                rec.repair = Repair::NotStarted;
7568                self.state.recovery = Some(rec.clone());
7569                self.state.save()?;
7570            }
7571            Repair::Started { before } => {
7572                // Interrupted: the unfinished edits are not trusted.
7573                // An unconfirmed rollback blocks the run with `Started` kept,
7574                // so a resume retries it; the tree is never reviewed as is.
7575                if let Err(e) = self.graft_restore(&wt, &before).await {
7576                    if e.is::<crate::repo_lock::ResourceBlocked>() {
7577                        return Err(e);
7578                    }
7579                    return self
7580                        .stop_recovery(rec, &before, format!("interrupted; rollback failed: {e:#}"))
7581                        .await;
7582                }
7583                rec.repair = Repair::Done {
7584                    before: before.clone(),
7585                    after: before,
7586                    committed: false,
7587                    failed: Some("interrupted; rolled back".to_owned()),
7588                };
7589                self.state
7590                    .event("recovery", "the repair was interrupted and rolled back");
7591                self.state.recovery = Some(rec);
7592                self.state.save()?;
7593                return Ok(());
7594            }
7595            Repair::NotStarted => {}
7596        }
7597        if crate::recovery::recheck(&mut rec, &head) {
7598            self.state.event("recovery", rec.summary());
7599            self.state.recovery = Some(rec);
7600            self.state.save()?;
7601            return Ok(());
7602        }
7603        rec.repair = Repair::Started {
7604            before: head.clone(),
7605        };
7606        self.state.recovery = Some(rec.clone());
7607        self.state.save()?;
7608
7609        let language = self.state.config.graph.language.clone();
7610        let sessions = self.state.config.graph.sessions;
7611        let artifacts = agent::artifacts_dir(&self.state.dir());
7612        let fix_prompt = prompt::recovery_fix(
7613            &self.state.instruction,
7614            &rec,
7615            self.state.config.graph.review_rounds,
7616            &language,
7617        );
7618        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
7619        self.state.event(
7620            "recovery",
7621            format!(
7622                "repair: the fixer starts from the failed verification on {}",
7623                short(&head)
7624            ),
7625        );
7626        let (_job, seat, out) = self
7627            .ask_fixer(winner, "fix", None, |spec, seat| SeatJob {
7628                prompt: fix_prompt.clone(),
7629                spec,
7630                seat,
7631                cwd: wt.clone(),
7632                timeout,
7633                allow_write: true,
7634                sessions,
7635                artifacts: artifacts.clone(),
7636                stem: "fix-recovery".to_owned(),
7637                handover: None,
7638            })
7639            .await;
7640        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
7641            rec.repair = Repair::WaitingForRestore { before: head };
7642            self.state.recovery = Some(rec);
7643            return self.stop_for_resource();
7644        }
7645        let failed = match &out {
7646            AgentOutcome::Ok(_) | AgentOutcome::ResourceBlocked(_) => None,
7647            AgentOutcome::Quota(o) => {
7648                self.state.quota.push(QuotaLoss::from_report(
7649                    seat.key.clone(),
7650                    "fix",
7651                    o.quota.as_ref(),
7652                ));
7653                Some("rate limited (quota); the fixer could not run".to_owned())
7654            }
7655            AgentOutcome::Dropped(_) => Some("the CLI dropped the stream".to_owned()),
7656            AgentOutcome::Failed(e) => Some(e.clone()),
7657        };
7658        self.state.seats.insert(seat.key.clone(), seat);
7659        let coordination = self.coordinate(&wt).await?;
7660        let failed = match failed {
7661            // The agent's partial edits are not kept.
7662            Some(why) => {
7663                if let Err(e) = git::restore_to(&wt, &head).await {
7664                    return self
7665                        .stop_recovery(rec, &head, format!("{why}; restore failed: {e:#}"))
7666                        .await;
7667                }
7668                Some(why)
7669            }
7670            None => {
7671                if let Ok(r) = git::rescue_commit(
7672                    &wt,
7673                    "magi: recovery repair of the failed verification (uncommitted work)",
7674                )
7675                .await
7676                {
7677                    self.state.note_withheld("fix", &r.withheld);
7678                }
7679                None
7680            }
7681        };
7682        let after = git::rev_parse(&wt, "HEAD").await?;
7683        drop(coordination);
7684        self.state.event(
7685            "recovery",
7686            match &failed {
7687                Some(why) => format!("repair: nothing kept ({why})"),
7688                None if after != head => {
7689                    format!("repair: committed {}", short(&after))
7690                }
7691                None => "repair: the fixer made no commit".to_owned(),
7692            },
7693        );
7694        rec.repair = Repair::Done {
7695            before: head.clone(),
7696            committed: after != head,
7697            after,
7698            failed,
7699        };
7700        self.state.recovery = Some(rec);
7701        self.state.save()?;
7702        Ok(())
7703    }
7704
7705    /// A repair whose rollback could not be confirmed: the run is blocked and
7706    /// resumable, and the unconfirmed state is never reviewed.
7707    async fn stop_recovery(
7708        &mut self,
7709        mut rec: crate::recovery::RecoveryRecord,
7710        head: &str,
7711        why: String,
7712    ) -> Result<()> {
7713        // `Started` stays recorded: a resume retries the restore.
7714        rec.repair = crate::recovery::Repair::Started {
7715            before: head.to_owned(),
7716        };
7717        self.state.recovery = Some(rec);
7718        self.state
7719            .event("recovery", format!("repair could not be undone: {why}"));
7720        self.state.status = RunStatus::Blocked;
7721        self.state.save()?;
7722        bail!("recovery repair could not be rolled back: {why}")
7723    }
7724
7725    async fn review_loop(&mut self) -> Result<()> {
7726        if self.hold_base_sync().await? {
7727            return Ok(());
7728        }
7729        loop {
7730            if self
7731                .state
7732                .base_sync
7733                .as_ref()
7734                .is_some_and(|s| s.conflict.is_some())
7735            {
7736                return Ok(());
7737            }
7738            if self.catchup_repairable() {
7739                let record = self.state.reviews.last().expect("repairable round").clone();
7740                let winner = self
7741                    .state
7742                    .winner()
7743                    .cloned()
7744                    .context("catch-up repair has no winner")?;
7745                if !self.fix_review_round(&winner, record).await? {
7746                    return Ok(());
7747                }
7748            }
7749            self.review_loop_pass().await?;
7750            if !self.catchup_repairable() {
7751                return Ok(());
7752            }
7753        }
7754    }
7755
7756    /// Derive an owed catch-up repair from durable round evidence, including
7757    /// reentry after a crash before the fixer was dispatched.
7758    fn catchup_repairable(&self) -> bool {
7759        self.state.reviews.len() < self.state.config.graph.review_rounds
7760            && self.state.reviews.last().is_some_and(|r| {
7761                !r.clean
7762                    && r.blocking == 0
7763                    && r.fix.is_none()
7764                    && r.e2e_status() == E2eStatus::Failed
7765            })
7766    }
7767
7768    async fn review_loop_pass(&mut self) -> Result<()> {
7769        // A base that would not rebase is a person's decision, not a review
7770        // round: nothing here would change the answer, and reviewers and a
7771        // fixer would be spending real budget on a tree that cannot land
7772        // regardless of what they find.
7773        if self
7774            .state
7775            .base_sync
7776            .as_ref()
7777            .is_some_and(|s| s.conflict.is_some())
7778        {
7779            return Ok(());
7780        }
7781        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
7782        // agent files with `magi task add` name the run that paid for it. The
7783        // prompt overlay is cloned alongside it because the waves borrow it
7784        // while `self` is mutably borrowed by the node's own bookkeeping.
7785        let run_id = self.state.id.clone();
7786        let prompts = self.state.config.prompts.clone();
7787        let Some(winner) = self.state.winner().cloned() else {
7788            return Ok(());
7789        };
7790        let granted_review = self
7791            .state
7792            .repair_grants
7793            .last()
7794            .filter(|g| g.phase == crate::repair_budget::Phase::Reviewing)
7795            .cloned();
7796        let fresh_review = granted_review
7797            .as_ref()
7798            .is_some_and(|g| self.state.reviews.len() == g.review_start);
7799        let max_rounds = granted_review
7800            .as_ref()
7801            .map_or(self.state.config.graph.review_rounds, |g| {
7802                g.review_start.saturating_add(1)
7803            });
7804        // A clean round, an exhausted round budget, or a stalled tree (see
7805        // `STAGNANT_LIMIT`) are all already-decided conclusions the moment
7806        // they are recorded — recomputed here, not read off `status`, so a
7807        // reentry into a run that already stopped restates the identical
7808        // verdict instead of silently handing back whatever an earlier node
7809        // in this same walk clobbered `status` to (a solo-candidate
7810        // `judge`/`deliberate` skip rewrites it on every reentry). The loop
7811        // below runs an empty range once the budget is spent, and would
7812        // otherwise fall through without touching `status` at all.
7813        if let Some(status) =
7814            review_conclusion(&self.state.reviews, max_rounds).filter(|_| !fresh_review)
7815        {
7816            // A reentry after a crash between the last round's save and
7817            // `stop_reviewing` reaches the hand-off here, not there.
7818            if status == RunStatus::Gating {
7819                self.record_contested_handoff();
7820            }
7821            self.state.status = status;
7822            self.state.save()?;
7823            return Ok(());
7824        }
7825        self.state.status = RunStatus::Reviewing;
7826        // A last recorded round whose own verification never resolved
7827        // (`ResourceBlocked` — the shared build cache, not the patch) is
7828        // never a concluded round, whatever the round budget says: starting
7829        // a fresh round on top of it would spend a whole new reviewer wave
7830        // re-reading an unchanged patch instead of just retrying the one
7831        // check that actually needs it, and once the budget is spent the
7832        // loop below has nothing left to do at all (its range is empty).
7833        // Retry that check directly instead, exactly the same retry
7834        // `stop_reviewing` already does for its own catch-up case.
7835        if !fresh_review
7836            && self.state.reviews.last().is_some_and(|r| {
7837                r.e2e_status() == E2eStatus::ResourceBlocked
7838                    || (r.e2e_status() == E2eStatus::Deferred && r.blocking == 0 && r.fix.is_none())
7839            })
7840        {
7841            let shell = self.state.config.shell();
7842            return self
7843                .stop_unresolved_review(
7844                    "the last round's own verification never resolved",
7845                    &shell,
7846                    &winner.worktree,
7847                )
7848                .await;
7849        }
7850
7851        if granted_review.is_none() {
7852            self.recovery_repair(&winner).await?;
7853        }
7854        if self.resource_halt()? {
7855            return Ok(());
7856        }
7857
7858        let repo = self.state.repo.clone();
7859        let root = self.state.worktree_root();
7860        let language = self.state.config.graph.language.clone();
7861        let sessions = self.state.config.graph.sessions;
7862        let artifacts = self.merge_repair_artifacts();
7863        let base = self.landing_base();
7864        let base_short = short(&base);
7865        let reviewers = self.roles.reviewers.clone();
7866        let shell = self.state.config.shell();
7867
7868        for round in (self.state.reviews.len() + 1)..=max_rounds {
7869            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
7870            let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
7871            let stat = git::diff_stat(&winner.worktree, &base, "HEAD").await?;
7872            // The prior round's own record, already persisted — never a
7873            // hand-carried variable of just its failing output: that is
7874            // exactly what let a round's e2e result drift out of sync with
7875            // which commit it was actually about (see `SCHEMA`'s doc for
7876            // schema 8). Judged against `head`, the commit reviewers are
7877            // about to look at now, so the summary always reads as "an
7878            // earlier head" here — this round's own patch has not been
7879            // checked yet.
7880            let prev_verification = self
7881                .state
7882                .reviews
7883                .last()
7884                .and_then(|r| r.verification_summary(&head));
7885            // Only the first round of a run that took a branch over: later
7886            // rounds have this run's own history.
7887            let prior_section = match (&self.state.recovery, round) {
7888                (Some(rec), 1) if self.state.reviews.is_empty() => {
7889                    let since = match (rec.mode, rec.reviewed_head.as_deref()) {
7890                        (crate::recovery::Mode::VerifyRepair, Some(reviewed)) => {
7891                            Some(crate::recovery::head_of(
7892                                &git::diff(&winner.worktree, reviewed, "HEAD")
7893                                    .await
7894                                    .unwrap_or_default(),
7895                                crate::recovery::SINCE_DIFF_MAX,
7896                            ))
7897                        }
7898                        _ => None,
7899                    };
7900                    Some(prompt::recovery_review(rec, since.as_deref()))
7901                }
7902                _ => None,
7903            };
7904
7905            // Each reviewer gets its own detached checkout of exactly this
7906            // commit: nobody can perturb the winner's tree, and the fixer can
7907            // keep working without racing a reviewer.
7908            let mut jobs = Vec::new();
7909            let coordination = if self.state.config.worktree.pre_clean.is_empty() {
7910                self.coordinate(&repo).await?
7911            } else {
7912                None
7913            };
7914            for (r, spec) in reviewers.iter().cloned().enumerate() {
7915                let wt = root.join(format!("review-{}", r + 1));
7916                // `clean -fdx` in a reset wipes setup's products, so every
7917                // round sets the seat up again.
7918                if wt.exists() {
7919                    crate::worktree_clean::reset(&mut self.state, &wt, Some(&head)).await?;
7920                } else {
7921                    let _lease = if self.state.config.worktree.pre_clean.is_empty() {
7922                        None
7923                    } else {
7924                        self.coordinate(&repo).await?
7925                    };
7926                    git::worktree_add_detached(&repo, &wt, &head).await?;
7927                }
7928                let _setup_lease = if self.state.config.worktree.pre_clean.is_empty() {
7929                    None
7930                } else {
7931                    self.coordinate(&repo).await?
7932                };
7933                self.setup_seat_worktree(
7934                    &repo,
7935                    &wt,
7936                    false,
7937                    coordination.as_ref().or(_setup_lease.as_ref()),
7938                )
7939                .await?;
7940                let seat_key = format!("review-{}", r + 1);
7941                // The seat starts the round on whoever answered it last, not
7942                // on the agent the spec names, so a failure is not re-paid.
7943                let spec = pick_start_spec(
7944                    &self.roles.reviewer_roster,
7945                    spec,
7946                    self.state.seat_history.get(&seat_key),
7947                );
7948                let seat = self.seat(&seat_key, &spec.id);
7949                jobs.push(SeatJob {
7950                    prompt: prompt::review(&prompt::ReviewCtx {
7951                        instruction: &self.state.instruction,
7952                        branch: &winner.branch,
7953                        base_short: &base_short,
7954                        stat: &stat,
7955                        patch: &patch,
7956                        verification: prev_verification.as_ref(),
7957                        prior: prior_section.as_deref(),
7958                        reviewers: reviewers.len(),
7959                        round,
7960                        rounds: max_rounds,
7961                        // A review-only run has no rankings, so nothing
7962                        // competed for this patch and the reviewer is told so.
7963                        competed: self.state.tally.as_ref().is_some_and(|t| t.rankings > 0),
7964                        lens: Lens::for_seat(r),
7965                        language: &language,
7966                        github_language: &self.state.config.graph.github_language,
7967                    }),
7968                    spec,
7969                    seat,
7970                    cwd: wt,
7971                    timeout: Duration::from_secs(self.state.config.graph.timeout_review),
7972                    allow_write: false,
7973                    sessions,
7974                    artifacts: artifacts.clone(),
7975                    stem: format!("review-{round}-{}", r + 1),
7976                    handover: None,
7977                });
7978            }
7979
7980            drop(coordination);
7981            self.state.event(
7982                "review",
7983                format!(
7984                    "round {round}: {} reviewers on {}",
7985                    jobs.len(),
7986                    short(&head)
7987                ),
7988            );
7989            let mut quota_losses = Vec::new();
7990            let review_retries = self.state.config.graph.retries;
7991            let review_cache = self.state.config.cache_dir();
7992            let ctx = WaveCtx {
7993                carry_seats: true,
7994                pauses: Some((&self.pause, &self.interrupt)),
7995                run: &run_id,
7996                node: "review",
7997                prompts: &prompts,
7998                cache: review_cache.as_deref(),
7999                round: Some(round),
8000            };
8001            let results = ask_json_wave::<Review>(
8002                jobs,
8003                Arc::clone(&self.sem),
8004                review_retries,
8005                &self.roles.reviewer_roster,
8006                &ctx,
8007                &mut quota_losses,
8008                &mut self.state,
8009                &|_: &Review| Ok(()),
8010            )
8011            .await;
8012            if self.state.resource_block.is_some() {
8013                return self.stop_for_resource();
8014            }
8015            // Counted before the move below: how many of *this* round's
8016            // reviewer seats were lost to their own rate limit, as opposed to
8017            // a crash, a timeout, or unparsable output — see `round_is_clean`.
8018            let round_quota_missing = quota_losses.len();
8019            self.state.quota.extend(quota_losses);
8020
8021            let mut records = Vec::new();
8022            let mut all_findings = Vec::new();
8023            for (r, (seat, res, attempts)) in results.into_iter().enumerate() {
8024                let agent_id = seat.agent.clone();
8025                self.state.seats.insert(seat.key.clone(), seat);
8026                let mut record = ReviewRecord {
8027                    reviewer: r + 1,
8028                    agent: agent_id,
8029                    summary: String::new(),
8030                    findings: Vec::new(),
8031                    vote: None,
8032                    failed: None,
8033                    duration_ms: 0,
8034                    // Set for both outcomes: `failed: Some(_)` with
8035                    // `attempts > 0` is a seat every retry still lost, not a
8036                    // recovered one — only `failed: None` with `attempts > 0`
8037                    // reads as "answered after a nudge" (see this field's own
8038                    // doc).
8039                    attempts,
8040                };
8041                match res {
8042                    Ok((review, out)) => {
8043                        // Sanitized here, at the point every other piece of
8044                        // agent prose in this file is (candidate summaries,
8045                        // deliberation turns, vote reasons): a reviewer's own
8046                        // words are the one thing about it that could name
8047                        // it, and reconsideration below broadcasts this same
8048                        // summary and these same findings to every other
8049                        // seat on the panel.
8050                        record.summary =
8051                            blind::sanitize_prose(&review.summary, &self.state.config.blind);
8052                        record.vote = Some(review.vote);
8053                        record.duration_ms = out.duration_ms;
8054                        for (n, mut f) in review.findings.into_iter().enumerate() {
8055                            // ids are magi's, never the agent's: the fixer's
8056                            // adoption report is keyed by them.
8057                            f.id = format!("R{round}-{}-{}", r + 1, n + 1);
8058                            f.title = blind::sanitize_prose(&f.title, &self.state.config.blind);
8059                            f.detail = blind::sanitize_prose(&f.detail, &self.state.config.blind);
8060                            // `file` is agent-supplied prose too, never
8061                            // checked against the real tree — the same
8062                            // exposure `title`/`detail` above have, just in
8063                            // a field easy to forget because it looks like a
8064                            // path rather than free text.
8065                            f.file = f
8066                                .file
8067                                .map(|file| blind::sanitize_prose(&file, &self.state.config.blind));
8068                            all_findings.push(f.clone());
8069                            record.findings.push(f);
8070                        }
8071                        self.state.event(
8072                            "review",
8073                            format!(
8074                                "round {round}: reviewer {} voted {} with {} finding(s)",
8075                                r + 1,
8076                                review.vote.label(),
8077                                record.findings.len()
8078                            ),
8079                        );
8080                    }
8081                    Err(e) => {
8082                        record.failed = Some(e.to_string());
8083                        self.state.event(
8084                            "review",
8085                            format!("round {round}: reviewer {} produced nothing: {e}", r + 1),
8086                        );
8087                    }
8088                }
8089                records.push(record);
8090            }
8091
8092            // Tally the round's votes and, if they split, spend the one
8093            // round of reconsideration the split -> deliberate -> revote
8094            // shape `judge`/`vote` use for the panel, sized down to what a
8095            // read-only review round can afford: one round, and a revote
8096            // rather than an argument, because the panel already wrote its
8097            // reasoning down as findings the first time around.
8098            let initial_votes: Vec<ReviewVote> = records.iter().filter_map(|r| r.vote).collect();
8099            let vote_split =
8100                initial_votes.len() > 1 && !initial_votes.iter().all(|v| *v == initial_votes[0]);
8101            let mut reconsideration: Vec<ReviewRevoteRecord> = Vec::new();
8102            if vote_split {
8103                self.state.event(
8104                    "review",
8105                    format!(
8106                        "round {round}: votes split ({}) — one round of reconsideration",
8107                        initial_votes
8108                            .iter()
8109                            .map(|v| v.label())
8110                            .collect::<Vec<_>>()
8111                            .join(", ")
8112                    ),
8113                );
8114                // Seats read every seat's findings and votes, still numbered
8115                // and never named — the same anonymity `review` itself keeps.
8116                let panel: Vec<ReviewSeatReport<'_>> = records
8117                    .iter()
8118                    .filter_map(|r| {
8119                        r.vote.map(|vote| ReviewSeatReport {
8120                            reviewer: r.reviewer,
8121                            vote,
8122                            summary: &r.summary,
8123                            findings: &r.findings,
8124                        })
8125                    })
8126                    .collect();
8127
8128                let mut jobs = Vec::new();
8129                let mut seats_at = Vec::new();
8130                for (r, spec) in reviewers.iter().cloned().enumerate() {
8131                    // A seat with no initial vote has nothing to reconsider
8132                    // from and stays absent, the same as it stayed absent
8133                    // from `panel` above.
8134                    if records[r].vote.is_none() {
8135                        continue;
8136                    }
8137                    let wt = root.join(format!("review-{}", r + 1));
8138                    let seat_key = format!("review-{}", r + 1);
8139                    let spec = self.occupant(&seat_key, spec);
8140                    let seat = self.seat(&seat_key, &spec.id);
8141                    // A seat with no live session has already forgotten the
8142                    // initial review's prompt — restate the patch it is
8143                    // voting on, the same as `deliberate`/`vote` do for a
8144                    // judge in the same position.
8145                    // The panel already carries this seat's own review and
8146                    // vote, so restating the patch makes the prompt whole for
8147                    // a seat handed to another agent.
8148                    let build = |with_patch: bool| {
8149                        prompt::review_reconsider(&ReviewReconsiderCtx {
8150                            instruction: &self.state.instruction,
8151                            reviewer: r + 1,
8152                            lens: Lens::for_seat(r),
8153                            panel: &panel,
8154                            patch: with_patch.then_some(ReviewPatch {
8155                                branch: &winner.branch,
8156                                base_short: &base_short,
8157                                stat: &stat,
8158                                patch: &patch,
8159                            }),
8160                            round,
8161                            rounds: max_rounds,
8162                            language: &language,
8163                        })
8164                    };
8165                    let full = build(true);
8166                    let prompt = if has_context(&spec, &seat, sessions) {
8167                        build(false)
8168                    } else {
8169                        full.clone()
8170                    };
8171                    jobs.push(SeatJob {
8172                        prompt,
8173                        spec,
8174                        seat,
8175                        cwd: wt,
8176                        timeout: Duration::from_secs(self.state.config.graph.timeout_review),
8177                        allow_write: false,
8178                        sessions,
8179                        artifacts: artifacts.clone(),
8180                        stem: format!("review-{round}-reconsider-{}", r + 1),
8181                        handover: Some(full),
8182                    });
8183                    seats_at.push(r);
8184                }
8185
8186                let mut recon_quota_losses = Vec::new();
8187                let recon_cache = self.state.config.cache_dir();
8188                let recon_ctx = WaveCtx {
8189                    carry_seats: true,
8190                    pauses: Some((&self.pause, &self.interrupt)),
8191                    run: &run_id,
8192                    node: "review",
8193                    prompts: &prompts,
8194                    cache: recon_cache.as_deref(),
8195                    round: Some(round),
8196                };
8197                let recon_results = ask_json_wave::<ReviewRevote>(
8198                    jobs,
8199                    Arc::clone(&self.sem),
8200                    review_retries,
8201                    &self.roles.reviewer_roster,
8202                    &recon_ctx,
8203                    &mut recon_quota_losses,
8204                    &mut self.state,
8205                    &|_: &ReviewRevote| Ok(()),
8206                )
8207                .await;
8208                if self.state.resource_block.is_some() {
8209                    return self.stop_for_resource();
8210                }
8211                self.state.quota.extend(recon_quota_losses);
8212
8213                for (&r, (seat, res, _attempts)) in seats_at.iter().zip(recon_results) {
8214                    let agent_id = seat.agent.clone();
8215                    self.state.seats.insert(seat.key.clone(), seat);
8216                    let mut rec = ReviewRevoteRecord {
8217                        reviewer: r + 1,
8218                        agent: agent_id,
8219                        vote: None,
8220                        reason: String::new(),
8221                        failed: None,
8222                    };
8223                    match res {
8224                        Ok((rv, _)) => {
8225                            rec.vote = Some(rv.vote);
8226                            rec.reason =
8227                                blind::sanitize_prose(&rv.reason, &self.state.config.blind);
8228                            self.state.event(
8229                                "review",
8230                                format!(
8231                                    "round {round}: reviewer {} revoted {}",
8232                                    r + 1,
8233                                    rv.vote.label()
8234                                ),
8235                            );
8236                        }
8237                        Err(e) => {
8238                            rec.failed = Some(e.to_string());
8239                            self.state.event(
8240                                "review",
8241                                format!("round {round}: reviewer {} did not revote: {e}", r + 1),
8242                            );
8243                        }
8244                    }
8245                    reconsideration.push(rec);
8246                }
8247            } else if initial_votes.len() > 1 {
8248                self.state.event(
8249                    "review",
8250                    format!(
8251                        "round {round}: votes agreed ({}) — no reconsideration",
8252                        initial_votes[0].label()
8253                    ),
8254                );
8255            }
8256
8257            let blocking = all_findings.iter().filter(|f| f.severity.blocks()).count();
8258            let verify_timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
8259            // A round that already has a blocking finding and a round left to
8260            // try is going back to the fixer no matter what `verify.e2e`
8261            // says, so running it first only spends the loop's slowest step
8262            // (minutes, for a Rust repo's full test suite) on a head about
8263            // to be rewritten. Deferred, never skipped: `verify.e2e` still
8264            // runs once a round has no blocking findings left (see
8265            // `round_is_clean`, which a deferred — empty — `e2e` can never
8266            // satisfy since `blocking` is nonzero whenever this branch is
8267            // taken), and `stop_reviewing` forces a real run before it will
8268            // ever read a deferred round as green.
8269            let defer_e2e =
8270                blocking > 0 && round < max_rounds && !self.state.config.graph.e2e_every_round;
8271            let (e2e, verify_retried, e2e_deferred, e2e_defer_reason) = if defer_e2e {
8272                let reason =
8273                    format!("{blocking} blocking finding(s) already required a fix this round");
8274                self.state.event(
8275                    "verify",
8276                    format!(
8277                        "round {round}: {reason} — e2e deferred to the fixer (reviewed head \
8278                         {}); it will run once a round has none left",
8279                        short(&head)
8280                    ),
8281                );
8282                (Vec::new(), false, true, Some(reason))
8283            } else {
8284                let e2e_commands = self.state.config.verify.e2e.clone();
8285                let cache_dir = self.state.config.cache_dir();
8286                let context = format!("round {round}");
8287                let wait = self.repository_wait();
8288                let (e2e, verify_retried) = with_cache_lease(
8289                    &mut self.state,
8290                    cache_dir.as_deref(),
8291                    "e2e",
8292                    "e2e",
8293                    &winner.worktree,
8294                    &head,
8295                    verify_timeout,
8296                    &context,
8297                    &wait,
8298                    |state, budget| {
8299                        let shell = shell.clone();
8300                        let e2e_commands = e2e_commands.clone();
8301                        let worktree = winner.worktree.clone();
8302                        let context = context.clone();
8303                        let winner = winner.clone();
8304                        async move {
8305                            if !e2e_commands.is_empty() {
8306                                // The suite certifies one SHA. Format before it
8307                                // runs, or the commit `pre_gate` makes at the
8308                                // gate owes the whole suite again.
8309                                Self::run_pre_gate(state, &winner).await;
8310                            }
8311                            run_e2e_with_retry(
8312                                state,
8313                                &shell,
8314                                &e2e_commands,
8315                                &worktree,
8316                                budget,
8317                                &context,
8318                                Some(round),
8319                            )
8320                            .await
8321                        }
8322                    },
8323                )
8324                .await?;
8325                (e2e, verify_retried, false, None)
8326            };
8327
8328            let expected = records.len();
8329            let answered = records.iter().filter(|r| r.failed.is_none()).count();
8330            let incomplete = answered < expected;
8331            let e2e_ok = e2e.iter().all(CommandOutcome::ok);
8332            let policy = self.state.config.graph.incomplete_review;
8333            let clean = round_is_clean(
8334                blocking,
8335                e2e_ok,
8336                answered,
8337                expected,
8338                round_quota_missing,
8339                policy,
8340            );
8341
8342            let mut round_record = ReviewRound {
8343                round,
8344                head: head.clone(),
8345                verified_head: None,
8346                verified_at: None,
8347                reviews: records,
8348                e2e,
8349                verify_retried,
8350                e2e_deferred,
8351                e2e_defer_reason,
8352                fix: None,
8353                blocking,
8354                answered,
8355                expected,
8356                clean,
8357                progressed: false,
8358                vote_split,
8359                reconsideration,
8360                verdict: None,
8361            };
8362            // The final vote per seat is its revote where reconsideration
8363            // ran and answered, its initial vote otherwise — the same
8364            // fallback `tally` uses for a judge whose private vote failed.
8365            round_record.verdict = ReviewVote::worst(
8366                round_record
8367                    .final_votes()
8368                    .into_iter()
8369                    .map(|(_, _, vote)| vote),
8370            );
8371            // Which commit and when magi actually attempted to check —
8372            // known the moment a command was dispatched against `head`,
8373            // whether or not it finished: a resource-blocked attempt still
8374            // targeted a specific commit at a specific time, and leaving
8375            // that unrecorded is exactly what made `verification_summary`
8376            // report a fresh attempt as "commit unknown ... recorded before
8377            // this was tracked", indistinguishable from a genuinely old,
8378            // untracked record. Only a deferred or unconfigured round never
8379            // ran at all and has nothing to record — see
8380            // `ReviewRound::verified_head`'s own doc.
8381            if !matches!(
8382                round_record.e2e_status(),
8383                E2eStatus::Deferred | E2eStatus::NotConfigured
8384            ) {
8385                // HEAD, not the reviewed `head`: `pre_gate` may have committed
8386                // mechanical fixes before the commands ran.
8387                round_record.verified_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
8388                round_record.verified_at = Some(Timestamp::now());
8389            }
8390
8391            if incomplete {
8392                let missing: Vec<String> = round_record
8393                    .reviews
8394                    .iter()
8395                    .filter(|r| r.failed.is_some())
8396                    .map(|r| format!("review-{}", r.reviewer))
8397                    .collect();
8398                self.state.event(
8399                    "review",
8400                    format!(
8401                        "round {round}: {answered}/{expected} reviewer(s) answered ({} never answered)",
8402                        missing.join(", ")
8403                    ),
8404                );
8405            }
8406
8407            if clean {
8408                self.state.event(
8409                    "review",
8410                    if incomplete && policy == IncompleteReviewPolicy::Warn {
8411                        format!(
8412                            "round {round}: clean (warn policy, incomplete panel) — no \
8413                             blocking findings from the seats that answered, verification green"
8414                        )
8415                    } else if incomplete {
8416                        format!(
8417                            "round {round}: clean ({} rate-limited reviewer(s) excluded from \
8418                             quorum) — no blocking findings from the seats that answered, \
8419                             verification green",
8420                            expected - answered
8421                        )
8422                    } else {
8423                        format!("round {round}: clean — no blocking findings, verification green")
8424                    },
8425                );
8426                self.state.reviews.push(round_record);
8427                self.state.status = RunStatus::Gating;
8428                self.state.save()?;
8429                return Ok(());
8430            }
8431
8432            // Nothing was raised and verification passed, but not every seat
8433            // answered and `round_is_clean` still refused to call it clean —
8434            // either a seat is missing for a reason other than its own quota
8435            // (a crash, a timeout, unparsable output — worth another try), or
8436            // every seat that could have answered lost its quota and nobody
8437            // is left to decide on: re-review rather than send the fixer
8438            // after a round with nothing to fix.
8439            if incomplete && blocking == 0 && e2e_ok {
8440                self.state.reviews.push(round_record);
8441                self.state.save()?;
8442                if round == max_rounds {
8443                    self.state.status = RunStatus::Blocked;
8444                    self.state.event(
8445                        "review",
8446                        format!(
8447                            "{} reviewer seat(s) never answered after {max_rounds} rounds; \
8448                             refusing to call it clean",
8449                            expected - answered
8450                        ),
8451                    );
8452                    return Ok(());
8453                }
8454                continue;
8455            }
8456
8457            // Nothing for the fixer to act on (`blocking == 0`) and the only
8458            // reason this round is not clean is that magi itself never got
8459            // a command to run — the shared build cache, not the patch (see
8460            // `CommandOutcome::resource_blocked`'s own doc). Sending that to
8461            // the fixer would invite a change to appease contention that has
8462            // nothing to do with the diff, and would leave this attempt
8463            // sitting in the next round's prompt as if it were about an
8464            // earlier, superseded commit rather than what it actually is:
8465            // the same head, still waiting to be checked. Wait for it the
8466            // same way the final round's own contention is already handled,
8467            // whatever round this happens to be.
8468            if blocking == 0 && round_record.e2e_status() == E2eStatus::ResourceBlocked {
8469                self.state.reviews.push(round_record);
8470                return self
8471                    .stop_unresolved_review(
8472                        "the round's own verification could not run",
8473                        &shell,
8474                        &winner.worktree,
8475                    )
8476                    .await;
8477            }
8478
8479            if round == max_rounds {
8480                self.state.reviews.push(round_record);
8481                return self
8482                    .stop_reviewing(
8483                        &format!(
8484                            "{blocking} blocking finding(s) still open after {max_rounds} round(s)"
8485                        ),
8486                        &shell,
8487                        &winner.worktree,
8488                    )
8489                    .await;
8490            }
8491
8492            if !self.fix_review_round(&winner, round_record).await? {
8493                return Ok(());
8494            }
8495        }
8496        Ok(())
8497    }
8498
8499    /// Run the same fix chain for an in-loop failure or a persisted catch-up failure.
8500    /// False means admission or continuation policy stopped the review loop.
8501    async fn fix_review_round(
8502        &mut self,
8503        winner: &Candidate,
8504        mut round_record: ReviewRound,
8505    ) -> Result<bool> {
8506        let round = round_record.round;
8507        let shell = self.state.config.shell();
8508        let step = self.run_fix_round(winner, &mut round_record).await?;
8509        if matches!(step, FixStep::Resource) {
8510            self.stop_for_resource()?;
8511            return Ok(false);
8512        }
8513        if self.state.reviews.len() < round {
8514            self.state.reviews.push(round_record);
8515        } else {
8516            self.state.reviews[round - 1] = round_record;
8517        }
8518        self.state.save()?;
8519
8520        // The fixer's own report never came back this round, even after
8521        // `continue_fix_report`'s own budget was spent on it — not an
8522        // ordinary "no report" (dropped stream, quota, plain failure),
8523        // which already reads that way and is left to the existing round
8524        // budget. Stopping here, rather than opening another round, is
8525        // what keeps a next reviewer/fixer wave from ever being
8526        // dispatched onto `winner.worktree` while whatever the seat's
8527        // last call may still have running there is unaccounted for: no
8528        // process liveness check exists (and none is being added — see
8529        // AGENTS.md/this task's own scope), so the only way to honour
8530        // "nothing starts before a valid report returns" is to not start
8531        // anything further on this worktree from this run at all.
8532        if matches!(step, FixStep::Recorded { report_lost: true }) {
8533            self.stop_reviewing(
8534                "the fixer's adoption report never came back, even after resuming its \
8535                         own seat; refusing to start another round against the same worktree \
8536                         while that is unresolved",
8537                &shell,
8538                &winner.worktree,
8539            )
8540            .await?;
8541            return Ok(false);
8542        }
8543
8544        let streak = self
8545            .state
8546            .reviews
8547            .iter()
8548            .rev()
8549            .take_while(|r| !r.progressed)
8550            .count();
8551        if streak >= STAGNANT_LIMIT {
8552            self.stop_reviewing(
8553                &format!("the tree has not moved against base for {streak} round(s) in a row"),
8554                &shell,
8555                &winner.worktree,
8556            )
8557            .await?;
8558            return Ok(false);
8559        }
8560        Ok(true)
8561    }
8562
8563    /// Execute the shared fixer chain; the caller owns persistence and stop policy.
8564    async fn run_fix_round(
8565        &mut self,
8566        winner: &Candidate,
8567        round_record: &mut ReviewRound,
8568    ) -> Result<FixStep> {
8569        let round = round_record.round;
8570        let max_rounds = self.state.config.graph.review_rounds;
8571        let run_id = self.state.id.clone();
8572        let prompts = self.state.config.prompts.clone();
8573        let language = self.state.config.graph.language.clone();
8574        let sessions = self.state.config.graph.sessions;
8575        let artifacts = self.merge_repair_artifacts();
8576        let base = self.landing_base();
8577        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
8578        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
8579        let this_round_verification = round_record.verification_summary(&head);
8580        let all_findings: Vec<_> = round_record
8581            .reviews
8582            .iter()
8583            .flat_map(|r| r.findings.iter().cloned())
8584            .collect();
8585        // Fix. The winner's own implementer seat continues its conversation:
8586        // the competition is over, so context is pure benefit now.
8587        let blocking_findings: Vec<_> = all_findings
8588            .iter()
8589            .filter(|f| f.severity.blocks())
8590            .cloned()
8591            .collect();
8592        let fix_prompt = prompt::fix_in(
8593            &self.state.instruction,
8594            &blocking_findings,
8595            this_round_verification.as_ref(),
8596            round,
8597            max_rounds,
8598            &language,
8599            &self.state.config.graph.github_language,
8600        );
8601        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
8602        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
8603        let (job, seat, out) = self
8604            .ask_fixer(winner, "fix", Some(round), |spec, seat| SeatJob {
8605                prompt: fix_prompt.clone(),
8606                spec,
8607                seat,
8608                cwd: winner.worktree.clone(),
8609                timeout,
8610                allow_write: true,
8611                sessions,
8612                artifacts: artifacts.clone(),
8613                stem: format!("fix-{round}"),
8614                handover: None,
8615            })
8616            .await;
8617        // Not asked: the round is not recorded (so a resume repeats it),
8618        // no fixer was handed over to, and the seat is left as it was.
8619        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
8620            return Ok(FixStep::Resource);
8621        }
8622        let agent_id = seat.agent.clone();
8623
8624        let mut fix = FixRecord {
8625            agent: agent_id,
8626            addressed: Vec::new(),
8627            rejected: Vec::new(),
8628            notes: String::new(),
8629            committed: false,
8630            failed: None,
8631            duration_ms: 0,
8632            continuation: None,
8633        };
8634        let mut continuation = ContinuationRecord::not_needed();
8635        let mut final_seat = seat.clone();
8636        match out {
8637            AgentOutcome::Ok(o) => {
8638                fix.duration_ms = o.duration_ms;
8639                let parsed = verdict::extract_json::<FixReport>(&o.text);
8640                // A parsed report standing next to a command this same
8641                // reply's own CLI never confirmed the exit status of is
8642                // not a resolved answer — the identical `CommandEvidence`
8643                // `state.jobs` renders, read here instead of only on
8644                // display, per the completion judgment and the shown
8645                // record needing to agree.
8646                let incomplete_reason = match &parsed {
8647                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
8648                        "the reply parsed, but it reported a command whose own CLI never \
8649                             confirmed an exit status"
8650                            .to_owned(),
8651                    ),
8652                    Ok(_) => None,
8653                    Err(e) => Some(e.to_string()),
8654                };
8655                match incomplete_reason {
8656                    None => {
8657                        let report = parsed.expect("checked Ok above");
8658                        fix.addressed = report.addressed;
8659                        fix.rejected = report.rejected;
8660                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
8661                    }
8662                    Some(reason) => {
8663                        let (resumed_seat, resolved, failure, cont) = self
8664                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, round)
8665                            .await;
8666                        fix.duration_ms += cont.cumulative_wait_ms;
8667                        continuation = cont;
8668                        final_seat = resumed_seat;
8669                        match resolved {
8670                            Some(report) => {
8671                                fix.addressed = report.addressed;
8672                                fix.rejected = report.rejected;
8673                                fix.notes =
8674                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
8675                            }
8676                            None => fix.failed = failure,
8677                        }
8678                    }
8679                }
8680            }
8681            // The CLI's raw error JSON is not a fix report to parse.
8682            AgentOutcome::Dropped(o) => {
8683                fix.duration_ms = o.duration_ms;
8684                let why = o
8685                    .dropped
8686                    .as_ref()
8687                    .map(|d| d.why.as_str())
8688                    .unwrap_or("the CLI ended the stream without delivering its answer");
8689                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
8690            }
8691            AgentOutcome::Quota(o) => {
8692                self.state.quota.push(QuotaLoss::from_report(
8693                    final_seat.key.clone(),
8694                    "fix",
8695                    o.quota.as_ref(),
8696                ));
8697                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
8698            }
8699            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => fix.failed = Some(e),
8700        }
8701        if self.state.resource_block.is_some() {
8702            self.state.seats.insert(final_seat.key.clone(), final_seat);
8703            return Ok(FixStep::Resource);
8704        }
8705        fix.continuation = Some(continuation);
8706        self.state.seats.insert(final_seat.key.clone(), final_seat);
8707        let coordination = self.coordinate(&winner.worktree).await?;
8708        if let Ok(r) = git::rescue_commit(
8709            &winner.worktree,
8710            &format!("magi: review round {round} fixes (uncommitted work)"),
8711        )
8712        .await
8713        {
8714            self.state.note_withheld("fix", &r.withheld);
8715        }
8716        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
8717        fix.committed = after != before;
8718        // Judged by what `git` says moved against base, never by the
8719        // fixer's own `addressed`/`rejected` count — see
8720        // `ReviewRound::progressed`. Propagated with `?`, the same as the
8721        // `patch` snapshot above: swallowing this error would default
8722        // `diff_after` to empty, which almost always differs from a
8723        // non-empty `patch` and reads as "progressed" — exactly backwards
8724        // for a `git` failure the stagnation check cannot see through.
8725        let diff_after = git::diff(&winner.worktree, &base, "HEAD").await?;
8726        drop(coordination);
8727        let progressed = diff_after != patch;
8728        let commit_note = if fix.committed {
8729            "committed"
8730        } else {
8731            "NO new commit"
8732        };
8733        let tree_note = if progressed {
8734            "changed vs base"
8735        } else {
8736            "unchanged vs base"
8737        };
8738        self.state.event(
8739            "fix",
8740            match &fix.failed {
8741                // Distinct on purpose from "0 addressed, 0 rejected": the
8742                // fixer's own diff still landed (blocking counts do keep
8743                // falling round over round), only its adoption report did
8744                // not come back, so this must never read like every
8745                // finding was reviewed and declined.
8746                Some(reason) => {
8747                    format!(
8748                        "round {round}: fixer's adoption report was lost ({reason}); \
8749                             {commit_note}, tree {tree_note}"
8750                    )
8751                }
8752                None => format!(
8753                    "round {round}: {} addressed, {} rejected, {commit_note}, tree \
8754                         {tree_note}{}",
8755                    fix.addressed.len(),
8756                    fix.rejected.len(),
8757                    if continuation.outcome == ContinuationOutcome::Resumed {
8758                        format!(
8759                            " (adoption report recovered after {} continuation(s))",
8760                            continuation.attempts
8761                        )
8762                    } else {
8763                        String::new()
8764                    },
8765                ),
8766            },
8767        );
8768        round_record.fix = Some(fix);
8769        round_record.progressed = progressed;
8770        Ok(FixStep::Recorded {
8771            report_lost: matches!(
8772                continuation.outcome,
8773                ContinuationOutcome::Exhausted
8774                    | ContinuationOutcome::QuotaLost
8775                    | ContinuationOutcome::NoSession
8776            ),
8777        })
8778    }
8779
8780    /// Decide, from the last recorded round's own verification, whether
8781    /// stopping the review loop is a hand-off or a genuine block.
8782    ///
8783    /// Called once the loop has given up trying — the round budget is spent,
8784    /// or the tree stopped moving (see [`STAGNANT_LIMIT`]) — with blocking
8785    /// findings still open, never while a round is still clean or the
8786    /// incomplete-panel case handled inline above. Gate and e2e are facts
8787    /// about the tree; a lingering review finding is an opinion, and this
8788    /// workload's own `magi stats` puts reviewer precision low enough
8789    /// (12-33%, 0.18-0.29 adopted per round) that a panel of open findings
8790    /// must not by itself stand between a green, verified change and the
8791    /// human who decides what to do with it. A red e2e is not an opinion, so
8792    /// that case still blocks, with the failing command and a tail of its
8793    /// output recorded here rather than left in `run.json` for someone to go
8794    /// find.
8795    ///
8796    /// A round that deferred its own e2e (see [`Config::graph`]'s
8797    /// `e2e_every_round`) is never read as that green: its `e2e` is empty
8798    /// only because nothing ran, and treating an empty list as a passing one
8799    /// here is exactly the "deferred painted green" bug this function exists
8800    /// to not have. When the last round's own verification never resolved —
8801    /// deferred on purpose, or a real attempt the shared build cache blocked
8802    /// — this makes (or retries) the real run, on the actual worktree this
8803    /// loop is about to stop touching, before deciding anything. A
8804    /// resource-blocked attempt is likewise never read as either green or
8805    /// red: it is evidence about the machine, not the patch (see
8806    /// [`CommandOutcome::resource_blocked`]'s own doc), so a persistently
8807    /// blocked cache leaves this call without deciding rather than guessing
8808    /// — the caller retries on a later reentry.
8809    /// Record, once, that the review loop handed off over a blocking finding
8810    /// a reviewer rejected on (see [`ReviewRound::contested_handoff`]), so
8811    /// `land` asks the owner even with `land_approval` off. Called from every
8812    /// path that concludes `Gating`; a reentry keeps the first record.
8813    fn record_contested_handoff(&mut self) {
8814        if self.state.contested_handoff.is_some() {
8815            return;
8816        }
8817        let Some(contested) = self
8818            .state
8819            .reviews
8820            .last()
8821            .and_then(ReviewRound::contested_handoff)
8822        else {
8823            return;
8824        };
8825        self.state.event(
8826            "review",
8827            format!(
8828                "{} blocking finding(s) open and {} reviewer(s) rejecting — the merge will \
8829                 wait for the owner's approval",
8830                contested.findings.len(),
8831                contested.rejecters.len()
8832            ),
8833        );
8834        self.state.contested_handoff = Some(contested);
8835    }
8836
8837    async fn stop_unresolved_review(
8838        &mut self,
8839        why: &str,
8840        shell: &[String],
8841        worktree: &Path,
8842    ) -> Result<()> {
8843        self.stop_reviewing_inner(why, shell, worktree, true).await
8844    }
8845
8846    async fn stop_reviewing(&mut self, why: &str, shell: &[String], worktree: &Path) -> Result<()> {
8847        self.stop_reviewing_inner(why, shell, worktree, false).await
8848    }
8849
8850    async fn stop_reviewing_inner(
8851        &mut self,
8852        why: &str,
8853        shell: &[String],
8854        worktree: &Path,
8855        repairable: bool,
8856    ) -> Result<()> {
8857        let round_idx = self.state.reviews.len() - 1;
8858        // A deferred round and a resource-blocked one are the same shape
8859        // here: neither has a real result yet, and both get one more
8860        // attempt. Read off `e2e_status` — the single source for this —
8861        // rather than `e2e.is_empty()` alone, so a resource-blocked attempt
8862        // (whose `e2e` is *not* empty; see `CommandOutcome::resource_blocked`)
8863        // still retries instead of being read as a settled result the
8864        // instant it stops being empty.
8865        let needs_catchup_run = matches!(
8866            self.state.reviews[round_idx].e2e_status(),
8867            E2eStatus::Deferred | E2eStatus::ResourceBlocked
8868        );
8869        if needs_catchup_run {
8870            let round = self.state.reviews[round_idx].round;
8871            let timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
8872            let commands = self.state.config.verify.e2e.clone();
8873            let before_head = git::rev_parse(worktree, "HEAD").await?;
8874            let winner = self.state.winner().cloned();
8875            let cache_dir = self.state.config.cache_dir();
8876            let context = format!(
8877                "round {round}: verification unresolved, catching up before the final decision"
8878            );
8879            let wait = self.repository_wait();
8880            let (outcomes, verify_retried) = with_cache_lease(
8881                &mut self.state,
8882                cache_dir.as_deref(),
8883                "e2e",
8884                "e2e",
8885                worktree,
8886                &before_head,
8887                timeout,
8888                &context,
8889                &wait,
8890                |state, budget| {
8891                    let shell = shell.to_vec();
8892                    let commands = commands.clone();
8893                    let context = context.clone();
8894                    async move {
8895                        if let Some(winner) = winner.filter(|_| !commands.is_empty()) {
8896                            // Same reason as in the round itself: format before
8897                            // the suite, not after it.
8898                            Self::run_pre_gate(state, &winner).await;
8899                        }
8900                        run_e2e_with_retry(
8901                            state,
8902                            &shell,
8903                            &commands,
8904                            worktree,
8905                            budget,
8906                            &context,
8907                            Some(round),
8908                        )
8909                        .await
8910                    }
8911                },
8912            )
8913            .await?;
8914            // After `pre_gate`: the commit the commands actually ran against.
8915            let attempted_head = git::rev_parse(worktree, "HEAD").await?;
8916            if !outcomes.is_empty() && !verify_inconclusive(&outcomes) {
8917                self.state.record_base_progress(&attempted_head);
8918            }
8919            let last = &mut self.state.reviews[round_idx];
8920            last.e2e = outcomes;
8921            last.verify_retried = verify_retried;
8922            // Always the commit and time this attempt actually targeted,
8923            // whether or not it happens to equal the reviewed `head` and
8924            // whether or not a command finished — see
8925            // `ReviewRound::verified_head`'s own doc. A still-inconclusive
8926            // attempt is recorded too, so a later reader sees "attempted
8927            // again at T2" rather than silence.
8928            last.verified_head = Some(attempted_head);
8929            last.verified_at = Some(Timestamp::now());
8930            if verify_inconclusive(&last.e2e) {
8931                // Still not a real result: `e2e_deferred` is left exactly
8932                // as it was, so `needs_catchup_run` above reads
8933                // `ResourceBlocked` (via `e2e_status`, which checks
8934                // `resource_blocked` before `e2e_deferred`) and retries
8935                // again on the next reentry, rather than recording
8936                // contention as a red e2e and blocking the run on it.
8937                self.state.save()?;
8938                return Ok(());
8939            }
8940            last.e2e_deferred = false;
8941            // A complete panel may have been saved as unclean solely because
8942            // verification could not run. Refresh that verdict with the new
8943            // outcomes before a granted repair consumes the round's result.
8944            // Incomplete panels retain their original policy/quota decision.
8945            if last.answered == last.expected {
8946                last.clean = round_is_clean(
8947                    last.blocking,
8948                    last.e2e.iter().all(CommandOutcome::ok),
8949                    last.answered,
8950                    last.expected,
8951                    0,
8952                    self.state.config.graph.incomplete_review,
8953                );
8954            }
8955        }
8956        let last = &self.state.reviews[round_idx];
8957        let open: usize = last.reviews.iter().map(|r| r.findings.len()).sum();
8958
8959        match last.e2e_status() {
8960            E2eStatus::Failed => {
8961                let red: Vec<String> = last
8962                    .e2e
8963                    .iter()
8964                    .filter(|o| !o.ok())
8965                    .map(|o| {
8966                        let comparison = crate::verify_evidence::outcome_comparison_summary(o)
8967                            .map(|c| format!(" ({c})"))
8968                            .unwrap_or_default();
8969                        format!(
8970                            "`{}` -> {:?}{comparison}\n{}",
8971                            o.command,
8972                            o.code,
8973                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
8974                        )
8975                    })
8976                    .collect();
8977                let can_repair = last.blocking == 0 && last.fix.is_none();
8978                self.state.reviews[round_idx].clean = false;
8979                self.state
8980                    .event("review", format!("{why}; e2e failed:\n{}", red.join("\n")));
8981                self.state.status = RunStatus::Blocked;
8982                if repairable
8983                    && can_repair
8984                    && self.state.reviews.len() < self.state.config.graph.review_rounds
8985                {
8986                    self.state.status = RunStatus::Reviewing;
8987                }
8988            }
8989            // `needs_catchup_run` above already retried once this call; if
8990            // it is still blocked, this is magi's own admission it could
8991            // not get a command to run, never a verdict on the patch — the
8992            // run is left exactly where a later reentry can retry again.
8993            E2eStatus::ResourceBlocked => {
8994                self.state.event(
8995                    "review",
8996                    format!(
8997                        "{why}; e2e could not run (resource unavailable); not \
8998                         deciding yet"
8999                    ),
9000                );
9001            }
9002            E2eStatus::Passed | E2eStatus::Deferred | E2eStatus::NotConfigured => {
9003                self.state.event(
9004                    "review",
9005                    format!("{why}; e2e is green — handing off with {open} finding(s) still open"),
9006                );
9007                self.record_contested_handoff();
9008                self.state.status = RunStatus::Gating;
9009            }
9010        }
9011        self.state.save()?;
9012        Ok(())
9013    }
9014
9015    // ----------------------------------------------------------------- gate
9016
9017    async fn gate(&mut self) -> Result<()> {
9018        if self.hold_base_sync().await? {
9019            return Ok(());
9020        }
9021        // Judged by the review record itself, not by `status`: a solo
9022        // candidate's `judge`/`deliberate` skip rewrites `status` on every
9023        // reentry (see `judge`), and trusting it here is exactly how a run
9024        // that exhausted its review budget got gated and merged a second
9025        // time around. `review_conclusion` recomputes the review loop's own
9026        // verdict from the round records themselves — `Gating` for a clean
9027        // round or a hand-off (see `stop_reviewing`), anything else means the
9028        // loop is still going or genuinely blocked.
9029        // A base the winner could not be replayed onto is a decision, not a
9030        // round: there is no landing tree to gate. Read as its own record for
9031        // the same reason the review verdict is.
9032        if self.state.status == RunStatus::Failed
9033            || self
9034                .state
9035                .base_sync
9036                .as_ref()
9037                .is_some_and(|s| s.conflict.is_some())
9038            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
9039                != Some(RunStatus::Gating)
9040        {
9041            return Ok(());
9042        }
9043        let Some(winner) = self.state.winner().cloned() else {
9044            return Ok(());
9045        };
9046        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
9047        self.state.reconcile_verification_head(&head);
9048        self.state.save()?;
9049        let wait = self.repository_wait();
9050        if !verify_current_head(&mut self.state, &winner, &wait).await? {
9051            return Ok(());
9052        }
9053        if self.state.gate_ran {
9054            // `review_loop` derives its conclusion from the clean review
9055            // record on every reentry and therefore puts a completed run back
9056            // in `Gating`. A recorded gate is a stronger, terminal fact:
9057            // retain its original command output (or lack of any, for a repo
9058            // with no `verify.gate` commands — see `RunState::gate_ran`'s own
9059            // doc) and restore `Blocked` on a real failure rather than
9060            // pretending the command is still running or running it a second
9061            // time. `gate_ran == false` remains the only shape — unattempted,
9062            // or a resource-blocked retry — that may still need to execute a
9063            // command.
9064            if self.state.gate.iter().any(|outcome| !outcome.ok()) {
9065                self.state.status = RunStatus::Blocked;
9066                self.state.save()?;
9067            }
9068            return Ok(());
9069        }
9070        self.state.status = RunStatus::Gating;
9071        let mut outcomes = self.run_gate(&winner).await?;
9072        let mut attempted_head = self.state.gate_head.clone();
9073        loop {
9074            // A resource-blocked outcome means the gate command never actually
9075            // ran - the shared build cache could not be acquired or confirmed
9076            // fresh in time - which is evidence about the machine, not about
9077            // the tree (see `CommandOutcome::resource_blocked`'s own doc).
9078            // Recording it as a red gate would mark a run `Blocked` on nothing
9079            // but contention magi has already logged; leaving `self.state.gate`
9080            // empty and `self.state.gate_ran` false instead keeps the shape
9081            // this function already treats as "still needs to run" (see the
9082            // early-return above), so the next call retries the command
9083            // rather than concluding anything.
9084            if verify_inconclusive(&outcomes) {
9085                self.state.save()?;
9086                return Ok(());
9087            }
9088            if outcomes.iter().all(CommandOutcome::ok) {
9089                break;
9090            }
9091            let fixes_before = self.state.gate_fixes.len();
9092            match self.gate_fix_round(&winner, &outcomes).await? {
9093                GateFix::Retry => {
9094                    outcomes = self.run_gate(&winner).await?;
9095                    attempted_head = self.state.gate_head.clone();
9096                }
9097                GateFix::Stop => {
9098                    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
9099                    if self.state.gate_fixes.len() > fixes_before
9100                        && attempted_head.as_deref() != Some(current.as_str())
9101                        && verify_current_head(&mut self.state, &winner, &wait).await?
9102                    {
9103                        // A new SHA owes a gate even when a spent fixer changed only
9104                        // commit metadata. This does not grant another repair round.
9105                        outcomes = self.run_gate(&winner).await?;
9106                        attempted_head = self.state.gate_head.clone();
9107                    } else {
9108                        break;
9109                    }
9110                }
9111                GateFix::Defer => {
9112                    self.state.save()?;
9113                    return Ok(());
9114                }
9115            }
9116        }
9117        let passed = outcomes.iter().all(CommandOutcome::ok);
9118        self.state.gate = outcomes;
9119        self.state.gate_ran = true;
9120        self.state.gate_head = attempted_head;
9121        if !self.state.gate.is_empty()
9122            && !verify_inconclusive(&self.state.gate)
9123            && let Some(head) = self.state.gate_head.clone()
9124        {
9125            self.state.record_base_progress(&head);
9126        }
9127        self.state.save()?;
9128        if !verify_current_head(&mut self.state, &winner, &wait).await? {
9129            return Ok(());
9130        }
9131        if !passed {
9132            self.state.status = RunStatus::Blocked;
9133            let spent = self.state.gate_fixes.len();
9134            self.state.event(
9135                "gate",
9136                if spent == 0 {
9137                    "gate failed; not merging".to_owned()
9138                } else {
9139                    format!("gate failed after {spent} gate-fix round(s); not merging")
9140                },
9141            );
9142        }
9143        self.state.save()?;
9144        Ok(())
9145    }
9146
9147    /// Run `verify.pre_gate` in the winner's worktree, then fold whatever it
9148    /// changed into one commit. Runs before `verify.e2e` in the review loop
9149    /// and again before the gate commands, always on the winner and never on
9150    /// a candidate awaiting judging.
9151    ///
9152    /// Before e2e as well as before the gate because command evidence belongs
9153    /// to a SHA ([`verify_current_head`]): a commit made only at the gate is a
9154    /// commit e2e never saw, and the suite ran again for a formatter's diff -
9155    /// 5 of the 22 gated runs on this repository in November 2026. The gate's
9156    /// own call then finds nothing left to change. The commands must be
9157    /// idempotent; one that is not makes a commit per call.
9158    ///
9159    /// Never fails the run: a non-zero exit or timeout is a warning and a
9160    /// recorded outcome, and the gate remains the single arbiter. Nothing
9161    /// configured means nothing happens - no event, no commit. `commit_all`
9162    /// commits any leftover change under the neutral identity and returns
9163    /// `false` when the tree is clean, so no empty commit is ever made.
9164    async fn run_pre_gate(state: &mut RunState, winner: &Candidate) {
9165        let commands = state.config.verify.pre_gate.clone();
9166        if commands.is_empty() {
9167            return;
9168        }
9169        let shell = state.config.shell();
9170        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
9171        let (outcomes, _) = run_commands(
9172            state,
9173            "pre_gate",
9174            "pre_gate",
9175            0,
9176            &shell,
9177            &commands,
9178            &winner.worktree,
9179            timeout,
9180        )
9181        .await;
9182        for o in &outcomes {
9183            if !o.ok() {
9184                tracing::warn!(
9185                    "pre_gate `{}` failed ({:?}); the gate decides",
9186                    o.command,
9187                    o.code
9188                );
9189            }
9190            state.event(
9191                "pre_gate",
9192                format!(
9193                    "`{}` -> {}",
9194                    o.command,
9195                    if o.ok() {
9196                        "pass".to_owned()
9197                    } else {
9198                        format!(
9199                            "FAIL ({:?})\n{}",
9200                            o.code,
9201                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
9202                        )
9203                    }
9204                ),
9205            );
9206        }
9207        state.pre_gate = outcomes;
9208        match git::commit_all(&winner.worktree, PRE_GATE_COMMIT_MESSAGE).await {
9209            Ok(true) => match git::rev_parse(&winner.worktree, "HEAD").await {
9210                Ok(head) => {
9211                    state.event(PRE_GATE_EVENT_NODE, pre_gate_commit_event(&head));
9212                    state.pre_gate_commit = Some(head);
9213                }
9214                Err(e) => tracing::warn!("pre_gate committed but HEAD unreadable: {e:#}"),
9215            },
9216            Ok(false) => {}
9217            Err(e) => tracing::warn!("pre_gate could not commit its changes: {e:#}"),
9218        }
9219        if let Err(e) = state.save() {
9220            tracing::warn!("could not persist the pre_gate record: {e:#}");
9221        }
9222    }
9223
9224    /// Run `verify.gate` once against the winner's current tree, logging one
9225    /// event per command. Empty when nothing is configured.
9226    async fn run_gate(&mut self, winner: &Candidate) -> Result<Vec<CommandOutcome>> {
9227        let wait = self.repository_wait();
9228        run_landing_gate(&mut self.state, winner, &wait).await
9229    }
9230
9231    /// One bounded fix round for a failing gate.
9232    ///
9233    /// The fixer is told the failure came from the gate itself, not from a
9234    /// reviewer, and is shown the failed commands, their exit codes and a tail
9235    /// of their output - whatever `[verify].gate` holds, nothing here knows
9236    /// what those commands run. Only a normal non-zero exit that printed
9237    /// something earns a round (see [`gate_fixable`]): a timeout, a missing
9238    /// command or a full disk says nothing about the code, and a fixer sent
9239    /// after it can only appease the machine. The round is judged by what git
9240    /// says moved, never by the fixer's own report, and `verify.e2e` runs
9241    /// again before the gate does, so a fix cannot trade a green gate for a
9242    /// red e2e unnoticed.
9243    async fn gate_fix_round(
9244        &mut self,
9245        winner: &Candidate,
9246        outcomes: &[CommandOutcome],
9247    ) -> Result<GateFix> {
9248        let cap = if self.state.repair_grants.last().is_some_and(|g| {
9249            g.phase == crate::repair_budget::Phase::Fixing
9250                && g.receipt.request.kind == crate::repair_budget::Kind::Gate
9251        }) {
9252            self.state.gate_fixes.len().saturating_add(1)
9253        } else {
9254            self.state.config.graph.gate_fix_rounds
9255        };
9256        let spent = self.state.gate_fixes.len();
9257        if spent >= cap {
9258            if cap > 0 {
9259                self.state.event(
9260                    "gate",
9261                    format!("{spent} gate-fix round(s) spent and the gate still fails"),
9262                );
9263            }
9264            return Ok(GateFix::Stop);
9265        }
9266        if !gate_fixable(outcomes) {
9267            self.state.event(
9268                "gate",
9269                "gate failure is not an ordinary non-zero exit with output (timeout, missing \
9270                 command or similar); not spending a fix round on it",
9271            );
9272            return Ok(GateFix::Stop);
9273        }
9274        let min_free = self.state.config.disk.min_free_bytes;
9275        if min_free > 0 {
9276            match crate::disk::free_bytes(&winner.worktree) {
9277                Ok(free) if crate::disk::enough_space(free, min_free) => {}
9278                Ok(free) => {
9279                    self.state.event(
9280                        "gate",
9281                        format!(
9282                            "only {free} bytes free ({min_free} required by `[disk] \
9283                             min_free_bytes`); not spending a fix round on a failure the disk \
9284                             may explain"
9285                        ),
9286                    );
9287                    return Ok(GateFix::Stop);
9288                }
9289                Err(e) => {
9290                    self.state.event(
9291                        "gate",
9292                        format!("free disk space could not be measured ({e:#}); no fix round"),
9293                    );
9294                    return Ok(GateFix::Stop);
9295                }
9296            }
9297        }
9298
9299        let attempt = spent + 1;
9300        let failed: Vec<CommandOutcome> = outcomes.iter().filter(|o| !o.ok()).cloned().collect();
9301        let base = self.landing_base();
9302        let fix_prompt = prompt::gate_fix_in(
9303            &self.state.instruction,
9304            &failed,
9305            attempt,
9306            cap,
9307            &self.state.config.graph.language,
9308            &self.state.config.graph.github_language,
9309        );
9310        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
9311        let sessions = self.state.config.graph.sessions;
9312        let artifacts = self.merge_repair_artifacts();
9313        self.state.event(
9314            "gate",
9315            format!("gate failed; gate-fix round {attempt} of {cap}"),
9316        );
9317        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
9318        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
9319        // Persist before invoking the fixer: it may commit and then be
9320        // interrupted before its result (or the following e2e) is saved.
9321        self.state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
9322            before.clone(),
9323            false,
9324            Vec::new(),
9325        ));
9326        self.state.save()?;
9327        let (_, seat, out) = self
9328            .ask_fixer(winner, "gate-fix", None, |spec, seat| SeatJob {
9329                prompt: fix_prompt.clone(),
9330                spec,
9331                seat,
9332                cwd: winner.worktree.clone(),
9333                timeout,
9334                allow_write: true,
9335                sessions,
9336                artifacts: artifacts.clone(),
9337                stem: format!("gate-fix-{attempt}"),
9338                handover: None,
9339            })
9340            .await;
9341        // The fixer was never asked: no round is spent (nothing is recorded)
9342        // and a later reentry asks the same agent again.
9343        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
9344            return Ok(GateFix::Defer);
9345        }
9346        let mut record = GateFixRecord {
9347            agent: seat.agent.clone(),
9348            failed,
9349            notes: String::new(),
9350            committed: false,
9351            error: None,
9352        };
9353        match out {
9354            AgentOutcome::Ok(o) => {
9355                // A missing report is not a failed fix: the round is judged
9356                // by the tree below, and the report only carries prose.
9357                if let Ok(report) = verdict::extract_json::<FixReport>(&o.text) {
9358                    record.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
9359                }
9360            }
9361            AgentOutcome::Dropped(_) => {
9362                record.error = Some("the CLI dropped the stream".to_owned());
9363            }
9364            AgentOutcome::Quota(o) => {
9365                self.state.quota.push(QuotaLoss::from_report(
9366                    seat.key.clone(),
9367                    "gate-fix",
9368                    o.quota.as_ref(),
9369                ));
9370                record.error = Some("rate limited (quota); fixer could not run".to_owned());
9371            }
9372            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => record.error = Some(e),
9373        }
9374        self.state.seats.insert(seat.key.clone(), seat);
9375        let coordination = self.coordinate(&winner.worktree).await?;
9376        if let Ok(r) = git::rescue_commit(
9377            &winner.worktree,
9378            &format!("magi: gate fix {attempt} (uncommitted work)"),
9379        )
9380        .await
9381        {
9382            self.state.note_withheld("gate-fix", &r.withheld);
9383        }
9384        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
9385        record.committed = after != before;
9386        let changed = git::diff(&winner.worktree, &base, "HEAD").await? != patch;
9387        let note = record.error.clone();
9388        self.state.gate_fixes.push(record);
9389        self.state.save()?;
9390        if !changed {
9391            self.state.event(
9392                "gate",
9393                match note {
9394                    Some(why) => format!("gate-fix round {attempt}: fixer failed ({why})"),
9395                    None => format!("gate-fix round {attempt}: the tree did not change"),
9396                },
9397            );
9398            return Ok(GateFix::Stop);
9399        }
9400        self.state.event(
9401            "gate",
9402            format!("gate-fix round {attempt}: tree changed vs base; re-running verify.e2e"),
9403        );
9404
9405        drop(coordination);
9406        let wait = self.repository_wait();
9407        check_gate_repair_e2e(&mut self.state, winner, &wait).await
9408    }
9409
9410    // ---------------------------------------------------------------- merge
9411
9412    /// One read-only rewrite by the summary's author; a text the gate still
9413    /// withholds goes to the owner (see `github_text`) and the fixed fallback
9414    /// applies on their word or on silence. `None` means the run is parked on
9415    /// that question and nothing may be pushed or opened yet.
9416    async fn guarded_pr_message(
9417        &mut self,
9418        winner: &Candidate,
9419        facts: Option<&BranchFacts>,
9420        posting: bool,
9421    ) -> Result<Option<PrMessage>> {
9422        let final_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
9423        let head = match final_head.as_deref() {
9424            Some(h) => crate::pr_outcome::FinalHead::At(h),
9425            None => crate::pr_outcome::FinalHead::Unknown,
9426        };
9427        // Only a pull request that is about to be posted pays for a summary.
9428        let summarized = if posting {
9429            Some(self.summarize_change(winner, final_head.as_deref()).await)
9430        } else {
9431            None
9432        };
9433        // A busy shared resource is not a permanent cause: publishing an
9434        // "unavailable" description would stick (a later head move never
9435        // edits the body). Stop before anything is pushed or opened; the
9436        // run is `Blocked` and a resume asks the summary again.
9437        if self.state.resource_block.is_some() {
9438            self.state.event(
9439                "pr-summary",
9440                "a shared resource was busy; nothing was published, resume to summarize again",
9441            );
9442            return Ok(None);
9443        }
9444        if posting && git::rev_parse(&winner.worktree, "HEAD").await.ok() != final_head {
9445            anyhow::bail!(
9446                "the final commit moved during public description generation; retry before publishing"
9447            );
9448        }
9449        let note = match (&summarized, &self.state.change_summary) {
9450            (Some(Ok(())), Some(c)) => ChangeNote::Summary(c),
9451            (Some(Err(why)), _) => ChangeNote::Unavailable(why),
9452            (Some(Ok(())), None) => ChangeNote::Unavailable("no summary was recorded"),
9453            (None, _) => ChangeNote::NotAsked,
9454        };
9455        let mut pr = pr_message_raw(&self.state, winner.label, facts, head, note);
9456        if !posting {
9457            let identity = crate::scrub::Identity::current();
9458            return Ok(Some(PrMessage {
9459                title: crate::scrub::scrub(&pr.title, &identity),
9460                body: crate::scrub::scrub(&pr.body, &identity),
9461            }));
9462        }
9463        // This very text was already rejected and asked about: no second
9464        // judge call, rewrite or question, just carry the record on.
9465        let raw_fp = crate::github_text::fingerprint(&pr.title, &pr.body);
9466        if let Some(known) = self
9467            .state
9468            .github_text
9469            .clone()
9470            .filter(|g| g.fingerprint == raw_fp)
9471        {
9472            return self.settle_withheld(winner, &pr, known).await;
9473        }
9474        let mut decision = self.judge_pr_language(&winner.worktree, &pr).await;
9475        let mut violations =
9476            crate::github_text::check_for(&self.state.config.graph, &pr.title, &pr.body, decision);
9477        let identity = crate::scrub::Identity::current();
9478        if (crate::scrub::scrub(&pr.title, &identity) != pr.title
9479            || crate::scrub::scrub(&pr.body, &identity) != pr.body)
9480            && !violations.contains(&crate::github_text::Violation::SensitiveData)
9481        {
9482            violations.push(crate::github_text::Violation::SensitiveData);
9483        }
9484        // A rewrite cannot fix sensitive data (e.g. a quoted original task), so
9485        // only a language violation starts one; sensitive data alone goes
9486        // straight to the owner, with the redacted text as the fallback.
9487        let has_language = violations
9488            .iter()
9489            .any(|v| *v != crate::github_text::Violation::SensitiveData);
9490        if self.state.config.graph.github_text_guard && !violations.is_empty() {
9491            self.state.event(
9492                "github-text",
9493                if has_language {
9494                    format!("description rejected: {violations:?}; requesting one rewrite")
9495                } else {
9496                    format!("description rejected: {violations:?}; asking the owner")
9497                },
9498            );
9499            let mut rewritten = false;
9500            let mut rejected_rewrite = None;
9501            if has_language && let Some(text) = self.rewrite_pr_text(winner, &pr, &violations).await
9502            {
9503                let output = text;
9504                if let Some(title) = summary_title(&output) {
9505                    // Judge the redacted candidate that will actually be posted.
9506                    // Sensitive data alone must not discard a useful rewrite.
9507                    let raw_body = summary_without_title(&output);
9508                    let clean_title = crate::scrub::scrub(&title, &identity);
9509                    let mut body = crate::scrub::scrub(&raw_body, &identity);
9510                    let redacted = clean_title != title || body != raw_body;
9511                    let title = clean_title;
9512                    let complete = crate::pr_outcome::covers_required_findings(&self.state, &body);
9513                    if !complete {
9514                        self.state.event(
9515                            "github-text",
9516                            "description rewrite omitted required findings",
9517                        );
9518                    }
9519                    if !body.trim().is_empty() {
9520                        body.push_str("\n\n");
9521                        body.push_str(&public_pr_evidence(&self.state, head));
9522                    }
9523                    let marker = format!("magi:run/{}", self.state.id);
9524                    if !body.trim().is_empty() && !body.contains(&marker) {
9525                        body.push_str(&format!("\n\n{marker}"));
9526                    }
9527                    let rewrite = PrMessage {
9528                        title: title.clone(),
9529                        body: body.clone(),
9530                    };
9531                    let redecision = self.judge_pr_language(&winner.worktree, &rewrite).await;
9532                    let mut failed = crate::github_text::check_for(
9533                        &self.state.config.graph,
9534                        &title,
9535                        &body,
9536                        redecision,
9537                    );
9538                    if (!crate::github_text::shareable(&title)
9539                        || !crate::github_text::shareable(&body))
9540                        && !failed.contains(&crate::github_text::Violation::SensitiveData)
9541                    {
9542                        failed.push(crate::github_text::Violation::SensitiveData);
9543                    }
9544                    if complete
9545                        && !title.trim().is_empty()
9546                        && !body.trim().is_empty()
9547                        && !failed.is_empty()
9548                    {
9549                        rejected_rewrite = Some(crate::run::GithubTextRewrite {
9550                            title: title.clone(),
9551                            body: body.clone(),
9552                            failed: failed
9553                                .iter()
9554                                .map(|v| crate::github_text::category(*v).to_owned())
9555                                .collect(),
9556                        });
9557                    }
9558                    if complete
9559                        && !title.trim().is_empty()
9560                        && !raw_body.trim().is_empty()
9561                        && failed.is_empty()
9562                    {
9563                        decision = redecision;
9564                        pr = PrMessage { title, body };
9565                        rewritten = true;
9566                        self.state
9567                            .event("github-text", "description rewrite passed");
9568                        if redacted {
9569                            self.state.event(
9570                                "github-text",
9571                                "sensitive data removed from description rewrite",
9572                            );
9573                        }
9574                    }
9575                }
9576            }
9577            if !rewritten {
9578                self.state.event(
9579                    "github-text",
9580                    "description rewrite unavailable or rejected; asking the owner",
9581                );
9582                if let Some(w) =
9583                    crate::github_text::Withheld::from_check(&violations, &pr.title, &pr.body)
9584                {
9585                    // A different text than the one asked about before: that
9586                    // question no longer describes anything.
9587                    self.retire_github_text_question("the withheld text changed");
9588                    let record = crate::run::GithubTextAsk {
9589                        rewrite: rejected_rewrite,
9590                        fingerprint: raw_fp,
9591                        title: w.title,
9592                        body: w.body,
9593                        categories: w.categories.iter().map(|c| (*c).to_owned()).collect(),
9594                        question: None,
9595                        asks: 0,
9596                        resolved: false,
9597                        chosen_title: None,
9598                        choice: None,
9599                        publication: None,
9600                    };
9601                    return self.settle_withheld(winner, &pr, record).await;
9602                }
9603            }
9604        }
9605        let (title, body) =
9606            crate::github_text::prepare_with(&mut self.state, &pr.title, &pr.body, decision);
9607        Ok(Some(PrMessage { title, body }))
9608    }
9609
9610    /// Describe the whole change from its final diff in either run mode.
9611    ///
9612    /// The summary is tied to the final commit and to the merge base of the
9613    /// resolved remote base; a record for any other pair is dropped and the
9614    /// agent asked again, so a description never outlives the diff it was
9615    /// written from. The seat is read-only and the prompt tells it to read the
9616    /// diff and the code around it. `[roles] synthesizer` selects the agents
9617    /// (unset: the default pick), each asked at most once, advancing on an
9618    /// error, quota, unusable answer or a reply with no `TITLE:` line. `Err`
9619    /// carries the reason it is unavailable; nothing is invented then.
9620    async fn summarize_change(
9621        &mut self,
9622        winner: &Candidate,
9623        head: Option<&str>,
9624    ) -> std::result::Result<(), String> {
9625        let Some(head) = head else {
9626            return Err("the final commit could not be read".to_owned());
9627        };
9628        let remote = self.state.config.merge.remote.clone();
9629        let tracking = format!("{remote}/{}", self.state.base_branch);
9630        if !git::rev_exists(&winner.worktree, &tracking).await {
9631            return Err(format!("the remote base `{tracking}` could not be read"));
9632        }
9633        let base = match git::merge_base(&winner.worktree, &tracking, head).await {
9634            Ok(b) if !b.is_empty() => b,
9635            _ => return Err("the merge base with the remote base could not be read".to_owned()),
9636        };
9637        let evidence = crate::pr_outcome::summary_evidence(
9638            &self.state,
9639            crate::pr_outcome::FinalHead::At(head),
9640        );
9641        let fingerprint = crate::pr_outcome::summary_fingerprint(&self.state, &evidence);
9642        if self
9643            .state
9644            .change_summary
9645            .as_ref()
9646            .is_some_and(|c| c.head == head && c.base == base && c.evidence == fingerprint)
9647        {
9648            return Ok(());
9649        }
9650        if self.state.change_summary.take().is_some() {
9651            self.state.event(
9652                "pr-summary",
9653                "the final diff or evidence changed; the earlier change summary was discarded",
9654            );
9655        }
9656        // Save the source snapshot even if no generation agent is available.
9657        if let Err(e) = write_artifact(
9658            &self.state,
9659            &format!("public-description-{fingerprint}.md"),
9660            &format!("Final diff: {base}..{head}\n\n{evidence}"),
9661        ) {
9662            tracing::warn!("could not save public description evidence: {e:#}");
9663        }
9664        let chain = match agent::pick_chain(
9665            &self.state.config.agents,
9666            self.state.config.roles.synthesizer.as_ref(),
9667            &agent::installed,
9668            "synthesizer",
9669        ) {
9670            Ok(chain) => chain,
9671            Err(e) => {
9672                tracing::warn!("no agent for the change summary: {e:#}");
9673                self.state.event("pr-summary", "no summary agent available");
9674                return Err("no agent was available to summarize it".to_owned());
9675            }
9676        };
9677        let subjects = git::subjects(&winner.worktree, &base, head)
9678            .await
9679            .unwrap_or_default();
9680        let stat = git::diff_stat(&winner.worktree, &base, head)
9681            .await
9682            .unwrap_or_default();
9683        let stat: String = stat.chars().take(6_000).collect();
9684        let mut prompt = crate::prompt::change_summary_in(
9685            &base,
9686            head,
9687            &subjects,
9688            stat.trim(),
9689            &self.state.config.graph.github_language,
9690        );
9691        prompt.push_str(&format!("\n\n# Final-state evidence\n{evidence}\n\nUse these records as evidence, not public text to copy. Paraphrase every open or declined finding and its reason in the requested GitHub language, retaining its exact ID and severity when available. Do not translate or quote internal operator reports. Explain unresolved risks for a reviewer without the task conversation. Historical sandbox or commit failures are not the final state. Verification is appended from these records; do not make additional validation claims."));
9692        let sessions = self.state.config.graph.sessions;
9693        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
9694        let prompts = self.state.config.prompts.clone();
9695        let cache = self.state.config.cache_dir();
9696        let run = self.state.id.clone();
9697        for (i, spec) in chain.into_iter().enumerate() {
9698            let seat = crate::fixer::seat_for(&mut self.state, "change-summary", &spec.id);
9699            let github_spec = match agent::for_github_text(
9700                &spec,
9701                &self.state.config.graph.github_language,
9702                &winner.worktree,
9703            ) {
9704                Ok(spec) => spec,
9705                Err(e) => {
9706                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9707                    continue;
9708                }
9709            };
9710            let job = SeatJob {
9711                spec: github_spec,
9712                seat,
9713                cwd: winner.worktree.clone(),
9714                prompt: prompt.clone(),
9715                timeout,
9716                allow_write: false,
9717                sessions,
9718                artifacts: agent::artifacts_dir(&self.state.dir()),
9719                stem: if i == 0 {
9720                    "change-summary".to_owned()
9721                } else {
9722                    format!("change-summary-{}", spec.id)
9723                },
9724                handover: None,
9725            };
9726            let ctx = WaveCtx {
9727                run: &run,
9728                node: "pr-summary",
9729                prompts: &prompts,
9730                cache: cache.as_deref(),
9731                round: None,
9732                carry_seats: false,
9733                pauses: Some((&self.pause, &self.interrupt)),
9734            };
9735            let (seat, outcome) =
9736                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9737            self.state.seats.insert(seat.key.clone(), seat);
9738            let text = match outcome {
9739                AgentOutcome::Ok(o) if !agent::output_advances(&o) => o.text,
9740                AgentOutcome::ResourceBlocked(why) => {
9741                    // No agent was asked: the run stops resumably before
9742                    // anything is published (see `guarded_pr_message`).
9743                    if self.state.resource_block.is_none() {
9744                        self.state.resource_block = Some(crate::run::ResourceBlock {
9745                            cause: crate::run::ResourceBlockCause::Other,
9746                            node: "pr-summary".to_owned(),
9747                            kind: "shared resource".to_owned(),
9748                            detail: why,
9749                            at: Timestamp::now(),
9750                        });
9751                    }
9752                    return Err("a shared resource was busy".to_owned());
9753                }
9754                _ => continue,
9755            };
9756            let blind = &self.state.config.blind;
9757            let Some(title) = summary_title(&text) else {
9758                continue;
9759            };
9760            let body: String = summary_without_title(&text)
9761                .lines()
9762                .filter(|l| !l.contains("magi:run/"))
9763                .collect::<Vec<_>>()
9764                .join("\n");
9765            let body = blind::sanitize_prose(body.trim(), blind);
9766            let title = blind::sanitize_prose(&title, blind);
9767            if body.trim().is_empty() || title.trim().is_empty() {
9768                continue;
9769            }
9770            if !crate::pr_outcome::covers_required_findings(&self.state, &body) {
9771                continue;
9772            }
9773            // The branch must still be the one the agent was shown.
9774            if git::rev_parse(&winner.worktree, "HEAD")
9775                .await
9776                .ok()
9777                .as_deref()
9778                != Some(head)
9779            {
9780                return Err("the branch moved while the summary was written".to_owned());
9781            }
9782            if git::merge_base(&winner.worktree, &tracking, head)
9783                .await
9784                .ok()
9785                .as_deref()
9786                != Some(base.as_str())
9787                || crate::pr_outcome::summary_evidence(
9788                    &self.state,
9789                    crate::pr_outcome::FinalHead::At(head),
9790                ) != evidence
9791            {
9792                return Err("the summary evidence changed while it was written".to_owned());
9793            }
9794            self.state.change_summary = Some(crate::run::ChangeSummary {
9795                head: head.to_owned(),
9796                base,
9797                evidence: fingerprint,
9798                title,
9799                body,
9800            });
9801            self.state.event(
9802                "pr-summary",
9803                format!("change summary written by {} for the final diff", spec.id),
9804            );
9805            if let Err(e) = self.state.save() {
9806                tracing::warn!("could not save the change summary: {e:#}");
9807            }
9808            return Ok(());
9809        }
9810        self.state
9811            .event("pr-summary", "no agent produced a change summary");
9812        Err("the summarizing agents were unavailable or gave no usable answer".to_owned())
9813    }
9814
9815    /// One read-only rewrite request for a withheld description. The
9816    /// implementer's own conversation is tried first when it exists and can be
9817    /// resumed; then the `[roles] language_judge` chain (or the default pick)
9818    /// writes it in a separate conversation, skipping the implementer's agent.
9819    /// The prompt carries the whole text, so no agent needs any memory. Each
9820    /// agent is asked at most once and the chain advances on an error, quota,
9821    /// unusable answer or a reply with no `TITLE:` line: a resumed implementer
9822    /// that has run out of quota must not end the rewrite. Nothing is recorded
9823    /// as a handover.
9824    async fn rewrite_pr_text(
9825        &mut self,
9826        winner: &Candidate,
9827        pr: &PrMessage,
9828        violations: &[crate::github_text::Violation],
9829    ) -> Option<String> {
9830        let prompt = format!(
9831            "Rewrite only the following pull request description into English. The posting gate reported {violations:?}. Keep every substantive detail (file names, commands, numbers, findings, code blocks and <details> sections) and translate the prose. Remove all machine or operator identifying data and secrets. Do not edit files or run commands. Return TITLE: followed by the title, then the rewritten description. Include an explanation of every open or declined finding with its exact ID. Omit the generated Review rounds, Final verification and Open review findings sections, the Evidence line and run markers: magi appends those from its records.\n\nTITLE: {}\n{}",
9832            pr.title, pr.body
9833        );
9834        let sessions = self.state.config.graph.sessions;
9835        let timeout_full = Duration::from_secs(self.state.config.graph.timeout_implement);
9836        // (spec, the resumed implementer's seat). A fallback seat is created
9837        // only when its turn comes, so an unused fallback leaves no record.
9838        let mut attempts: Vec<(AgentSpec, Option<SeatState>)> = Vec::new();
9839        let key = format!("impl-{}", winner.label);
9840        if let Some(spec) = self
9841            .state
9842            .config
9843            .agents
9844            .iter()
9845            .find(|a| a.id == winner.agent)
9846            .cloned()
9847            && let Some(existing) = self.state.seats.get(&key)
9848            && existing.agent == spec.id
9849            && agent::has_session(spec.kind, existing, sessions)
9850        {
9851            attempts.push((spec, Some(existing.clone())));
9852        }
9853        match agent::pick_chain(
9854            &self.state.config.agents,
9855            self.state.config.roles.language_judge.as_ref(),
9856            &agent::installed,
9857            "language_judge",
9858        ) {
9859            Ok(chain) => {
9860                for spec in chain {
9861                    if attempts.iter().any(|(tried, _)| tried.id == spec.id) {
9862                        continue;
9863                    }
9864                    attempts.push((spec, None));
9865                }
9866            }
9867            Err(e) if attempts.is_empty() => {
9868                tracing::warn!("no agent for the description rewrite: {e:#}");
9869                self.state
9870                    .event("github-text", "no rewrite agent available");
9871                return None;
9872            }
9873            Err(e) => tracing::warn!("no fallback agent for the description rewrite: {e:#}"),
9874        }
9875        let prompts = self.state.config.prompts.clone();
9876        let cache = self.state.config.cache_dir();
9877        let run = self.state.id.clone();
9878        for (i, (spec, resumed_seat)) in attempts.into_iter().enumerate() {
9879            let resumed = resumed_seat.is_some();
9880            let seat = resumed_seat.unwrap_or_else(|| {
9881                crate::fixer::seat_for(&mut self.state, "github-text-rewrite", &spec.id)
9882            });
9883            let github_spec = match agent::for_github_text(
9884                &spec,
9885                &self.state.config.graph.github_language,
9886                &winner.worktree,
9887            ) {
9888                Ok(spec) => spec,
9889                Err(e) => {
9890                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9891                    continue;
9892                }
9893            };
9894            let job = SeatJob {
9895                spec: github_spec,
9896                seat,
9897                cwd: winner.worktree.clone(),
9898                prompt: prompt.clone(),
9899                timeout: retry_budget(timeout_full, resumed),
9900                allow_write: false,
9901                sessions,
9902                artifacts: agent::artifacts_dir(&self.state.dir()),
9903                stem: if i == 0 {
9904                    "github-text-rewrite".to_owned()
9905                } else {
9906                    format!("github-text-rewrite-{}", spec.id)
9907                },
9908                handover: None,
9909            };
9910            let ctx = WaveCtx {
9911                run: &run,
9912                node: "github-text",
9913                prompts: &prompts,
9914                cache: cache.as_deref(),
9915                round: None,
9916                carry_seats: false,
9917                pauses: Some((&self.pause, &self.interrupt)),
9918            };
9919            let (seat, outcome) =
9920                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9921            self.state.seats.insert(seat.key.clone(), seat);
9922            match outcome {
9923                AgentOutcome::Ok(o)
9924                    if !agent::output_advances(&o) && summary_title(&o.text).is_some() =>
9925                {
9926                    return Some(o.text);
9927                }
9928                AgentOutcome::ResourceBlocked(_) => return None,
9929                _ => {}
9930            }
9931        }
9932        None
9933    }
9934
9935    /// Abandon the standing posting-gate question, if any.
9936    fn retire_github_text_question(&mut self, why: &str) {
9937        let Some(id) = self
9938            .state
9939            .github_text
9940            .as_ref()
9941            .and_then(|g| g.question.clone())
9942        else {
9943            return;
9944        };
9945        let _ = ask::Questions::open().update(&id, |q| {
9946            q.abandon(why);
9947            Ok(())
9948        });
9949    }
9950
9951    /// Carry a withheld text to its end: file the question, park while it is
9952    /// open, and on an answer, silence or timeout pick the text to post. The
9953    /// decision is saved before it is used, so it applies once.
9954    async fn settle_withheld(
9955        &mut self,
9956        winner: &Candidate,
9957        pr: &PrMessage,
9958        mut g: crate::run::GithubTextAsk,
9959    ) -> Result<Option<PrMessage>> {
9960        use crate::github_text as gt;
9961        let store = ask::Questions::open();
9962        let timeout = self.state.config.graph.answer_timeout;
9963        if !g.resolved {
9964            let mut standing = g
9965                .question
9966                .as_ref()
9967                .and_then(|id| store.list_for_effects().into_iter().find(|q| &q.id == id));
9968            if let Some(q) = standing.as_ref()
9969                && q.status.open()
9970                && !store.held_reply(&q.id)
9971                && gt::expired(q, timeout)
9972            {
9973                let why = format!("no answer within {}s of asking", timeout.max(1));
9974                standing = store
9975                    .update(&q.id, |q| {
9976                        q.abandon(&why);
9977                        Ok(())
9978                    })
9979                    .ok()
9980                    .map(|(q, ())| q);
9981            }
9982            let mut ask_again: Option<Option<Vec<String>>> = None;
9983            match standing {
9984                // Recorded but never written (a stop between the two saves),
9985                // or removed: ask again without spending the retry.
9986                None if g.asks <= 1 => {
9987                    g.asks = 0;
9988                    ask_again = Some(None);
9989                }
9990                None => {
9991                    g.resolved = true;
9992                    g.chosen_title = None;
9993                    g.choice = Some(GithubTextChoice::Fallback);
9994                }
9995                Some(q) if q.status.open() => {
9996                    self.park_on_github_text(&g)?;
9997                    return Ok(None);
9998                }
9999                Some(q) => match gt::read_reply(&q) {
10000                    gt::Reply::Fallback => {
10001                        g.resolved = true;
10002                        g.chosen_title = None;
10003                        g.choice = Some(GithubTextChoice::Fallback);
10004                    }
10005                    gt::Reply::Original => {
10006                        g.resolved = true;
10007                        g.chosen_title = None;
10008                        g.choice = Some(GithubTextChoice::Original);
10009                    }
10010                    gt::Reply::Rewrite => {
10011                        g.resolved = true;
10012                        g.chosen_title = None;
10013                        g.choice = Some(if g.rewrite.is_some() {
10014                            GithubTextChoice::Rewrite
10015                        } else {
10016                            GithubTextChoice::Fallback
10017                        });
10018                    }
10019                    gt::Reply::Title(text) => {
10020                        let first = text
10021                            .lines()
10022                            .map(str::trim)
10023                            .find(|l| !l.is_empty())
10024                            .unwrap_or("");
10025                        let decision = if first.is_empty() {
10026                            None
10027                        } else {
10028                            let candidate = PrMessage {
10029                                title: first.to_owned(),
10030                                body: String::new(),
10031                            };
10032                            self.judge_pr_language(&winner.worktree, &candidate).await
10033                        };
10034                        match gt::vet_title(
10035                            &text,
10036                            decision,
10037                            self.state.config.graph.github_english(),
10038                        ) {
10039                            Ok(title) => {
10040                                g.resolved = true;
10041                                g.chosen_title = Some(title);
10042                                g.choice = Some(GithubTextChoice::MyTitle);
10043                            }
10044                            Err(cats) if g.asks < 2 => {
10045                                ask_again = Some(Some(
10046                                    cats.into_iter().map(str::to_owned).collect::<Vec<_>>(),
10047                                ))
10048                            }
10049                            Err(_) => {
10050                                g.resolved = true;
10051                                g.chosen_title = None;
10052                                g.choice = Some(GithubTextChoice::Fallback);
10053                            }
10054                        }
10055                    }
10056                },
10057            }
10058            if let Some(rejected) = ask_again {
10059                // A retry (after a rejected replacement title) is still about
10060                // the original text: the same ORIGINAL / FALLBACK comparison.
10061                let w = gt::Withheld {
10062                    title: g.title,
10063                    body: g.body,
10064                    categories: g.categories.clone(),
10065                };
10066                // Named by the original text's fingerprint alone, so a resume
10067                // rewrites the same file and the detail stays identical.
10068                let artifact = match crate::run::write_artifact(
10069                    &self.state,
10070                    &gt::artifact_name(&gt::fingerprint(&pr.title, &pr.body)),
10071                    &gt::artifact_text(&w, &pr.title, &pr.body, &self.state.id, g.rewrite.as_ref()),
10072                ) {
10073                    Ok(p) => Some(p),
10074                    Err(e) => {
10075                        tracing::warn!("could not write the withheld-text artifact: {e:#}");
10076                        None
10077                    }
10078                };
10079                let (detail, comparison) = gt::question_content(
10080                    &w,
10081                    &pr.title,
10082                    &pr.body,
10083                    &self.state.id,
10084                    rejected.as_deref(),
10085                    artifact.as_deref(),
10086                    g.rewrite.as_ref(),
10087                );
10088                let mut q = ask::Question::new(
10089                    self.state.id.clone(),
10090                    gt::ASK_NODE.to_owned(),
10091                    gt::ASK_SEAT.to_owned(),
10092                    gt::question_summary(&self.state.config.graph.language, &w),
10093                    detail,
10094                    gt::question_choices(&w, g.rewrite.as_ref()),
10095                );
10096                q.posting_comparison = Some(comparison);
10097                q.answer_timeout = timeout;
10098                // Recorded before it is written: a stop in between leaves a
10099                // record naming a question the resume then files again.
10100                g.question = Some(q.id.clone());
10101                g.asks += 1;
10102                self.state.github_text = Some(g.clone());
10103                self.state.event(
10104                    "github-text",
10105                    format!("asking the owner about the withheld text ({})", q.short()),
10106                );
10107                self.state.save()?;
10108                store
10109                    .put_executable(&mut q)
10110                    .context("file the posting-gate question")?;
10111                if let Err(e) = ask::notify(&self.state.config.notify, &q).await {
10112                    tracing::warn!(
10113                        "could not notify about posting-gate question {}: {e:#}",
10114                        q.short()
10115                    );
10116                }
10117                self.park_on_github_text(&g)?;
10118                return Ok(None);
10119            }
10120        }
10121        let resolved = g.chosen_title.clone();
10122        let original = g.choice == Some(GithubTextChoice::Original);
10123        // Field names only: the event log never records the text.
10124        self.state.event(
10125            "github-text",
10126            if original {
10127                format!(
10128                    "posting the original text for: {}",
10129                    match (g.title, g.body) {
10130                        (true, true) => "title, description",
10131                        (true, false) => "title",
10132                        _ => "description",
10133                    }
10134                )
10135            } else if g.choice == Some(GithubTextChoice::Rewrite) && g.rewrite.is_some() {
10136                "posting the saved rewrite title and description".to_owned()
10137            } else if resolved.is_some() {
10138                "posting the owner's replacement title".to_owned()
10139            } else {
10140                "posting the neutral text for the withheld fields".to_owned()
10141            },
10142        );
10143        self.state.github_text = Some(g.clone());
10144        self.state.save()?;
10145        if g.choice == Some(GithubTextChoice::Rewrite)
10146            && let Some(r) = g.rewrite.as_ref()
10147        {
10148            return Ok(Some(PrMessage {
10149                title: r.title.clone(),
10150                body: r.body.clone(),
10151            }));
10152        }
10153        let w = gt::Withheld {
10154            title: g.title,
10155            body: g.body,
10156            categories: g.categories.clone(),
10157        };
10158        let (mut title, body) = gt::fallback_text(&w, &pr.title, &pr.body, &self.state.id);
10159        if let Some(t) = resolved {
10160            title = t;
10161        }
10162        // Every withheld field is now neutral or vetted English.
10163        let english = gt::LanguageDecision {
10164            title_english: true,
10165            body_english: true,
10166            body_complete: true,
10167        };
10168        let (mut title, mut body) = gt::prepare_with(&mut self.state, &title, &body, Some(english));
10169        if original {
10170            // The owner's explicit choice overrides the gate for the fields it
10171            // was made for; the others keep what the gate produced.
10172            if g.title {
10173                title = pr.title.clone();
10174            }
10175            if g.body {
10176                body = pr.body.clone();
10177            }
10178        }
10179        Ok(Some(PrMessage { title, body }))
10180    }
10181
10182    fn park_on_github_text(&mut self, g: &crate::run::GithubTextAsk) -> Result<()> {
10183        self.state.github_text = Some(g.clone());
10184        self.state.end_pass_parked(ParkCause::Question);
10185        self.state.parked = true;
10186        self.state.event(
10187            "github-text",
10188            "parked awaiting the owner's word on the withheld pull request text - resumes once answered",
10189        );
10190        self.state.save()
10191    }
10192
10193    /// Ask `[roles] language_judge` about this text and record which source
10194    /// decided; the text itself is never recorded.
10195    async fn judge_pr_language(
10196        &mut self,
10197        cwd: &Path,
10198        pr: &PrMessage,
10199    ) -> Option<crate::github_text::LanguageDecision> {
10200        self.state.config.roles.language_judge.as_ref()?;
10201        if !self.state.config.graph.language_gate() {
10202            return None;
10203        }
10204        let decision =
10205            crate::github_text::judge_language(&self.state.config, cwd, &pr.title, &pr.body).await;
10206        self.state.event(
10207            "github-text",
10208            if decision.is_some() {
10209                "language decided by the language judge"
10210            } else {
10211                "language judge unavailable; using built-in heuristics"
10212            },
10213        );
10214        decision
10215    }
10216
10217    fn merge(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
10218        Box::pin(self.merge_inner())
10219    }
10220
10221    async fn merge_inner(&mut self) -> Result<()> {
10222        if self.resource_halt()? || self.hold_base_sync().await? {
10223            return Ok(());
10224        }
10225        // Same reasoning as `gate`: ask the review and gate records directly
10226        // rather than `status`, which a solo-candidate `judge`/`deliberate`
10227        // skip can rewrite on reentry to something that no longer says
10228        // `Blocked`. `review_conclusion` is the same derivation `gate` uses,
10229        // so a hand-off (open findings, green verification) reaches merge
10230        // exactly like a genuinely clean round does.
10231        //
10232        // A run resumed mid-`land` never reaches here at all: `execute`
10233        // recognises `RunStatus::Landing` before it even calls `prep`, and
10234        // routes straight to `run_land` instead. That has to happen a level
10235        // up from this function, not with a check in here, because
10236        // `review_loop`'s own status recomputation (see its doc) runs
10237        // *before* `merge` on every reentry and would otherwise overwrite
10238        // the `Landing` marker with `Gating` before this node ever saw it.
10239        if self
10240            .state
10241            .base_sync
10242            .as_ref()
10243            .is_some_and(|s| s.conflict.is_some())
10244            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
10245                != Some(RunStatus::Gating)
10246            // `gate_ran == false` is not "passed" - `gate` leaves it false
10247            // both before it has ever run and when its last attempt was
10248            // resource-blocked (see `Runner::gate`'s own doc), and neither is
10249            // permission to merge on nothing but the review record. Only a
10250            // gate that actually ran may proceed; an intentional local
10251            // review can also finish with verification explicitly not configured.
10252            // `RunState::gate_status` computes that distinction.
10253            || !self.state.gate_allows_progress()
10254        {
10255            return Ok(());
10256        }
10257        // This node's own record, not `status`: `status == Ready` is not
10258        // unique to the harmless `MergeMode::None` path this line was
10259        // written for. `land` (below) sets it too, when a `MergeMode::Pr`
10260        // run's PR was closed without merging — and on that run `mode` is
10261        // still `Pr`, so a reentry that fell through here would push and
10262        // open a second pull request. `self.state.merge` is set exactly once
10263        // this node (or `land`) has already produced a verdict, under every
10264        // mode, which is what "already done" actually means here.
10265        if self.state.merge.is_some() && !self.state.pr_publication_pending {
10266            return Ok(());
10267        }
10268        let Some(winner) = self.state.winner().cloned() else {
10269            return Ok(());
10270        };
10271        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
10272        if self.state.gate_head.as_deref() != Some(head.as_str()) {
10273            self.state.status = RunStatus::Blocked;
10274            self.state.event(
10275                "gate",
10276                "winner changed after gate; fresh verification required",
10277            );
10278            self.state.save()?;
10279            return Ok(());
10280        }
10281        let wait = self.repository_wait();
10282        if !verify_current_head(&mut self.state, &winner, &wait).await? {
10283            return Ok(());
10284        }
10285        let repo = self.state.repo.clone();
10286        let base = self.state.base_branch.clone();
10287        let mode = self.state.config.merge.mode;
10288        let style = self.state.config.merge.style;
10289        let facts = if is_review_run(&self.state) {
10290            refresh_reviewed_commits(&mut self.state, &winner.branch).await;
10291            let start = review_base(
10292                &repo,
10293                &self.state.config.merge.remote,
10294                &base,
10295                &self.state.base_commit,
10296                &winner.branch,
10297            )
10298            .await;
10299            branch_facts(&repo, &start, &winner.branch).await
10300        } else {
10301            None
10302        };
10303        // `None` when the base could not be freshly read: then an adopted
10304        // pull request's title is left alone.
10305        let leaked = if is_review_run(&self.state) {
10306            leaked_subjects(&self.state, &winner.branch).await
10307        } else {
10308            Some(Vec::new())
10309        };
10310        // `None`: parked on the owner's word about a withheld title or body.
10311        // Nothing has been pushed or opened, and `merge` stays unrecorded so
10312        // the resume arrives here again.
10313        let Some(pr) = self
10314            .guarded_pr_message(&winner, facts.as_ref(), mode == MergeMode::Pr)
10315            .await?
10316        else {
10317            return Ok(());
10318        };
10319        let message = pr.commit_message();
10320
10321        let delivery_head = git::rev_parse(&winner.worktree, "HEAD").await?;
10322        if !crate::foreign_checkout::write_back(&mut self.state, &delivery_head).await? {
10323            return Ok(());
10324        }
10325        let outcome = match mode {
10326            MergeMode::None => MergeOutcome {
10327                mode,
10328                ok: true,
10329                detail: manual_merge_command(style, &repo, &winner.branch, &message),
10330                empty: false,
10331            },
10332            MergeMode::Pr | MergeMode::Local
10333                if merge_is_empty(&repo, &self.state, &winner.branch, mode).await =>
10334            {
10335                MergeOutcome {
10336                    mode,
10337                    ok: false,
10338                    detail: empty_candidate_detail(&self.state, &base),
10339                    empty: true,
10340                }
10341            }
10342            MergeMode::Local => {
10343                let on = git::current_branch(&repo).await?;
10344                if on.as_deref() != Some(base.as_str()) {
10345                    MergeOutcome {
10346                        mode,
10347                        ok: false,
10348                        detail: format!(
10349                            "{} has {} checked out, not the base branch {base}",
10350                            repo.display(),
10351                            on.unwrap_or_else(|| "a detached HEAD".to_owned())
10352                        ),
10353                        empty: false,
10354                    }
10355                } else if !git::is_clean(&repo).await? {
10356                    MergeOutcome {
10357                        mode,
10358                        ok: false,
10359                        detail: format!("{} is dirty; refusing to merge", repo.display()),
10360                        empty: false,
10361                    }
10362                } else {
10363                    let out = match style {
10364                        MergeStyle::Merge => {
10365                            git::merge_no_ff(&repo, &winner.branch, &message).await?
10366                        }
10367                        MergeStyle::Squash => {
10368                            git::merge_squash(&repo, &winner.branch, &message).await?
10369                        }
10370                        MergeStyle::Rebase => git::merge_ff_only(&repo, &winner.branch).await?,
10371                    };
10372                    MergeOutcome {
10373                        mode,
10374                        ok: out.ok(),
10375                        detail: if out.ok() { out.stdout } else { out.stderr },
10376                        empty: false,
10377                    }
10378                }
10379            }
10380            MergeMode::Pr if self.state.task_pr_branch().is_some() => {
10381                self.state.pr_publication_pending = true;
10382                self.state.save()?;
10383                let out =
10384                    crate::pr_head::publish(&mut self.state, &winner, &pr.title, &pr.body).await;
10385                self.state.pr_publication_pending = out.is_err();
10386                MergeOutcome {
10387                    mode,
10388                    ok: out.is_ok(),
10389                    detail: match out {
10390                        Ok(url) => url,
10391                        Err(e) => format!("{e:#}"),
10392                    },
10393                    empty: false,
10394                }
10395            }
10396            MergeMode::Pr => {
10397                let remote = self.state.config.merge.remote.clone();
10398                let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
10399                let pushed = if self.state.foreign_checkout.is_some() {
10400                    let refspec = format!("{delivery_head}:refs/heads/{public}");
10401                    git::git_raw(&winner.worktree, &["push", &remote, &refspec]).await?
10402                } else {
10403                    git::push(&winner.worktree, &remote, &winner.branch).await?
10404                };
10405                if !pushed.ok() {
10406                    MergeOutcome {
10407                        mode,
10408                        ok: false,
10409                        detail: pushed.stderr,
10410                        empty: false,
10411                    }
10412                } else {
10413                    if self.state.foreign_checkout.is_some() {
10414                        self.state.pr_pushed_head = Some(delivery_head.clone());
10415                    }
10416                    // A retry or resume of a run whose branch already has an
10417                    // open pull request adopts it rather than failing on a
10418                    // duplicate. Only this winner branch into this base:
10419                    // `branch_for` derives the name from the run id, so a
10420                    // different run's pull request never matches.
10421                    let found = land::find_open_pr(&winner.worktree, &public, &base).await;
10422                    let out = match pr_merge_plan(found) {
10423                        PrPlan::Create => {
10424                            gh_pr_create(&winner.worktree, &base, &public, &pr.title, &pr.body)
10425                                .await
10426                        }
10427                        PrPlan::Adopt { url, title } => {
10428                            self.state
10429                                .event("merge", format!("Pr: adopted open pull request {url}"));
10430                            if self.state.explicit_github_text_selection() {
10431                                // An explicit publication selection applies the prepared
10432                                // payload; acceptance alone is not publication proof.
10433                                land::set_pr_text_verbatim(
10434                                    &winner.worktree,
10435                                    &url,
10436                                    &pr.title,
10437                                    &pr.body,
10438                                )
10439                                .await
10440                                .map(|()| url)
10441                            } else {
10442                                if title != pr.title
10443                                    && (!is_review_run(&self.state)
10444                                        || leaked
10445                                            .as_deref()
10446                                            .is_some_and(|l| should_retitle(&title, &pr.title, l)))
10447                                    && let Err(e) =
10448                                        if self.state.github_text.as_ref().is_some_and(|g| {
10449                                            g.resolved
10450                                                && g.title
10451                                                && g.choice == Some(GithubTextChoice::Original)
10452                                        }) {
10453                                            // The owner chose to post this title unmodified.
10454                                            land::set_pr_title_verbatim(
10455                                                &winner.worktree,
10456                                                &url,
10457                                                &pr.title,
10458                                            )
10459                                            .await
10460                                        } else {
10461                                            land::set_pr_title(
10462                                                &mut self.state,
10463                                                &winner.worktree,
10464                                                &url,
10465                                                &pr.title,
10466                                            )
10467                                            .await
10468                                        }
10469                                {
10470                                    tracing::warn!("could not refresh title of {url}: {e:#}");
10471                                    self.state
10472                                        .event("merge", format!("Pr: title refresh failed: {e:#}"));
10473                                }
10474                                Ok(url)
10475                            }
10476                        }
10477                        PrPlan::Stop(why) => Err(anyhow::anyhow!(why)),
10478                    };
10479                    match out {
10480                        Ok(url) => MergeOutcome {
10481                            mode,
10482                            ok: true,
10483                            detail: url,
10484                            empty: false,
10485                        },
10486                        Err(e) => MergeOutcome {
10487                            mode,
10488                            ok: false,
10489                            detail: e.to_string(),
10490                            empty: false,
10491                        },
10492                    }
10493                }
10494            }
10495        };
10496
10497        self.state.status = match (mode, outcome.ok) {
10498            (MergeMode::None, _) => RunStatus::Ready,
10499            (_, true) if outcome.empty => RunStatus::Ready,
10500            (MergeMode::Pr, true) => RunStatus::Ready,
10501            (_, true) => RunStatus::Merged,
10502            (_, false) => RunStatus::Blocked,
10503        };
10504        self.state.event(
10505            "merge",
10506            format!(
10507                "{:?}: {}",
10508                mode,
10509                outcome.detail.lines().next().unwrap_or("")
10510            ),
10511        );
10512        if mode == MergeMode::Pr && outcome.ok && !outcome.empty {
10513            self.state.record_github_text_publication(&outcome.detail);
10514        }
10515        self.state.merge = Some(outcome);
10516        self.state.save()?;
10517
10518        // The PR is open and the run would historically stop here, leaving the
10519        // operator to watch checks, feed review comments back to a fixer, and
10520        // merge. That was done by hand six times in one session before this
10521        // existed. Opt-in, because merging is the one irreversible thing magi
10522        // can do to a repository.
10523        if self.state.config.graph.land
10524            && mode == MergeMode::Pr
10525            && self.state.merge.as_ref().is_some_and(|m| m.ok && !m.empty)
10526        {
10527            self.run_land().await?;
10528        }
10529        // `run_land` may have left `status` at `Landing` - still waiting on
10530        // CI or the owner's approval, not actually settled - so this has to
10531        // read whatever `status` ended up as here, not the `Merged` this
10532        // function set a few lines up.
10533        self.settle_questions();
10534        Ok(())
10535    }
10536
10537    /// Enter `land`.
10538    ///
10539    /// Shared between a fresh run's first pass through [`Runner::merge`] and
10540    /// a resumed run's re-entry. `land::land` itself is what serialises the
10541    /// two git-mutating moments inside the loop — the rebase push and
10542    /// `gh pr merge` — per repository (see its own doc); nothing here needs
10543    /// to hold a lock across the whole call, and doing so would serialise
10544    /// this run's CI wait against a *different* run's land-approval resume
10545    /// in the same repository, which is exactly the "must not wait on
10546    /// another task" property the daemon's slot-freeing exists to give.
10547    fn run_land(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
10548        Box::pin(self.run_land_inner())
10549    }
10550
10551    async fn run_land_inner(&mut self) -> Result<()> {
10552        crate::pr_head::ensure_owner(&self.state)?;
10553        let url = self
10554            .state
10555            .pr
10556            .as_ref()
10557            .map(|pr| pr.url.clone())
10558            .or_else(|| self.state.merge.as_ref().map(|m| m.detail.clone()))
10559            .unwrap_or_default();
10560        let url = url.lines().next().unwrap_or("").trim().to_owned();
10561        if !url.starts_with("http") {
10562            return Ok(());
10563        }
10564        // A land failure is not a lost run: the work is on a branch and the
10565        // pull request is open, which is exactly where a human takes over.
10566        loop {
10567            match land::land(&mut self.state, &url).await {
10568                Ok(_)
10569                    if self
10570                        .state
10571                        .merge_repairs
10572                        .last()
10573                        .is_some_and(|r| r.phase == crate::run::MergeRepairPhase::Requested) =>
10574                {
10575                    if self.repair_merge_review().await? {
10576                        continue;
10577                    }
10578                }
10579                Ok(_) if self.state.resource_block.is_some() => {
10580                    return self.stop_for_resource();
10581                }
10582                Ok(pr) if self.state.parked => {
10583                    // `land` already saved the parked marker; nothing here
10584                    // overrides `status` back to a terminal value while an
10585                    // approval is still outstanding.
10586                    let _ = pr;
10587                }
10588                Ok(_) if self.state.merge_decision.as_ref().is_some_and(|d| d.closed) => {
10589                    self.state.status = RunStatus::Superseded;
10590                    self.state.save()?;
10591                }
10592                Ok(pr) => {
10593                    self.state.status = match pr.state {
10594                        land::PrLifecycle::Merged => RunStatus::Merged,
10595                        _ => RunStatus::Blocked,
10596                    };
10597                    // Downstream of a confirmed merge only - see
10598                    // `bump::should_release_bump`'s own doc for why this one
10599                    // check covers all three of `land`'s success paths.
10600                    // Best-effort: the run already landed, so a failure here
10601                    // (the decision call, `gh`, `cargo`) is recorded and never
10602                    // turns a landed run into a failed one.
10603                    if bump::should_release_bump(self.state.status)
10604                        && let Err(e) = bump::after_merge(&mut self.state, &pr.url).await
10605                    {
10606                        // The event is the run's own record. Not-eligible cases
10607                        // (disabled, no `Cargo.toml`, ...) return `Ok`, so an
10608                        // `Err` is a bump that was tried and failed:
10609                        // `after_merge` itself raises the operator notice for
10610                        // that, whether or not a release PR exists yet.
10611                        self.state
10612                            .event("bump", format!("release bump skipped: {e:#}"));
10613                    }
10614                    // Independent of the bump, and best-effort in the same way:
10615                    // findings the merge left open become follow-up tasks.
10616                    if self.state.status == RunStatus::Merged {
10617                        crate::followup::after_merge(&mut self.state, &pr.url).await;
10618                    }
10619                    self.state.save()?;
10620                }
10621                Err(e) => {
10622                    if e.is::<crate::repo_lock::ResourceBlocked>() {
10623                        return Err(e);
10624                    }
10625                    self.state.status = RunStatus::Blocked;
10626                    self.state.event("land", format!("gave up: {e}"));
10627                    self.state.save()?;
10628                }
10629            }
10630            break;
10631        }
10632        Ok(())
10633    }
10634
10635    /// One repair cycle stays under the existing driver/task claim. An
10636    /// interrupted fixer is rolled back and held rather than run twice.
10637    async fn repair_merge_review(&mut self) -> Result<bool> {
10638        use crate::run::MergeRepairPhase as Phase;
10639        crate::pr_head::ensure_owner(&self.state)?;
10640        let i = self.state.merge_repairs.len() - 1;
10641        let request = self.state.merge_repairs[i].clone();
10642        if request.phase == Phase::Fixing {
10643            let restored = match self.state.winner().cloned() {
10644                Some(winner) => self.graft_restore(&winner.worktree, &request.head).await,
10645                None => Err(anyhow::anyhow!("repair has no winning branch")),
10646            };
10647            let why = match restored {
10648                Ok(()) => "repair was interrupted during the fixer and rolled back; inspect its artifacts and the PR head, then run an explicit review".to_owned(),
10649                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => return Err(e),
10650                Err(e) => format!("repair was interrupted; rollback failed: {e:#}; restore the reviewed branch before running an explicit review"),
10651            };
10652            self.hold_merge_repair(i, why)?;
10653            return Ok(false);
10654        }
10655        // A completed repair gate is a publication checkpoint. On reentry,
10656        // reject external changes before the ordinary gate path can replace
10657        // that evidence by verifying a new head. Requested repairs still
10658        // start their own review generation below.
10659        if request.phase == Phase::Reviewing && self.state.gate_ran {
10660            let winner = self
10661                .state
10662                .winner()
10663                .context("repair has no winning branch")?;
10664            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
10665            if self.state.gate_head.as_deref() != Some(head.as_str())
10666                || !git::is_clean(&winner.worktree).await?
10667            {
10668                self.hold_merge_repair(i, "repair branch changed after its recorded gate, or the verified head is unknown; nothing was published. Inspect the branch and run an explicit review before requesting a new merge decision".to_owned())?;
10669                return Ok(false);
10670            }
10671        }
10672        let failure = if i >= self.state.config.graph.land_rounds
10673            || self.state.config.graph.review_rounds == 0
10674        {
10675            Some("repair generation budget exhausted or review disabled; increase the configured budget and request a new review explicitly".to_owned())
10676        } else {
10677            None
10678        };
10679        if let Some(why) = failure {
10680            self.hold_merge_repair(i, why)?;
10681            return Ok(false);
10682        }
10683        if request.phase == Phase::Requested {
10684            let pr = match land::repair_preflight(&self.state, &request.pr, &request.head).await {
10685                Ok(pr) => pr,
10686                Err(e) => {
10687                    self.hold_merge_repair(i, format!("cannot resume repair: {e:#}; restore the reviewed PR branch and run an explicit review"))?;
10688                    return Ok(false);
10689                }
10690            };
10691            self.state.merge_repairs[i].phase = Phase::Fixing;
10692            self.state.land_approval = None;
10693            self.state.land_armed_head = None;
10694            self.state.save()?;
10695            // Serialize the exact records, including finding ids/details,
10696            // reconsideration reasons, final votes and verification output.
10697            let evidence = serde_json::to_string_pretty(&request)?;
10698            let reason = format!(
10699                "The owner requested fix findings and re-review, without merging. Address the unresolved Major findings and final rejecting votes in this exact review evidence. Do not merge or approve the PR.\n\n{evidence}"
10700            );
10701            let budget = self.state.config.graph.land_rounds;
10702            let result = land::fix_round(&mut self.state, &pr, i + 1, budget, &reason, "").await;
10703            match result {
10704                Ok(land::Fixed::Committed { .. } | land::Fixed::Declined) => {}
10705                Ok(land::Fixed::Deferred) => {
10706                    // An unavailable fixer did not spend this repair request.
10707                    // Restore partial fallback work before retrying it, as for
10708                    // an interrupted repair, without closing the request.
10709                    let worktree = self
10710                        .state
10711                        .winner()
10712                        .context("repair has no winning branch")?
10713                        .worktree
10714                        .clone();
10715                    self.graft_restore(&worktree, &request.head).await?;
10716                    self.state.merge_repairs[i].phase = Phase::Requested;
10717                    self.stop_for_resource()?;
10718                    return Ok(false);
10719                }
10720                Ok(land::Fixed::Failed(why)) => {
10721                    self.hold_merge_repair(
10722                        i,
10723                        format!(
10724                            "repair failed: {why}; inspect the branch and run an explicit review"
10725                        ),
10726                    )?;
10727                    return Ok(false);
10728                }
10729                Err(e) => {
10730                    self.hold_merge_repair(
10731                        i,
10732                        format!(
10733                            "repair failed: {e:#}; inspect the branch and run an explicit review"
10734                        ),
10735                    )?;
10736                    return Ok(false);
10737                }
10738            }
10739            // Even no change gets a real new reviewer wave. The previous
10740            // evidence remains in the request; a former clean/concluded round
10741            // cannot short-circuit the new review or gate.
10742            self.begin_merge_repair_review(i)?;
10743        }
10744        self.review_loop().await?;
10745        self.gate().await?;
10746        if self.resource_halt()? || self.state.parked {
10747            return Ok(false);
10748        }
10749        if review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
10750            != Some(RunStatus::Gating)
10751            || !self.state.gate_allows_progress()
10752        {
10753            self.hold_merge_repair(i, "updated review or gate did not pass; inspect the new results and resume review explicitly".to_owned())?;
10754            return Ok(false);
10755        }
10756        // Review and gate may have added commits after the initial repair.
10757        // Publish exactly their final head to the existing PR, with a lease.
10758        let winner = self
10759            .state
10760            .winner()
10761            .cloned()
10762            .context("repair has no winning branch")?;
10763        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
10764        if self.state.gate_head.as_deref() != Some(after.as_str())
10765            || !git::is_clean(&winner.worktree).await?
10766        {
10767            self.hold_merge_repair(i, "repair branch changed after its recorded gate, or the verified head is unknown; nothing was published. Inspect the branch and run an explicit review before requesting a new merge decision".to_owned())?;
10768            return Ok(false);
10769        }
10770        let expected = self
10771            .state
10772            .pr_pushed_head
10773            .as_deref()
10774            .unwrap_or(&request.head)
10775            .to_owned();
10776        let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
10777        // Push the checked commit itself: a local ref moving after the check
10778        // must not change which commit the forge receives.
10779        if !crate::foreign_checkout::write_back(&mut self.state, &after).await? {
10780            return Ok(false);
10781        }
10782        let lease = format!("--force-with-lease=refs/heads/{public}:{expected}");
10783        let refspec = format!("{after}:refs/heads/{public}");
10784        let push = git::git_raw(
10785            &winner.worktree,
10786            &["push", &lease, &self.state.config.merge.remote, &refspec],
10787        )
10788        .await;
10789        match push {
10790            Ok(out) if out.ok() => self.state.pr_pushed_head = Some(after),
10791            Ok(out) => {
10792                self.hold_merge_repair(i, format!("publishing reviewed repair failed: {}; inspect the PR head and resume review explicitly", out.stderr))?;
10793                return Ok(false);
10794            }
10795            Err(e) => {
10796                self.hold_merge_repair(i, format!("publishing reviewed repair failed: {e:#}; inspect the PR head and resume review explicitly"))?;
10797                return Ok(false);
10798            }
10799        }
10800        self.state.merge_repairs[i].phase = Phase::Complete;
10801        self.state.status = RunStatus::Landing;
10802        self.state.event(
10803            "repair",
10804            "new review and gate completed; fresh owner merge decision required",
10805        );
10806        self.state.save()?;
10807        Ok(true)
10808    }
10809
10810    fn merge_repair_artifacts(&self) -> PathBuf {
10811        let artifacts = agent::artifacts_dir(&self.state.dir());
10812        match self
10813            .state
10814            .merge_repairs
10815            .last()
10816            .filter(|r| r.phase == crate::run::MergeRepairPhase::Reviewing)
10817        {
10818            Some(r) => artifacts.join(format!("merge-repair-{}", r.question)),
10819            None => artifacts,
10820        }
10821    }
10822
10823    fn begin_merge_repair_review(&mut self, index: usize) -> Result<()> {
10824        if let Some(e2e) = self.state.head_e2e.take() {
10825            self.state
10826                .verification_history
10827                .push(crate::run::VerificationEvidence {
10828                    superseded_by: None,
10829                    archived_at: Some(Timestamp::now()),
10830                    fixes_spent: Some(self.state.gate_fixes.len()),
10831                    gate_head: None,
10832                    gate_ran: false,
10833                    gate: Vec::new(),
10834                    e2e: Some(e2e),
10835                });
10836        }
10837        self.state.reviews.clear();
10838        self.state.gate.clear();
10839        self.state.gate_ran = false;
10840        self.state.gate_head = None;
10841        self.state.gate_fixes.clear();
10842        self.state.gate_repair_e2e = None;
10843        self.state.pre_gate.clear();
10844        self.state.pre_gate_commit = None;
10845        self.state.contested_handoff = None;
10846        self.state.land_reruns = None;
10847        self.state.land_approval = None;
10848        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Reviewing;
10849        self.state.status = RunStatus::Reviewing;
10850        self.state.save()
10851    }
10852
10853    fn hold_merge_repair(&mut self, index: usize, why: String) -> Result<()> {
10854        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Failed;
10855        self.state.merge_repairs[index].failure = Some(why.clone());
10856        self.state.status = RunStatus::Blocked;
10857        self.state.event("repair", why);
10858        self.state.save()
10859    }
10860
10861    // -------------------------------------------------------------- helpers
10862
10863    /// Fetch or create a seat, keeping its conversation across nodes.
10864    fn seat(&mut self, key: &str, agent: &str) -> SeatState {
10865        if let Some(existing) = self.state.seats.get(key)
10866            && existing.agent == agent
10867        {
10868            return existing.clone();
10869        }
10870        // A seat that changes agent mints its session id from the agent too,
10871        // like a handover: the old agent's uuid is already taken by the CLI.
10872        let fresh = if self.state.seats.contains_key(key) {
10873            handover_seat(key, agent, self.state.next_seat_seed())
10874        } else {
10875            SeatState::new(key, agent, self.state.seed)
10876        };
10877        self.state.seats.insert(key.to_owned(), fresh.clone());
10878        fresh
10879    }
10880
10881    /// The agent now holding seat `key`: `spec`, unless a handover moved the
10882    /// seat to another roster agent, in which case that agent. Nodes that
10883    /// continue a seat's conversation (deliberation, the votes, a reviewer's
10884    /// reconsideration) must keep talking to whoever answered it, not slip
10885    /// back to the agent that failed it.
10886    fn occupant(&self, key: &str, spec: AgentSpec) -> AgentSpec {
10887        match self.state.seats.get(key) {
10888            Some(s) if s.agent != spec.id => {
10889                self.state.config.agent(&s.agent).cloned().unwrap_or(spec)
10890            }
10891            _ => spec,
10892        }
10893    }
10894
10895    /// A candidate rendered for judging, with the leak policy applied.
10896    fn view(&self, c: &Candidate) -> CandidateView {
10897        let raw = crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
10898            .unwrap_or_default();
10899        let (patch, _) = blind::sanitize_patch(
10900            &format!("candidate {} patch", c.label),
10901            &raw,
10902            &self.state.config.blind,
10903        );
10904        CandidateView {
10905            label: c.label,
10906            branch: c.branch.clone(),
10907            summary: c.summary.clone(),
10908            stat: c.stat.clone(),
10909            patch,
10910        }
10911    }
10912
10913    /// The full candidate set as prompt text, for seats with no live session.
10914    fn candidate_block(&self, candidates: &[Candidate], base_short: &str) -> String {
10915        let views: Vec<CandidateView> = candidates.iter().map(|c| self.view(c)).collect();
10916        prompt::judge(
10917            "(see above)",
10918            &views,
10919            self.roles.judges.len(),
10920            base_short,
10921            "en",
10922        )
10923    }
10924
10925    /// The final-vote prompt with everything a seat that has no session of its
10926    /// own needs: the candidates, the seat's own ranking and reasons, and the
10927    /// anonymised deliberation it took part in (only when there was one, so a
10928    /// handed-over seat never sees more than the seat it replaces did). The
10929    /// `Final vote` heading stays first.
10930    fn vote_prompt_full(
10931        &self,
10932        j: usize,
10933        labels: &[char],
10934        language: &str,
10935        candidates: &[Candidate],
10936        base_short: &str,
10937    ) -> String {
10938        let mut text = format!(
10939            "{}\n\n# The task the candidates were given\n\n{}\n\n# Candidates\n\n{}",
10940            prompt::final_vote(labels, language),
10941            self.state.instruction,
10942            self.candidate_block(candidates, base_short)
10943        );
10944        if let Some(own) = self
10945            .state
10946            .judgements
10947            .get(j)
10948            .filter(|r| !r.ranking.is_empty())
10949        {
10950            let reasons = own
10951                .reasons
10952                .iter()
10953                .map(|(k, v)| format!("- {k}: {v}"))
10954                .collect::<Vec<_>>()
10955                .join("\n");
10956            text.push_str(&format!(
10957                "\n\n# Your own earlier ranking\n\nYou ranked {}{}{reasons}\n",
10958                own.ranking.iter().collect::<String>(),
10959                if reasons.is_empty() {
10960                    ""
10961                } else {
10962                    ", because:\n"
10963                }
10964            ));
10965        }
10966        if !self.state.deliberation.is_empty() {
10967            text.push_str("\n# What was argued before this vote\n");
10968            for t in self.transcript(&[], j) {
10969                text.push_str(&format!(
10970                    "\n## {}{}\n\n{}\n",
10971                    t.who,
10972                    if t.is_self { " (you)" } else { "" },
10973                    t.body.trim()
10974                ));
10975            }
10976        }
10977        text
10978    }
10979
10980    /// Anonymised transcript for judge `self_idx`.
10981    ///
10982    /// The initial rankings are always the opening statements. Seeding them
10983    /// only when no turn had been taken yet meant every judge after the first
10984    /// argued against a single voice instead of against the actual split — the
10985    /// disagreement is the information, so it is always on the table.
10986    fn transcript(&self, current: &[DeliberationTurn], self_idx: usize) -> Vec<Turn> {
10987        let mut turns = Vec::new();
10988        for j in &self.state.judgements {
10989            if j.ranking.is_empty() {
10990                continue;
10991            }
10992            let reasons = j
10993                .reasons
10994                .iter()
10995                .map(|(k, v)| format!("- {k}: {v}"))
10996                .collect::<Vec<_>>()
10997                .join("\n");
10998            turns.push(Turn {
10999                who: format!("Judge {} (opening ranking)", j.judge),
11000                is_self: j.judge == self_idx + 1,
11001                body: format!(
11002                    "Ranked {}{}{reasons}",
11003                    j.ranking.iter().collect::<String>(),
11004                    if reasons.is_empty() {
11005                        ""
11006                    } else {
11007                        ", because:\n"
11008                    }
11009                ),
11010            });
11011        }
11012        for t in self
11013            .state
11014            .deliberation
11015            .iter()
11016            .flat_map(|r| r.turns.iter())
11017            .chain(current)
11018        {
11019            turns.push(Turn {
11020                who: format!("Judge {}", t.judge),
11021                is_self: t.judge == self_idx + 1,
11022                body: t.body.clone(),
11023            });
11024        }
11025        turns
11026    }
11027}
11028
11029/// Does this seat still hold the context a follow-up prompt would rely on?
11030fn has_context(spec: &AgentSpec, seat: &SeatState, sessions: bool) -> bool {
11031    agent::has_session(spec.kind, seat, sessions)
11032}
11033
11034/// The next entry in `roster` after `start`, never wrapping back to the
11035/// front, whose id is not in `tried` yet.
11036///
11037/// Starts one past `start` rather than at the front of `roster`: `start` is
11038/// the seat's own original position, and a seat whose candidate slot already
11039/// sits on the roster's second entry must fall through to the third next, not
11040/// restart at the first — which is very likely a different candidate's own
11041/// agent already. Never wraps back past `start`, for the same reason: an
11042/// entry earlier in the roster than the seat's own position is almost
11043/// certainly some *other* candidate slot's own agent, and once the tail of
11044/// the roster is exhausted there are no more untried agents for *this* seat
11045/// to fall through to — the caller's fallback chain ends there, exactly as
11046/// "no further untried agents remain in the list for that seat" asks for.
11047///
11048/// Matched by [`AgentSpec::id`], never the whole spec: a roster that names
11049/// the same id twice (an operator's `roles.implementers` typo, or a
11050/// `[[agents]]` list reused across roles) must not let
11051/// [`Runner::resume_seat_handovers`] retry that id forever — one forward pass
11052/// over `roster` either finds an untried id or runs out, so this always
11053/// terminates regardless of duplicates.
11054fn next_untried_in_roster<'a>(
11055    roster: &'a [AgentSpec],
11056    start: usize,
11057    tried: &BTreeSet<String>,
11058) -> Option<&'a AgentSpec> {
11059    roster
11060        .get(start + 1..)?
11061        .iter()
11062        .find(|s| !tried.contains(&s.id))
11063}
11064
11065/// The successor for a seat, shared by all four seat kinds (implement, judge,
11066/// review, advise). `others` holds the ids that *currently* occupy the other
11067/// seats of the same wave (after any earlier handover, as [`Runner::occupant`]
11068/// sees them), so roster entries beyond the seat count act as spares: a failed
11069/// seat goes to an agent no other seat holds whenever the roster permits.
11070///
11071/// `carried` is `Some` only for the review loop's carried failure history.
11072/// Order: (1) forward from `start`, never wrapping, untried, not a carried
11073/// failure, not another seat's occupant; (2) with `carried`, a rescue over the
11074/// whole roster: untried and not another seat's occupant; (3) the plain walk
11075/// ([`next_untried_in_roster`] / [`next_for_seat`]) that ignores `others`.
11076/// Step 3 is deliberate: a duplicate agent on two seats is a worse panel but
11077/// a better outcome than an empty seat, and it keeps the answer to "is there
11078/// a successor at all" exactly what it was before occupants were considered,
11079/// so no handover rule (`should_hand_over`, nudges, the tried-once bound)
11080/// moves. The rescue excludes occupants too, on the same reasoning: retrying a
11081/// carried failure is a cheaper bet than doubling an agent on the panel, and
11082/// if it fails again `tried` bounds it and step 3 takes over. Seats failing in
11083/// the same round are handled one at a time, so a seat later in the batch
11084/// sees an earlier one's new occupant but not yet its own freed agent.
11085fn pick_successor<'a>(
11086    roster: &'a [AgentSpec],
11087    start: usize,
11088    tried: &BTreeSet<String>,
11089    carried: Option<&BTreeSet<String>>,
11090    others: &BTreeSet<String>,
11091) -> Option<&'a AgentSpec> {
11092    let free = |s: &&AgentSpec| !tried.contains(&s.id) && !others.contains(&s.id);
11093    roster
11094        .get(start + 1..)
11095        .and_then(|tail| {
11096            tail.iter()
11097                .filter(free)
11098                .find(|s| carried.is_none_or(|c| !c.contains(&s.id)))
11099        })
11100        .or_else(|| {
11101            carried
11102                .is_some()
11103                .then(|| roster.iter().find(free))
11104                .flatten()
11105        })
11106        .or_else(|| match carried {
11107            Some(c) => next_for_seat(roster, start, tried, c),
11108            None => next_untried_in_roster(roster, start, tried),
11109        })
11110}
11111
11112/// The next agent for a seat that carries its failure history across rounds
11113/// (the review loop). `round_tried` is this round's own bound and starts
11114/// empty every round; `carried_failed` only decides priority.
11115///
11116/// First: an id walking forward from `start`, never wrapping, that is neither
11117/// tried this round nor failed in an earlier one. Only when that is exhausted
11118/// does it rescue: the first roster id (in roster order, so this one *does*
11119/// look before `start`) not yet tried this round, which is by then a carried
11120/// failure. Each id is rescued at most once per round, so it cannot loop.
11121fn next_for_seat<'a>(
11122    roster: &'a [AgentSpec],
11123    start: usize,
11124    round_tried: &BTreeSet<String>,
11125    carried_failed: &BTreeSet<String>,
11126) -> Option<&'a AgentSpec> {
11127    roster
11128        .get(start + 1..)?
11129        .iter()
11130        .find(|s| !round_tried.contains(&s.id) && !carried_failed.contains(&s.id))
11131        .or_else(|| roster.iter().find(|s| !round_tried.contains(&s.id)))
11132}
11133
11134/// Where a reviewer seat starts a round: the agent that last answered it when
11135/// it is still on the roster and not marked failed, else the spec's own agent
11136/// unless it failed, else the next roster agent that has not failed, else the
11137/// spec's own agent again (the whole roster failed). Ids no longer on the
11138/// roster are ignored. An empty roster has no handover, so the spec stands.
11139fn pick_start_spec(roster: &[AgentSpec], spec: AgentSpec, hist: Option<&SeatHistory>) -> AgentSpec {
11140    let Some(h) = hist.filter(|_| !roster.is_empty()) else {
11141        return spec;
11142    };
11143    let ok = |id: &str| !h.failed.contains(id);
11144    if let Some(last) = h.last_ok.as_deref()
11145        && ok(last)
11146        && let Some(s) = roster.iter().find(|s| s.id == last)
11147    {
11148        return s.clone();
11149    }
11150    if ok(&spec.id) {
11151        return spec;
11152    }
11153    let from = roster.iter().position(|s| s.id == spec.id).unwrap_or(0);
11154    roster
11155        .get(from + 1..)
11156        .into_iter()
11157        .flatten()
11158        .chain(roster.iter())
11159        .find(|s| ok(&s.id))
11160        .cloned()
11161        .unwrap_or(spec)
11162}
11163
11164/// A fresh seat for the agent taking over `key`. Mixes the agent id into the
11165/// seed so a CLI that mints its session id up front (`--session-id`) never
11166/// reuses the uuid the previous agent already opened under the same seat key.
11167pub(crate) fn handover_seat(key: &str, agent: &str, run_seed: u64) -> SeatState {
11168    SeatState::new(key, agent, run_seed ^ crate::rng::fnv1a(agent))
11169}
11170
11171/// What an agent's turn timed out as, in [`AgentOutcome::Failed`]. One const
11172/// so the classifier below and the code that builds the message cannot drift.
11173const TIMED_OUT: &str = "timed out";
11174
11175impl FailClass {
11176    /// `None` for an answer; otherwise how the turn failed.
11177    fn of(out: &AgentOutcome) -> Option<Self> {
11178        match out {
11179            AgentOutcome::Ok(_) => None,
11180            AgentOutcome::Quota(_) => Some(Self::Quota),
11181            AgentOutcome::Dropped(_) => Some(Self::Other("dropped".to_owned())),
11182            AgentOutcome::Failed(e) if e == TIMED_OUT => Some(Self::Timeout),
11183            AgentOutcome::Failed(e) => Some(Self::Other(failure_signature(e))),
11184            // Not a failure of the agent. Callers check for it first; `None`
11185            // here means "no class to hand over on".
11186            AgentOutcome::ResourceBlocked(_) => None,
11187        }
11188    }
11189
11190    /// The word in a handover's artifact stem (`impl-A-quota-beta`).
11191    fn stem_word(&self) -> &'static str {
11192        match self {
11193            Self::Quota => "quota",
11194            _ => "handover",
11195        }
11196    }
11197}
11198
11199/// The message's first line with its variable parts removed — digit runs and
11200/// path-like tokens — so "exit code 2" and "exit code 7" read
11201/// as one kind of failure.
11202fn failure_signature(msg: &str) -> String {
11203    let mut line = msg.lines().next().unwrap_or("").trim().to_lowercase();
11204    // `SeatHistory::last_fail` persists these signatures across resumes. Keep
11205    // the historical machine key while the process diagnosis uses readable prose.
11206    if let Some(code) = line
11207        .strip_prefix("process exited with no usable output (exit code ")
11208        .and_then(|s| s.strip_suffix(')'))
11209        .and_then(|s| s.parse::<i32>().ok())
11210    {
11211        line = format!("exited with some({code}) and no usable output");
11212    } else if matches!(
11213        line.as_str(),
11214        "process exited with no usable output (no exit code reported)"
11215            | "process exited with no usable output (exit code unavailable)"
11216    ) {
11217        line = "exited with none and no usable output".to_owned();
11218    }
11219    let mut out = Vec::new();
11220    for word in line.split_whitespace() {
11221        if word.contains('/') || word.contains('\\') {
11222            out.push("<path>".to_owned());
11223            continue;
11224        }
11225        let mut w = String::new();
11226        let mut in_digits = false;
11227        for c in word.chars() {
11228            if c.is_ascii_digit() {
11229                if !in_digits {
11230                    w.push('#');
11231                }
11232                in_digits = true;
11233            } else {
11234                in_digits = false;
11235                w.push(c);
11236            }
11237        }
11238        out.push(w);
11239    }
11240    out.join(" ").chars().take(120).collect()
11241}
11242
11243/// Whether a seat that just failed with `cur` may go to the next roster agent.
11244/// A quota or a timeout always may. Any other failure may not when the agent
11245/// before it failed the same way: an error the prompt causes would otherwise
11246/// walk the whole roster. `prev` is the class of the immediately preceding
11247/// agent's failure, so a quota or timeout in between breaks the run of
11248/// identical failures by itself.
11249fn should_hand_over(prev: Option<&FailClass>, cur: &FailClass) -> bool {
11250    match cur {
11251        FailClass::Quota | FailClass::Timeout => true,
11252        FailClass::Other(_) => prev != Some(cur),
11253    }
11254}
11255
11256/// A short human reason for a failed outcome, for the handover record.
11257fn fail_reason(out: &AgentOutcome) -> String {
11258    match out {
11259        AgentOutcome::Ok(_) => String::new(),
11260        AgentOutcome::Quota(_) => "rate limited (quota)".to_owned(),
11261        AgentOutcome::Dropped(o) => format!(
11262            "the CLI dropped the stream ({})",
11263            o.dropped
11264                .as_ref()
11265                .map(|d| d.why.as_str())
11266                .unwrap_or("it ended without delivering its answer")
11267        ),
11268        AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
11269            e.lines().next().unwrap_or("").chars().take(160).collect()
11270        }
11271    }
11272}
11273
11274/// Note one handover in the run: the structured record and, in the timeline,
11275/// the sentence a person reads. A quota keeps the wording it always had.
11276pub(crate) fn record_handover(
11277    state: &mut RunState,
11278    node: &str,
11279    seat: &str,
11280    from: &str,
11281    to: &str,
11282    class: &FailClass,
11283    reason: &str,
11284) {
11285    let message = if *class == FailClass::Quota {
11286        format!("{seat}: rate limited (quota) on {from}; retrying with {to}")
11287    } else {
11288        format!("{seat}: handed over {from} -> {to} ({reason})")
11289    };
11290    state.event(node, message);
11291    state.handovers.push(Handover {
11292        at: Timestamp::now(),
11293        node: node.to_owned(),
11294        seat: seat.to_owned(),
11295        from: from.to_owned(),
11296        to: to.to_owned(),
11297        reason: reason.to_owned(),
11298    });
11299}
11300
11301/// Did this reply report running a command whose own CLI never confirmed an
11302/// exit status?
11303///
11304/// An [`agent::CommandEvidence`] only ever exists when the CLI reported the
11305/// command *finished* (see that type's own doc), so this can only be `true`
11306/// for a command whose completion event carried no readable exit code — not
11307/// for one that simply is not mentioned at all. That is the one signal this
11308/// crate can read, from the same record `state.jobs` renders, about a reply
11309/// standing next to work its own CLI cannot vouch for finishing; it is
11310/// deliberately not a check on the exit code's *value* (a fixer legitimately
11311/// runs a command that fails mid-iteration before it succeeds) and not a
11312/// guess at a command still running in the background (which emits no event
11313/// at all, and so leaves no evidence here to find).
11314fn has_unconfirmed_command(commands: &[agent::CommandEvidence]) -> bool {
11315    commands.iter().any(|c| c.exit_code.is_none())
11316}
11317
11318/// The reason recorded for a candidate, and named in a handover, when an
11319/// implement seat ended its turn without starting the work and did so again
11320/// on its one retry. See [`Runner::retry_unstarted`].
11321const UNSTARTED_TWICE: &str = "the agent ended its turn without starting the work (no tool call, \
11322                               worktree unchanged), and again when asked once more";
11323
11324/// Did this turn end cleanly without the seat having started the work?
11325///
11326/// Every part is positive evidence, and a missing one means "no": a usable
11327/// reply; a CLI whose stream reports tool calls and reported none
11328/// (`tool_calls` is `None` for a backend that does not report them, which is
11329/// unknown, never zero); no command evidence; and a checkout whose `HEAD` is
11330/// the one recorded before the turn (`before`) with nothing uncommitted. A
11331/// dirty tree, a moved `HEAD` or an unreadable repository never authorizes a
11332/// retry: partial work is the other recoveries' business.
11333///
11334/// The comparison is with the seat's own starting point, not the run's base,
11335/// so a seat that left an inherited patch untouched is unstarted too.
11336fn ended_unstarted(
11337    out: &AgentOutput,
11338    before: Option<&str>,
11339    after: Option<&str>,
11340    clean: Option<bool>,
11341) -> bool {
11342    out.usable()
11343        && out.tool_calls == Some(0)
11344        && out.commands.is_empty()
11345        && before.is_some()
11346        && before == after
11347        && clean == Some(true)
11348}
11349
11350/// Outcome of evaluating a candidate's reply against the `NO CHANGE NEEDED:`
11351/// adoption guard.
11352#[derive(Debug, Clone, PartialEq, Eq)]
11353enum NoopClaimVerdict {
11354    /// Reply did not open with `NO CHANGE NEEDED:`.
11355    Absent,
11356    /// Structured evidence passed schema, CLI command, and repository checks.
11357    Accepted,
11358    /// Reply opened with `NO CHANGE NEEDED:` but was disqualified with a
11359    /// concrete reason.
11360    Rejected(String),
11361}
11362
11363fn command_matches_check(cmd: &agent::CommandEvidence, check: &verdict::NoopCheck) -> bool {
11364    // Keep quoting and shell syntax intact: they can change the meaning of a command.
11365    cmd.description.trim() == check.method.trim()
11366}
11367
11368/// Checks cited by `requirements` plus the final check, deduplicated in order.
11369fn checks_to_cross_verify(report: &verdict::VerifiedNoopReport) -> Vec<&verdict::NoopCheck> {
11370    let mut out = report.cited_checks();
11371    if let Some(last) = report.checks.last()
11372        && !out
11373            .iter()
11374            .any(|c| c.id.trim().eq_ignore_ascii_case(last.id.trim()))
11375    {
11376        out.push(last);
11377    }
11378    out
11379}
11380
11381/// Cross-check claimed passing checks against structured CLI [`agent::CommandEvidence`]
11382/// when the backend reported commands. Empty `commands` is allowed because not
11383/// every backend emits structured command events.
11384fn check_command_evidence(
11385    report: &verdict::VerifiedNoopReport,
11386    commands: &[agent::CommandEvidence],
11387) -> std::result::Result<(), String> {
11388    if commands.is_empty() {
11389        return Ok(());
11390    }
11391    for check in checks_to_cross_verify(report) {
11392        let matching: Vec<&agent::CommandEvidence> = commands
11393            .iter()
11394            .filter(|cmd| command_matches_check(cmd, check))
11395            .collect();
11396        match check.kind {
11397            verdict::NoopEvidenceKind::Command
11398            | verdict::NoopEvidenceKind::Test
11399            | verdict::NoopEvidenceKind::Path => {
11400                let Some(last_cmd) = matching.last() else {
11401                    return Err(format!(
11402                        "contradictory command evidence: check `{}` (`{}`) claims `{}` passed, \
11403                         but no matching command was recorded by the CLI",
11404                        check.id.trim(),
11405                        check.kind,
11406                        check.target.trim()
11407                    ));
11408                };
11409                if last_cmd.exit_code != Some(0) {
11410                    return Err(format!(
11411                        "contradictory command evidence: check `{}` claims `{}` passed, \
11412                         but its last recorded CLI command (`{}`) exited with {}",
11413                        check.id.trim(),
11414                        check.target.trim(),
11415                        last_cmd.description.trim(),
11416                        crate::notices::exit_status(last_cmd.exit_code)
11417                    ));
11418                }
11419                if check.kind == verdict::NoopEvidenceKind::Test
11420                    && crate::verify_evidence::contradicts_passing_test(&last_cmd.result_summary)
11421                {
11422                    return Err(format!(
11423                        "contradictory command evidence: test check `{}` claims `{}` passed, \
11424                         but its last recorded CLI output reports failure or no passing tests",
11425                        check.id.trim(),
11426                        check.target.trim()
11427                    ));
11428                }
11429            }
11430            verdict::NoopEvidenceKind::Commit => {
11431                if let Some(last_cmd) = matching.last()
11432                    && last_cmd.exit_code != Some(0)
11433                {
11434                    return Err(format!(
11435                        "contradictory command evidence: commit check `{}` claims `{}` passed, \
11436                         but its last recorded CLI command (`{}`) exited with {}",
11437                        check.id.trim(),
11438                        check.target.trim(),
11439                        last_cmd.description.trim(),
11440                        crate::notices::exit_status(last_cmd.exit_code)
11441                    ));
11442                }
11443            }
11444        }
11445    }
11446    Ok(())
11447}
11448
11449/// Pure, synchronous half of the `NO CHANGE NEEDED:` adoption guard: clean CLI
11450/// exit, confirmed commands, strict structured JSON validation, and
11451/// `CommandEvidence` consistency.
11452fn evaluate_noop_claim(
11453    usable: bool,
11454    commands: &[agent::CommandEvidence],
11455    text: &str,
11456) -> std::result::Result<Option<verdict::VerifiedNoopReport>, String> {
11457    if !text
11458        .trim_start()
11459        .starts_with(verdict::NO_CHANGE_NEEDED_MARKER)
11460    {
11461        return Ok(None);
11462    }
11463    if !usable {
11464        return Err("turn did not finish cleanly (non-zero exit or timeout)".to_owned());
11465    }
11466    if has_unconfirmed_command(commands) {
11467        return Err("reply reported a command whose CLI never confirmed an exit status".to_owned());
11468    }
11469    let Some(parsed) = verdict::parse_verified_noop(text) else {
11470        return Ok(None);
11471    };
11472    let report = parsed?;
11473    check_command_evidence(&report, commands)?;
11474    Ok(Some(report))
11475}
11476
11477/// Cross-check verifiable commit SHAs and repository-relative paths cited by a
11478/// structured no-op report against the candidate's real Git history and
11479/// worktree. Existence alone never satisfies a requirement (the report still
11480/// had to carry concrete passing checks), while a missing commit/path or a
11481/// commit not on `base_commit` disqualifies the claim.
11482async fn verify_noop_repo_evidence(
11483    report: &verdict::VerifiedNoopReport,
11484    worktree: &Path,
11485    base_commit: &str,
11486) -> std::result::Result<(), String> {
11487    let wt_canon = std::fs::canonicalize(worktree).ok();
11488    for check in checks_to_cross_verify(report) {
11489        match check.kind {
11490            verdict::NoopEvidenceKind::Commit => {
11491                let target = check.target.trim();
11492                let Some(sha) = git::commit_of(worktree, target).await else {
11493                    return Err(format!(
11494                        "check `{}` cites commit `{target}`, which does not exist in git history",
11495                        check.id.trim()
11496                    ));
11497                };
11498                if !git::is_ancestor(worktree, &sha, base_commit).await {
11499                    return Err(format!(
11500                        "check `{}` cites commit `{target}`, which is not an ancestor of base commit `{}`",
11501                        check.id.trim(),
11502                        short(base_commit)
11503                    ));
11504                }
11505            }
11506            verdict::NoopEvidenceKind::Path => {
11507                let target = check.target.trim();
11508                let rel = verdict::strip_path_locator(target);
11509                let full = worktree.join(rel);
11510                if !full.exists() {
11511                    return Err(format!(
11512                        "check `{}` cites path `{target}`, which does not exist in the worktree",
11513                        check.id.trim()
11514                    ));
11515                }
11516                if let (Some(wt_canon), Ok(path_canon)) = (&wt_canon, std::fs::canonicalize(&full))
11517                    && !path_canon.starts_with(wt_canon)
11518                {
11519                    return Err(format!(
11520                        "check `{}` cites path `{target}`, which resolves outside the worktree",
11521                        check.id.trim()
11522                    ));
11523                }
11524            }
11525            verdict::NoopEvidenceKind::Test | verdict::NoopEvidenceKind::Command => {}
11526        }
11527    }
11528    Ok(())
11529}
11530
11531/// Full adoption guard for an implementer reply, including real Git history and
11532/// worktree path verification.
11533async fn verified_noop_claim_in_worktree(
11534    usable: bool,
11535    commands: &[agent::CommandEvidence],
11536    text: &str,
11537    worktree: &Path,
11538    base_commit: &str,
11539) -> NoopClaimVerdict {
11540    let report = match evaluate_noop_claim(usable, commands, text) {
11541        Ok(Some(r)) => r,
11542        Ok(None) => return NoopClaimVerdict::Absent,
11543        Err(reason) => return NoopClaimVerdict::Rejected(reason),
11544    };
11545    if let Err(reason) = verify_noop_repo_evidence(&report, worktree, base_commit).await {
11546        return NoopClaimVerdict::Rejected(reason);
11547    }
11548    NoopClaimVerdict::Accepted
11549}
11550
11551/// Whether a `NO CHANGE NEEDED` marker in an implementer's reply should be
11552/// trusted as a verified no-op — the adoption guard's pure text-and-command
11553/// half (repository history/path verification runs in
11554/// [`verified_noop_claim_in_worktree`]).
11555///
11556/// `usable` is the caller's `AgentOutput::usable()` (a clean CLI exit, not
11557/// timed out): a marker only earns the benefit of the doubt from a turn the
11558/// CLI itself vouches for finishing properly, the same house style
11559/// `resume_unconfirmed_commands` and `continue_fix_report` already hold a
11560/// *fix* report to for `commands`. A candidate that timed out, exited
11561/// non-zero, left a command unconfirmed, contradicted its CLI command evidence,
11562/// or failed structured validation returns `None`.
11563#[cfg(test)]
11564fn verified_noop_claim(
11565    usable: bool,
11566    commands: &[agent::CommandEvidence],
11567    text: &str,
11568) -> Option<String> {
11569    evaluate_noop_claim(usable, commands, text)
11570        .ok()
11571        .flatten()
11572        .map(|report| report.summary_text())
11573}
11574
11575fn short(commit: &str) -> String {
11576    commit.chars().take(7).collect()
11577}
11578
11579fn make_executable(path: &Path) -> Result<()> {
11580    #[cfg(unix)]
11581    {
11582        use std::os::unix::fs::PermissionsExt as _;
11583        let mut perms = std::fs::metadata(path)?.permissions();
11584        perms.set_mode(0o755);
11585        std::fs::set_permissions(path, perms)?;
11586    }
11587    #[cfg(not(unix))]
11588    {
11589        let _ = path;
11590    }
11591    Ok(())
11592}
11593
11594/// What every seat in one batch shares: where the answers are attributed, the
11595/// prompt overlay they inherit, and the build cache they are told to use.
11596///
11597/// A struct rather than four more parameters: `wave` also needs the run's
11598/// state (to record who is answering right now) and the attempt number, and
11599/// eight positional arguments is both unreadable and a clippy error.
11600struct WaveCtx<'a> {
11601    /// Exported as `MAGI_RUN`, so a task an agent files names the run that
11602    /// paid for it.
11603    run: &'a str,
11604    /// Exported as `MAGI_NODE`, and the key the prompt overlay is chosen by.
11605    node: &'a str,
11606    prompts: &'a Prompts,
11607    /// The shared `CARGO_TARGET_DIR`, when the config declares one.
11608    cache: Option<&'a Path>,
11609    /// The review round this wave belongs to, for `"review"`/`"fix"` — see
11610    /// `JobRecord::round`. `None` for every other node.
11611    round: Option<usize>,
11612    /// Carry each seat's failed-agent history across waves (the review loop
11613    /// only): start-of-round priority and handover choice read
11614    /// [`RunState::seat_history`], and every answer or failure writes it.
11615    carry_seats: bool,
11616    /// The run's park / interrupt requests, so a wait for a shared resource
11617    /// can be abandoned the moment the operator asks to park.
11618    pauses: Option<(&'a Pause, &'a Pause)>,
11619}
11620
11621/// Shared scheduling policy for operations and spawned seat invocations.
11622fn repository_wait(
11623    state: &RunState,
11624    pauses: Option<(&Pause, &Pause)>,
11625) -> crate::repo_lock::WaitPolicy {
11626    let pauses = pauses.map(|(a, b)| (a.clone(), b.clone()));
11627    let inherited = crate::repo_lock::WaitPolicy::current();
11628    crate::repo_lock::WaitPolicy::new(
11629        Duration::from_secs(state.config.graph.timeout_resource_wait),
11630        move || {
11631            inherited.cancelled()
11632                || pauses
11633                    .as_ref()
11634                    .is_some_and(|(a, b)| a.parked() || b.parked())
11635        },
11636    )
11637}
11638
11639fn record_repository_block(state: &mut RunState, error: &anyhow::Error) {
11640    if let Some(timeout) = error.downcast_ref::<agent::IsolatedSeatWait>() {
11641        state.event("resource", timeout.0.description());
11642        state.resource_block = Some(timeout.0.clone());
11643        return;
11644    }
11645    if error.is::<crate::repo_lock::ResourceBlocked>() {
11646        state.resource_block = Some(crate::run::ResourceBlock {
11647            cause: crate::run::ResourceBlockCause::Other,
11648            node: "repository".into(),
11649            kind: if error.is::<crate::build_target::AdmissionDiskWait>() {
11650                "disk admission"
11651            } else if error.to_string().contains("disk pressure") {
11652                "disk pressure"
11653            } else if error.to_string().contains("disk admission") {
11654                "disk admission"
11655            } else if error.to_string().contains(crate::incremental::BLOCKED) {
11656                "incremental cache admission"
11657            } else {
11658                "repository coordination"
11659            }
11660            .into(),
11661            detail: format!("{error:#}"),
11662            at: Timestamp::now(),
11663        });
11664        state.event("resource", error.to_string());
11665    }
11666}
11667
11668async fn coordinate_operation(
11669    state: &mut RunState,
11670    cwd: &Path,
11671    wait: &crate::repo_lock::WaitPolicy,
11672) -> Result<Option<crate::repo_lock::SeatLease>> {
11673    let result =
11674        crate::repo_lock::SeatLease::operation_with(cwd, state.config.coordination.as_ref(), wait)
11675            .await;
11676    if let Err(e) = &result {
11677        record_repository_block(state, e);
11678    }
11679    result
11680}
11681
11682/// Run one job, honouring the parallelism budget.
11683async fn run_one(
11684    job: SeatJob,
11685    sem: Arc<Semaphore>,
11686    ctx: &WaveCtx<'_>,
11687    state: &mut RunState,
11688    attempt: usize,
11689) -> (SeatState, AgentOutcome) {
11690    let (_, seat, out) = wave(vec![job], sem, ctx, state, attempt)
11691        .await
11692        .pop()
11693        .expect("one job in, one result out");
11694    (seat, out)
11695}
11696
11697/// Run every job concurrently, capped by the semaphore, preserving order.
11698///
11699/// Every seat in the batch is recorded into [`RunState::active`] before the
11700/// wave starts and cleared as each answer lands, so the run's own record says
11701/// who is still being waited on rather than only who finished.
11702async fn wave(
11703    jobs: Vec<SeatJob>,
11704    sem: Arc<Semaphore>,
11705    ctx: &WaveCtx<'_>,
11706    state: &mut RunState,
11707    attempt: usize,
11708) -> Vec<(usize, SeatState, AgentOutcome)> {
11709    let WaveCtx {
11710        run,
11711        node,
11712        prompts,
11713        cache,
11714        round,
11715        carry_seats: _,
11716        pauses,
11717    } = *ctx;
11718    let cache = cache.filter(|_| !crate::build_target::isolated(&state.config));
11719    for job in &jobs {
11720        state.seat_started(node, &job.seat.key, job.timeout, attempt);
11721    }
11722    if let Err(e) = state.save() {
11723        // A failed persist of "who is answering right now" must not abort the
11724        // wave: the seats are already being asked, and the alternative is
11725        // losing the answers to save a status line nobody may even be
11726        // watching.
11727        tracing::warn!("could not persist in-progress seats: {e:#}");
11728    }
11729    // Shared-mode waves keep their existing single lease. Isolated writers
11730    // acquire their own checkout's target at seat admission.
11731    let jobs_had_a_writer = jobs.iter().any(|j| j.allow_write);
11732    // The wait for the lease has its own bound, `timeout_resource_wait`; it is
11733    // never borrowed from a job's agent budget (and never charged to it either,
11734    // see below). The agent's clock starts in `agent::invoke`, at spawn.
11735    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
11736    let cache_guard = if let Some(cache_dir) = cache {
11737        if jobs_had_a_writer {
11738            let owner = crate::cache::Owner::here(run, node, "*", Path::new("(wave)"), "");
11739            let cancel = move || pauses.is_some_and(|(a, b)| a.parked() || b.parked());
11740            match acquire_cache_lease(
11741                state,
11742                cache_dir,
11743                &owner,
11744                resource_limit,
11745                node,
11746                node,
11747                &cancel,
11748            )
11749            .await
11750            {
11751                Ok(Some(g)) => Some(g),
11752                // Parking: leave without spawning anything. The run parks at
11753                // the next boundary and the seats are asked afresh on resume.
11754                Ok(None) => {
11755                    if let Some(block) = &mut state.resource_block {
11756                        block.cause = crate::run::ResourceBlockCause::Cancelled {
11757                            park: pauses.and_then(|(a, b)| b.cause().or_else(|| a.cause())),
11758                        };
11759                    }
11760                    return block_wave(
11761                        jobs,
11762                        state,
11763                        node,
11764                        attempt,
11765                        "parked while waiting for the shared build cache",
11766                    );
11767                }
11768                // An unreadable lease is not contention: keep the old
11769                // fallback (no shared cache for this wave's seats).
11770                Err(e) if e.downcast_ref::<CacheCheckError>().is_some() => None,
11771                Err(e) => {
11772                    // Writing seats may not build into a cache this run does
11773                    // not hold, and an agent that cannot be given one is not
11774                    // asked at all: the run stops resumably instead.
11775                    let why = format!("{e:#}");
11776                    state.event(
11777                        "resource",
11778                        format!("{node}: no agent was started - {why}; resume to ask the same agents again"),
11779                    );
11780                    return block_wave(jobs, state, node, attempt, &why);
11781                }
11782            }
11783        } else {
11784            None
11785        }
11786    } else {
11787        None
11788    };
11789    // Every job keeps its whole budget: the wait above was not the agent's.
11790    // Restart the seats' clocks so "started" means "being spawned now".
11791    state.seats_spawning(node, attempt);
11792    if let Err(e) = state.save() {
11793        tracing::warn!("could not persist the start of a wave: {e:#}");
11794    }
11795    // Queueing behind this wave's own seats for a parallelism slot is normal
11796    // (each of them is bounded by its own agent timeout); only a wait beyond
11797    // all of them plus the resource limit means the slots never came back.
11798    let slot_limit = resource_limit
11799        + jobs
11800            .iter()
11801            .map(|j| j.timeout)
11802            .max()
11803            .unwrap_or_default()
11804            .saturating_mul(jobs.len() as u32);
11805    let mut set = tokio::task::JoinSet::new();
11806    // Seats announce themselves here the moment they hold a parallelism
11807    // permit, i.e. just before their CLI is spawned.
11808    let (spawned_tx, mut spawned_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
11809    let overlay = prompts.overlay(node);
11810    let repository_wait = repository_wait(state, pauses);
11811    for (i, mut job) in jobs.into_iter().enumerate() {
11812        job.prompt = prompt::with_overlay(job.prompt, overlay.clone());
11813        if cache.is_some() {
11814            job.prompt.push('\n');
11815            job.prompt
11816                .push_str(&prompt::build_cache_note(node, job.allow_write));
11817        }
11818        let sem = Arc::clone(&sem);
11819        let run = run.to_owned();
11820        let node = node.to_owned();
11821        // Only implementers were told about the task's attachments, so only
11822        // their seats get the directory widened for reading.
11823        let attachments = if node == "implement" {
11824            state.attachments.clone()
11825        } else {
11826            Vec::new()
11827        };
11828        // A read-only seat is never handed `CARGO_TARGET_DIR` — see
11829        // `prompt::build_cache_note`'s doc for why setting it anyway is
11830        // exactly how a sandboxed reviewer's write refusal got reported as a
11831        // defect in the patch, not a property of its own seat. And a
11832        // write-allowed one is handed it only when the lease above was
11833        // actually acquired: a wave that could not get it (`cache_guard` is
11834        // `None`, see its own comment) must not send seats to build into a
11835        // directory this run does not hold - that is the exact concurrent,
11836        // unmanaged-write race this module exists to prevent, not something
11837        // "proceeding anyway" is allowed to reintroduce.
11838        let cache = cache
11839            .filter(|_| job.allow_write && cache_guard.is_some())
11840            .map(Path::to_path_buf);
11841        let spawned_tx = spawned_tx.clone();
11842        let repository_wait = repository_wait.clone();
11843        let coordination = state.config.coordination.clone();
11844        let fetched_base = state.fetched_base.clone();
11845        set.spawn(async move {
11846            // A wait for a parallelism slot is scheduling, not the agent: it
11847            // is bounded by its own limit and ends as a resource block, never
11848            // as a timeout of the agent that was not started.
11849            let _permit = match tokio::time::timeout(slot_limit, sem.acquire()).await {
11850                Ok(p) => p,
11851                Err(_) => {
11852                    return (
11853                        i,
11854                        job.seat,
11855                        AgentOutcome::ResourceBlocked(format!(
11856                            "no parallel slot became free within {}s",
11857                            slot_limit.as_secs()
11858                        )),
11859                        None,
11860                        false,
11861                    );
11862                }
11863            };
11864            spawned_tx.send(job.seat.key.clone()).ok();
11865            let mut seat = job.seat;
11866            let out = repository_wait
11867                .scope(agent::invoke(
11868                    &job.spec,
11869                    &mut seat,
11870                    &Invocation {
11871                        coordination: coordination.as_ref(),
11872                        fetched_base: fetched_base.as_ref(),
11873                        cwd: &job.cwd,
11874                        prompt: &job.prompt,
11875                        timeout: job.timeout,
11876                        allow_write: job.allow_write,
11877                        sessions: job.sessions,
11878                        artifacts: &job.artifacts,
11879                        stem: &job.stem,
11880                        run: &run,
11881                        node: &node,
11882                        cache_dir: cache.as_deref(),
11883                        attachments: &attachments,
11884                        writable: &[],
11885                    },
11886                ))
11887                .await;
11888            let cache_block = out
11889                .as_ref()
11890                .err()
11891                .and_then(|error| error.downcast_ref::<agent::IsolatedSeatWait>())
11892                .map(|timeout| timeout.0.clone());
11893            let interrupted = out
11894                .as_ref()
11895                .err()
11896                .is_some_and(|error| error.is::<agent::ExecutionInterrupted>());
11897            let out = match out {
11898                Ok(o) if o.quota_exhausted() => AgentOutcome::Quota(o),
11899                Ok(o) if o.usable() => AgentOutcome::Ok(o),
11900                // Billed work the CLI failed to hand over is not an ordinary
11901                // failure, but its text is the CLI's raw error JSON, not an
11902                // answer — `Dropped` keeps it out of `Ok` so a caller cannot
11903                // read it as one by forgetting to check. `usable()` is always
11904                // false here (dropped implies an empty response), so this has
11905                // to be checked before the catch-all `Failed` below or the
11906                // one shape this exists for is lost with the rest.
11907                Ok(o) if o.work_undelivered() => AgentOutcome::Dropped(o),
11908                Ok(o) if o.timed_out => AgentOutcome::Failed(TIMED_OUT.to_owned()),
11909                Ok(o) => AgentOutcome::Failed(format!(
11910                    "process exited with no usable output ({})",
11911                    crate::notices::exit_status(o.exit_code)
11912                )),
11913                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
11914                    AgentOutcome::ResourceBlocked(e.to_string())
11915                }
11916                Err(e) => AgentOutcome::Failed(e.to_string()),
11917            };
11918            (i, seat, out, cache_block, interrupted)
11919        });
11920    }
11921    drop(spawned_tx);
11922    let mut collected: Vec<Option<(usize, SeatState, AgentOutcome)>> = Vec::new();
11923    loop {
11924        let joined = tokio::select! {
11925            Some(key) = spawned_rx.recv() => {
11926                // The clock of this seat starts now, not when it queued.
11927                state.seat_spawned(&key);
11928                if let Err(e) = state.save() {
11929                    tracing::warn!("could not persist a seat's start: {e:#}");
11930                }
11931                continue;
11932            }
11933            joined = set.join_next() => joined,
11934        };
11935        let Some(joined) = joined else {
11936            break;
11937        };
11938        let (i, seat, out, cache_block, interrupted) = match joined {
11939            Ok(v) => v,
11940            // No seat to clear: a panicked task never reported which one it
11941            // was. The defensive sweep below this loop is what stops that
11942            // seat's `active` entry from surviving forever.
11943            Err(e) => {
11944                tracing::error!("agent task panicked: {e}");
11945                continue;
11946            }
11947        };
11948        state.seat_finished(&seat.key);
11949        if interrupted
11950            && node == "implement"
11951            && let Some(label) = state
11952                .candidates
11953                .iter()
11954                .find(|candidate| seat.key == format!("impl-{}", candidate.label))
11955                .map(|candidate| candidate.label)
11956        {
11957            state.candidate_preservation.insert(
11958                label,
11959                "interrupted implementation awaiting persistence".into(),
11960            );
11961            state.interrupted_implementations.insert(label);
11962        }
11963        if let Some(block) = cache_block
11964            && state.resource_block.is_none()
11965        {
11966            state.event("resource", block.description());
11967            state.resource_block = Some(block);
11968        }
11969        if let AgentOutcome::ResourceBlocked(why) = &out
11970            && state.resource_block.is_none()
11971        {
11972            state.resource_block = Some(crate::run::ResourceBlock {
11973                cause: crate::run::ResourceBlockCause::Other,
11974                node: node.to_owned(),
11975                kind: if why.contains("disk pressure") {
11976                    "disk pressure"
11977                } else if why.contains("disk admission") {
11978                    "disk admission"
11979                } else if why.contains(crate::incremental::BLOCKED) {
11980                    "incremental cache admission"
11981                } else if why.contains(crate::build_target::KIND) {
11982                    crate::build_target::KIND
11983                } else if why.contains("repository coordination") {
11984                    "repository coordination"
11985                } else {
11986                    "parallel slot"
11987                }
11988                .to_owned(),
11989                detail: why.clone(),
11990                at: Timestamp::now(),
11991            });
11992            let activity = if interrupted {
11993                "agent execution interrupted"
11994            } else {
11995                "no agent was started"
11996            };
11997            state.event("resource", format!("{node}: {activity} - {why}"));
11998        }
11999        record_jobs(state, node, round, &seat.key, &out);
12000        if let Err(e) = state.save() {
12001            tracing::warn!("could not persist a seat's completion: {e:#}");
12002        }
12003        if collected.len() <= i {
12004            collected.resize_with(i + 1, || None);
12005        }
12006        collected[i] = Some((i, seat, out));
12007    }
12008    // Belt-and-braces for the panic branch above: every seat this exact batch
12009    // started shares this `(node, attempt)` pair, and every seat that finished
12010    // normally already cleared itself, so anything left tagged with it here
12011    // can only be a panicked task's leftover. Cleared unconditionally rather
12012    // than left to read as still answering forever.
12013    if state
12014        .active
12015        .values()
12016        .any(|a| a.node == node && a.attempt == attempt)
12017    {
12018        state
12019            .active
12020            .retain(|_, a| !(a.node == node && a.attempt == attempt));
12021        if let Err(e) = state.save() {
12022            tracing::warn!("could not persist the end of a wave: {e:#}");
12023        }
12024    }
12025    // Whether or not the lease above was actually held, several worktrees
12026    // may just have built into the cache with nothing here able to name one
12027    // coherent (worktree, head) for it - see `cache::invalidate_identity`'s
12028    // own doc. Forgetting the old record costs the next `e2e`/`gate` one
12029    // clean it might not have strictly needed; trusting a stale match would
12030    // cost it a wrong answer.
12031    if let Some(cache_dir) = cache
12032        && jobs_had_a_writer
12033    {
12034        crate::cache::invalidate_identity(&crate::run::home(), cache_dir);
12035    }
12036    if let Some(guard) = cache_guard {
12037        guard.release();
12038    }
12039    collected.into_iter().flatten().collect()
12040}
12041
12042/// Fold one seat's [`agent::CommandEvidence`] (if its outcome carries any)
12043/// into the run's [`JobRecord`] log — every node, every seat, uniformly:
12044/// this is data collection, not the fix-specific completion contract in
12045/// [`Runner::continue_fix_report`], and applies regardless of which node
12046/// asked.
12047///
12048/// Only `AgentOutcome::Ok`/`Quota`/`Dropped` carry an [`AgentOutput`] to read
12049/// evidence from; `Failed` does not, and correctly contributes nothing — a
12050/// timeout or crash is not itself evidence about a command the seat may have
12051/// started.
12052fn record_jobs(
12053    state: &mut RunState,
12054    node: &str,
12055    round: Option<usize>,
12056    seat: &str,
12057    out: &AgentOutcome,
12058) {
12059    let commands: &[agent::CommandEvidence] = match out {
12060        AgentOutcome::Ok(o) | AgentOutcome::Quota(o) | AgentOutcome::Dropped(o) => &o.commands,
12061        AgentOutcome::Failed(_) | AgentOutcome::ResourceBlocked(_) => &[],
12062    };
12063    let checked_at = Timestamp::now();
12064    for c in commands {
12065        state.jobs.push(JobRecord {
12066            node: node.to_owned(),
12067            round,
12068            seat: seat.to_owned(),
12069            id: c.id.clone(),
12070            description: c.description.clone(),
12071            checked_at,
12072            status: match c.exit_code {
12073                Some(0) => JobStatus::Completed,
12074                Some(_) => JobStatus::Failed,
12075                None => JobStatus::Unknown,
12076            },
12077            exit_code: c.exit_code,
12078            result_summary: c.result_summary.clone(),
12079            source: c.source.clone(),
12080        });
12081    }
12082}
12083
12084/// Is a review round clean, given how many reviewer seats answered against
12085/// how many the round expected?
12086///
12087/// A seat that never answered (timeout, crash, unparsable output) is not a
12088/// seat that read the patch and found nothing — treating it as such is
12089/// exactly the bug this function exists to close. Under the default `block`
12090/// policy a missing seat can never be clean; `warn` still requires the seats
12091/// that *did* answer to have found nothing blocking and verification to be
12092/// green.
12093///
12094/// `quota_missing` narrows that `block` default for exactly one cause of
12095/// absence: a seat lost to its own rate limit this round. Re-reviewing hoping
12096/// a session limit lifts by the very next round buys nothing — the seat is
12097/// asked again with the same quota — so once every missing seat is accounted
12098/// for by a quota loss (and at least one seat *did* answer, so a decision has
12099/// something to rest on) the round is decided on the panel that could answer,
12100/// same as `warn` would. A panel that lost every seat to quota is not
12101/// decided here: `answered == 0` falls through to the existing `block`
12102/// fallback so a fully collapsed panel still waits rather than landing on no
12103/// review at all.
12104fn round_is_clean(
12105    blocking: usize,
12106    e2e_ok: bool,
12107    answered: usize,
12108    expected: usize,
12109    quota_missing: usize,
12110    policy: IncompleteReviewPolicy,
12111) -> bool {
12112    if blocking != 0 || !e2e_ok {
12113        return false;
12114    }
12115    if answered == expected || policy == IncompleteReviewPolicy::Warn {
12116        return true;
12117    }
12118    answered > 0 && expected - answered <= quota_missing
12119}
12120
12121/// The review loop's own conclusion, derived entirely from its persisted
12122/// round records and the round budget that produced them — never from
12123/// `status`, so a reentry (or `gate`/`merge` reading it independently)
12124/// recomputes the identical answer regardless of what an earlier node in the
12125/// same walk, or a previous walk, did to `status`.
12126///
12127/// `None` while more rounds remain to try, including when review never ran
12128/// at all (`review_rounds = 0`, or nothing yet recorded). Once a round has
12129/// gone clean, or the budget is spent, or the tree has stopped moving (see
12130/// [`STAGNANT_LIMIT`]), the answer is one of two things:
12131///
12132/// - An incomplete panel that raised nothing is missing input, not a
12133///   verified tree — never a hand-off candidate, whatever verification said
12134///   (see [`ReviewRound::incomplete`], `IncompleteReviewPolicy`).
12135/// - Otherwise, green e2e on the last round hands off (see
12136///   [`Runner::stop_reviewing`]); red e2e blocks.
12137///
12138/// A last round whose own verification is still `ResourceBlocked` — magi
12139/// itself never got a command to run, not evidence the patch is broken —
12140/// is neither: this returns `None` for it too, the same as "more rounds
12141/// remain", so a reentry retries the check (see `Runner::review_loop`'s own
12142/// handling of that shape) instead of this cheap recomputation guessing a
12143/// verdict a real attempt never produced.
12144pub(crate) fn review_conclusion(reviews: &[ReviewRound], max_rounds: usize) -> Option<RunStatus> {
12145    if max_rounds == 0
12146        || reviews.last().is_some_and(|r| {
12147            r.clean && matches!(r.e2e_status(), E2eStatus::Passed | E2eStatus::NotConfigured)
12148        })
12149    {
12150        return Some(RunStatus::Gating);
12151    }
12152    let last = reviews.last()?;
12153    let stagnant = reviews.iter().rev().take_while(|r| !r.progressed).count() >= STAGNANT_LIMIT;
12154    if reviews.len() < max_rounds && !stagnant {
12155        return None;
12156    }
12157    if last.incomplete() && last.blocking == 0 {
12158        return Some(RunStatus::Blocked);
12159    }
12160    if last.e2e_status() == E2eStatus::ResourceBlocked
12161        || (last.e2e_status() == E2eStatus::Deferred && last.blocking == 0 && last.fix.is_none())
12162    {
12163        return None;
12164    }
12165    Some(if last.e2e.iter().all(CommandOutcome::ok) {
12166        RunStatus::Gating
12167    } else {
12168        RunStatus::Blocked
12169    })
12170}
12171
12172/// How long a re-ask may take, given the budget the first attempt had.
12173///
12174/// A `nudged` retry is a request to restate an answer the seat has already
12175/// worked out: it carries no new work, so it does not deserve the original
12176/// budget. Measured on run 01c2, two judges restated their ranking in 41 and
12177/// 133 seconds while a third sat for over ten minutes on a resumed session
12178/// holding 410 KB of prior output - and because the retry had inherited the
12179/// full 1200s judge timeout, one stuck nudge nearly doubled the wall time of a
12180/// judging round whose other seats were long finished.
12181///
12182/// A quarter of the budget, with a floor so that a deliberately short timeout
12183/// does not collapse to nothing. A retry that re-sends the whole prompt
12184/// (because the seat kept no context) is the original job again, and keeps the
12185/// original budget.
12186pub(crate) fn retry_budget(full: Duration, nudged: bool) -> Duration {
12187    if nudged {
12188        (full / 4).max(Duration::from_secs(120)).min(full)
12189    } else {
12190        full
12191    }
12192}
12193
12194/// Run a wave and parse each reply, re-asking the seats whose reply was
12195/// unusable.
12196///
12197/// The re-ask is a nudge rather than the whole prompt again when the seat still
12198/// holds its conversation, which is the difference between a cheap retry and
12199/// paying for the entire candidate set twice.
12200///
12201/// A seat whose agent *fails* (rate limit, timeout, any other error) and has a
12202/// successor in `roster` is handed to it instead of being re-asked: the
12203/// handover is the retry. A seat with no successor left (a single-agent
12204/// roster, the roster's tail) is nudged as before, up to `retries` times. So
12205/// the asks to one seat in one node number at most
12206/// `roster.len().max(1) * (1 + retries)`; an agent that still has a successor
12207/// is asked once (a dropped stream is nudged first), and only the last agent
12208/// of the chain gets the `retries` same-agent nudges. Each roster agent is
12209/// tried at most once per seat, walking forward from the seat's own position and never wrapping
12210/// ([`next_untried_in_roster`]); a quota or timeout always hands over, any
12211/// other failure stops the chain when the previous agent failed the same way
12212/// ([`should_hand_over`]). The new agent takes a fresh [`SeatState`], so
12213/// [`has_context`] is false and the job's own full prompt and full budget are
12214/// sent. A seat whose chain ends on a quota records one [`QuotaLoss`] (the
12215/// intermediate ones are not losses) and is returned as a failure like any
12216/// other absent seat — the caller decides whether the panel still has a
12217/// quorum. An empty `roster` disables handover: failures are nudged as they
12218/// always were, and a quota is simply lost. A reply that fails to parse or
12219/// validate is the prompt's doing and is only ever nudged, never handed over.
12220///
12221/// The returned [`SeatState`] names the agent that answered (or tried last).
12222#[allow(clippy::too_many_arguments)]
12223async fn ask_json_wave<T>(
12224    jobs: Vec<SeatJob>,
12225    sem: Arc<Semaphore>,
12226    retries: usize,
12227    roster: &[AgentSpec],
12228    ctx: &WaveCtx<'_>,
12229    losses: &mut Vec<QuotaLoss>,
12230    state: &mut RunState,
12231    validate: &(dyn Fn(&T) -> Result<()> + Send + Sync),
12232) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
12233where
12234    T: serde::de::DeserializeOwned + Send + 'static,
12235{
12236    ask_wave_with(
12237        jobs,
12238        sem,
12239        retries,
12240        roster,
12241        ctx,
12242        losses,
12243        state,
12244        &|text: &str| {
12245            let v = verdict::extract_json::<T>(text)?;
12246            validate(&v)?;
12247            Ok(v)
12248        },
12249    )
12250    .await
12251}
12252
12253/// [`ask_json_wave`] with the reading of an answer supplied by the caller, so
12254/// a node whose answer is prose (deliberation) shares the same handover,
12255/// failure classification, quota bookkeeping and bounds instead of a copy.
12256///
12257/// A seat handed to another roster agent is sent the job's `handover` prompt
12258/// (when it has one) rather than `prompt`: the new agent has no session, so a
12259/// resume-style prompt would be incomplete. That holds for the handover ask
12260/// and for every nudge to that agent whose `has_context` is false.
12261#[allow(clippy::too_many_arguments)]
12262async fn ask_wave_with<T>(
12263    jobs: Vec<SeatJob>,
12264    sem: Arc<Semaphore>,
12265    retries: usize,
12266    roster: &[AgentSpec],
12267    ctx: &WaveCtx<'_>,
12268    losses: &mut Vec<QuotaLoss>,
12269    state: &mut RunState,
12270    parse: &(dyn Fn(&str) -> Result<T> + Send + Sync),
12271) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
12272where
12273    T: Send + 'static,
12274{
12275    let n = jobs.len();
12276    let originals: Vec<SeatJob> = jobs;
12277    let mut seats: Vec<SeatState> = originals.iter().map(|j| j.seat.clone()).collect();
12278    let mut done: Vec<Option<Result<(T, AgentOutput)>>> = (0..n).map(|_| None).collect();
12279    // Nudges each seat's *current* agent has taken — 0 for a first-ask
12280    // answer, N once it has gone through N nudges. Read back once this
12281    // returns, so a caller building a history record (`ReviewRecord`) can
12282    // tell "never answered" (`failed: Some(_)`, `attempts == 0`) apart from
12283    // "recovered after a nudge" (`failed: None`, `attempts > 0`) — see that
12284    // field's own doc.
12285    let mut nudges: Vec<usize> = vec![0; n];
12286    // The agent now occupying each seat, the ids it has already been through,
12287    // where in the roster the walk began, the class of the last failure, and
12288    // the stem word of a handover not yet asked (full prompt, full budget).
12289    let mut specs: Vec<AgentSpec> = originals.iter().map(|j| j.spec.clone()).collect();
12290    let mut tried: Vec<BTreeSet<String>> = specs
12291        .iter()
12292        .map(|s| BTreeSet::from([s.id.clone()]))
12293        .collect();
12294    let starts: Vec<usize> = specs
12295        .iter()
12296        .map(|s| roster.iter().position(|r| r.id == s.id).unwrap_or(0))
12297        .collect();
12298    let carry = ctx.carry_seats && !roster.is_empty();
12299    // Carried across rounds: ids that failed the seat earlier, and how the
12300    // last failure went (so a repeat of it is not handed over again).
12301    let carried: Vec<BTreeSet<String>> = originals
12302        .iter()
12303        .map(|j| {
12304            state
12305                .seat_history
12306                .get(&j.seat.key)
12307                .filter(|_| carry)
12308                .map(|h| h.failed.clone())
12309                .unwrap_or_default()
12310        })
12311        .collect();
12312    let mut prev: Vec<Option<FailClass>> = originals
12313        .iter()
12314        .map(|j| {
12315            state
12316                .seat_history
12317                .get(&j.seat.key)
12318                .filter(|_| carry)
12319                .and_then(|h| h.last_fail.clone())
12320        })
12321        .collect();
12322    let next_agent =
12323        |i: usize, tried: &BTreeSet<String>, specs: &[AgentSpec]| -> Option<AgentSpec> {
12324            let others: BTreeSet<String> = specs
12325                .iter()
12326                .enumerate()
12327                .filter(|(j, _)| *j != i)
12328                .map(|(_, s)| s.id.clone())
12329                .collect();
12330            pick_successor(
12331                roster,
12332                starts[i],
12333                tried,
12334                carry.then(|| &carried[i]),
12335                &others,
12336            )
12337            .cloned()
12338        };
12339    let mut fresh: Vec<Option<String>> = vec![None; n];
12340    let mut last_quota: Vec<Option<agent::Quota>> = vec![None; n];
12341    let mut pending: Vec<usize> = (0..n).collect();
12342
12343    // Per seat the work is bounded by `roster.len().max(1) * (1 + retries)`
12344    // asks: an agent with a successor is asked once and handed over, and only
12345    // a seat with no successor spends `retries` nudges on the same agent. This
12346    // only guarantees the loop's own termination whatever those say.
12347    let max_rounds = (retries + 1) * roster.len().max(1) + 1;
12348    for round in 0..max_rounds {
12349        if pending.is_empty() {
12350            break;
12351        }
12352        let mut batch = Vec::with_capacity(pending.len());
12353        let mut renudged: Vec<&str> = Vec::new();
12354        for &i in &pending {
12355            let src = &originals[i];
12356            // A seat now held by another agent than the job named has no
12357            // session of its own: it gets the full-context prompt whenever
12358            // it is asked in full (the handover ask, a nudge it cannot
12359            // resume).
12360            let full: &str = match &src.handover {
12361                Some(h) if specs[i].id != src.spec.id => h,
12362                _ => &src.prompt,
12363            };
12364            // The prompt and the budget are one decision: a nudge restates
12365            // finished work, a re-sent prompt redoes it.
12366            let (prompt, timeout, stem) = if let Some(word) = fresh[i].take() {
12367                (
12368                    full.to_owned(),
12369                    src.timeout,
12370                    format!("{}-{word}-{}", src.stem, specs[i].id),
12371                )
12372            } else if nudges[i] == 0 {
12373                (full.to_owned(), src.timeout, src.stem.clone())
12374            } else {
12375                renudged.push(src.seat.key.as_str());
12376                let why = done[i]
12377                    .as_ref()
12378                    .and_then(|r| r.as_ref().err().map(ToString::to_string))
12379                    .unwrap_or_else(|| "no parsable answer".to_owned());
12380                let nudge = prompt::nudge(&why);
12381                let nudged = has_context(&specs[i], &seats[i], src.sessions);
12382                let prompt = if nudged {
12383                    nudge
12384                } else {
12385                    format!("{full}\n\n---\n\n{nudge}")
12386                };
12387                (
12388                    prompt,
12389                    retry_budget(src.timeout, nudged),
12390                    format!("{}-retry{}", src.stem, nudges[i]),
12391                )
12392            };
12393            batch.push(SeatJob {
12394                spec: specs[i].clone(),
12395                seat: seats[i].clone(),
12396                cwd: src.cwd.clone(),
12397                prompt,
12398                timeout,
12399                allow_write: src.allow_write,
12400                sessions: src.sessions,
12401                artifacts: src.artifacts.clone(),
12402                stem,
12403                handover: None,
12404            });
12405        }
12406
12407        if !renudged.is_empty() {
12408            state.event(
12409                ctx.node,
12410                format!("retry {round}: re-asking {}", renudged.join(", ")),
12411            );
12412        }
12413        let results = wave(batch, Arc::clone(&sem), ctx, state, round).await;
12414        let mut still = Vec::new();
12415        for (&i, (_wi, seat, out)) in pending.iter().zip(results) {
12416            seats[i] = seat;
12417            // No agent was asked: nothing to hand over, nudge, remember or
12418            // charge. The caller sees `resource_block` and stops the node.
12419            if let AgentOutcome::ResourceBlocked(why) = &out {
12420                done[i] = Some(Err(anyhow::anyhow!("{why}")));
12421                continue;
12422            }
12423            let class = FailClass::of(&out);
12424            // A dropped stream is nudged first (the conversation is still
12425            // there to pick up); only a seat whose nudges are spent hands over.
12426            let nudge_first = matches!(out, AgentOutcome::Dropped(_))
12427                && nudges[i] < retries
12428                && !roster.is_empty();
12429            if let Some(cur) = class.clone().filter(|_| !roster.is_empty() && !nudge_first) {
12430                let next = should_hand_over(prev[i].as_ref(), &cur)
12431                    .then(|| next_agent(i, &tried[i], &specs))
12432                    .flatten();
12433                if carry {
12434                    let h = state
12435                        .seat_history
12436                        .entry(originals[i].seat.key.clone())
12437                        .or_default();
12438                    h.failed.insert(specs[i].id.clone());
12439                    h.last_fail = Some(cur.clone());
12440                    if h.last_ok.as_deref() == Some(specs[i].id.as_str()) {
12441                        h.last_ok = None;
12442                    }
12443                    // Saved before the next agent is asked, so a restart in
12444                    // between does not forget who failed.
12445                    if let Err(e) = state.save() {
12446                        tracing::warn!("could not persist a seat's failure history: {e:#}");
12447                    }
12448                }
12449                if let Some(next) = next {
12450                    record_handover(
12451                        state,
12452                        ctx.node,
12453                        &originals[i].seat.key,
12454                        &specs[i].id,
12455                        &next.id,
12456                        &cur,
12457                        &fail_reason(&out),
12458                    );
12459                    tried[i].insert(next.id.clone());
12460                    prev[i] = Some(cur.clone());
12461                    seats[i] =
12462                        handover_seat(&originals[i].seat.key, &next.id, state.next_seat_seed());
12463                    specs[i] = next;
12464                    fresh[i] = Some(cur.stem_word().to_owned());
12465                    nudges[i] = 0;
12466                    done[i] = Some(Err(anyhow::anyhow!(
12467                        "handed over after: {}",
12468                        fail_reason(&out)
12469                    )));
12470                    still.push(i);
12471                    continue;
12472                }
12473            }
12474            if carry
12475                && !nudge_first
12476                && let Some(cur) = class.clone()
12477            {
12478                // The chain ended here (no successor, or a repeated failure).
12479                let h = state
12480                    .seat_history
12481                    .entry(originals[i].seat.key.clone())
12482                    .or_default();
12483                h.failed.insert(specs[i].id.clone());
12484                h.last_fail = Some(cur);
12485            }
12486            let parsed = match out {
12487                AgentOutcome::Ok(o) => parse(&o.text).map(|v| (v, o)),
12488                AgentOutcome::Quota(o) => {
12489                    last_quota[i] = o.quota.clone();
12490                    Err(anyhow::anyhow!("rate limited (quota); not retrying now"))
12491                }
12492                // Not a parseable answer: the nudge loop re-asks it, which is
12493                // exactly what a dropped stream needs. Just don't hand its raw
12494                // error JSON to `extract_json`.
12495                AgentOutcome::Dropped(o) => {
12496                    let why = o
12497                        .dropped
12498                        .as_ref()
12499                        .map(|d| d.why.as_str())
12500                        .unwrap_or("the CLI ended the stream without delivering its answer");
12501                    Err(anyhow::anyhow!("the CLI dropped the stream ({why})"))
12502                }
12503                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
12504                    Err(anyhow::anyhow!(e))
12505                }
12506            };
12507            let quota = class == Some(FailClass::Quota);
12508            let failed = parsed.is_err();
12509            if !failed && matches!(ctx.node, "judge" | "vote") {
12510                // A validated answer restores this seat's quorum presence,
12511                // including on the normal path after an all-seat block.
12512                state
12513                    .quota
12514                    .retain(|loss| loss.seat != originals[i].seat.key);
12515            }
12516            done[i] = Some(parsed);
12517            if carry && !failed {
12518                let h = state
12519                    .seat_history
12520                    .entry(originals[i].seat.key.clone())
12521                    .or_default();
12522                h.failed.remove(&specs[i].id);
12523                h.last_ok = Some(specs[i].id.clone());
12524                h.last_fail = None;
12525            }
12526            // Do not re-ask a rate-limited seat (quota) — a retry is known to
12527            // fail the same way; and never re-ask a seat that already parsed.
12528            // A failed agent that still has a successor is not re-asked
12529            // either: the handover was its remedy and has just been refused
12530            // (the chain stops on a repeated failure class). A seat with no
12531            // successor left (a single-agent roster, the roster's tail, or an
12532            // empty roster) keeps the same-agent nudge, bounded by `retries`.
12533            let agent_failure = class.is_some()
12534                && !nudge_first
12535                && !roster.is_empty()
12536                && next_agent(i, &tried[i], &specs).is_some();
12537            if failed && !quota && !agent_failure && nudges[i] < retries {
12538                nudges[i] += 1;
12539                still.push(i);
12540            }
12541        }
12542        pending = still;
12543    }
12544
12545    // One loss per seat whose chain ended on a quota: the intermediate ones
12546    // were absorbed by a handover and are not losses.
12547    for (i, q) in last_quota.into_iter().enumerate() {
12548        if let Some(quota) = q {
12549            losses.push(QuotaLoss::from_report(
12550                originals[i].seat.key.clone(),
12551                ctx.node,
12552                Some(&quota),
12553            ));
12554        }
12555    }
12556
12557    // A stalled quorum already has its own recovery checkpoint. Refresh
12558    // its missing seats before deciding whether it can resume.
12559    if state.status != RunStatus::Stalled
12560        && ctx.node != "deliberate"
12561        && n > 0
12562        && losses.len() == n
12563        && done.iter().all(|r| r.as_ref().is_some_and(Result::is_err))
12564    {
12565        block_machine_outage(state, ctx.node, losses);
12566        state.quota.append(losses);
12567    }
12568
12569    seats
12570        .into_iter()
12571        .zip(done)
12572        .zip(nudges)
12573        .map(|((seat, res), attempts)| {
12574            (
12575                seat,
12576                res.unwrap_or_else(|| Err(anyhow::anyhow!("no attempt was made"))),
12577                attempts,
12578            )
12579        })
12580        .collect()
12581}
12582
12583/// A node with no available agent has no task verdict. Preserve the node
12584/// checkpoint and record why a subsequent explicit resume is needed.
12585pub(crate) fn block_machine_outage(state: &mut RunState, node: &str, losses: &[QuotaLoss]) {
12586    let mut auth: Vec<_> = losses
12587        .iter()
12588        .filter(|loss| loss.cause == agent::QuotaCause::Authentication)
12589        .map(|loss| loss.agent.clone())
12590        .collect();
12591    auth.sort();
12592    auth.dedup();
12593    let (kind, detail) = if auth.is_empty() {
12594        (
12595            "agent usage limit",
12596            "All seats reached their agent usage limits; resume after usage is available"
12597                .to_owned(),
12598        )
12599    } else {
12600        (
12601            "agent authentication",
12602            format!(
12603                "Agents {} cannot authenticate; re-authenticate these agents, then resume the held task",
12604                auth.join(", ")
12605            ),
12606        )
12607    };
12608    state.resource_block = Some(crate::run::ResourceBlock {
12609        node: node.to_owned(),
12610        kind: kind.to_owned(),
12611        cause: crate::run::ResourceBlockCause::Other,
12612        detail: detail.clone(),
12613        at: Timestamp::now(),
12614    });
12615    state.event(node, detail);
12616}
12617
12618/// Did the wave end without asking any agent (see [`block_wave`])?
12619fn wave_blocked(results: &[(usize, SeatState, AgentOutcome)]) -> bool {
12620    results
12621        .iter()
12622        .any(|(_, _, o)| matches!(o, AgentOutcome::ResourceBlocked(_)))
12623}
12624
12625/// Settle a wave that never spawned anything: every job answers
12626/// [`AgentOutcome::ResourceBlocked`], its seat leaves `active`, and nothing
12627/// else about the seat (session, history, quota) is touched.
12628fn block_wave(
12629    jobs: Vec<SeatJob>,
12630    state: &mut RunState,
12631    node: &str,
12632    attempt: usize,
12633    why: &str,
12634) -> Vec<(usize, SeatState, AgentOutcome)> {
12635    state.resource_wait = None;
12636    state
12637        .active
12638        .retain(|_, a| !(a.node == node && a.attempt == attempt));
12639    if let Err(e) = state.save() {
12640        tracing::warn!("could not persist a resource-blocked wave: {e:#}");
12641    }
12642    jobs.into_iter()
12643        .enumerate()
12644        .map(|(i, j)| (i, j.seat, AgentOutcome::ResourceBlocked(why.to_owned())))
12645        .collect()
12646}
12647
12648/// Acquire the shared build cache's lease, waiting out contention within
12649/// `budget` (never past it — see AGENTS.md's build-cache section on why an
12650/// unbounded wait is never acceptable).
12651///
12652/// A first, non-blocking check happens before ever waiting; if it finds the
12653/// lease busy, that fact is logged as a `verify` event *and* flushed with
12654/// [`RunState::save`] immediately — not only once the wait finally succeeds
12655/// or gives up — so a `magi show` run by a different process while this one
12656/// is still waiting reads a `run.json` that says so, rather than whatever it
12657/// looked like before the wait started. The same applies to the terminal
12658/// failure: logged and saved before this returns `Err`, so a caller that
12659/// could not get the lease at all still leaves a legible record of why.
12660async fn acquire_cache_lease(
12661    state: &mut RunState,
12662    cache_dir: &Path,
12663    owner: &crate::cache::Owner,
12664    budget: Duration,
12665    node: &str,
12666    context: &str,
12667    cancel: &(dyn Fn() -> bool + Sync),
12668) -> Result<Option<crate::cache::Guard>> {
12669    let home = crate::run::home();
12670    let kind = if crate::build_target::isolated(&state.config) {
12671        crate::build_target::KIND
12672    } else {
12673        "shared build cache"
12674    };
12675    let started = Instant::now();
12676    let busy = match crate::cache::try_acquire(&home, cache_dir, owner) {
12677        Ok(crate::cache::AcquireOutcome::Acquired(g)) => return Ok(Some(g)),
12678        Ok(crate::cache::AcquireOutcome::Busy(busy)) => busy,
12679        Err(e) => {
12680            state.event(
12681                "verify",
12682                format!(
12683                    "{context}: could not check the {kind} at {}: {e:#}",
12684                    cache_dir.display()
12685                ),
12686            );
12687            if let Err(e2) = state.save() {
12688                tracing::warn!("could not persist a cache-check failure: {e2:#}");
12689            }
12690            return Err(anyhow::Error::new(CacheCheckError(format!("{e:#}"))));
12691        }
12692    };
12693    state.event(
12694        "verify",
12695        format!(
12696            "{context}: waiting for the {kind} at {} ({})",
12697            cache_dir.display(),
12698            busy.describe()
12699        ),
12700    );
12701    // Seats of this node are waiting, not running: say so, so the countdown a
12702    // reader sees only ever measures an agent that has been spawned.
12703    state.resource_wait = Some(crate::run::ResourceWait {
12704        node: context.to_owned(),
12705        kind: kind.to_owned(),
12706        holder: format!("{}: {}", cache_dir.display(), busy.describe()),
12707        since: Timestamp::now(),
12708        limit_secs: budget.as_secs(),
12709    });
12710    if let Err(e) = state.save() {
12711        tracing::warn!("could not persist a cache wait: {e:#}");
12712    }
12713    let remaining = budget.saturating_sub(started.elapsed());
12714    let waited = crate::cache::wait_for_unless(
12715        &home,
12716        cache_dir,
12717        owner,
12718        remaining,
12719        Duration::from_secs(5),
12720        cancel,
12721    )
12722    .await;
12723    state.resource_wait = None;
12724    let cause = match &waited {
12725        Ok(Some(_)) => None,
12726        Ok(None) => Some(crate::run::ResourceBlockCause::Cancelled { park: None }),
12727        Err(error)
12728            if error.is::<crate::cache::WaitTimeout>() && kind == crate::build_target::KIND =>
12729        {
12730            Some(crate::run::ResourceBlockCause::IsolatedCacheTimeout {
12731                target: cache_dir.to_owned(),
12732                waited_secs: started.elapsed().as_secs(),
12733                limit_secs: budget.as_secs(),
12734            })
12735        }
12736        Err(error) if error.is::<crate::cache::WaitTimeout>() => {
12737            Some(crate::run::ResourceBlockCause::Timeout {
12738                waited_secs: started.elapsed().as_secs(),
12739                limit_secs: budget.as_secs(),
12740            })
12741        }
12742        Err(_) => Some(crate::run::ResourceBlockCause::Other),
12743    };
12744    if let Some(cause) = cause {
12745        let detail = match &waited {
12746            Ok(_) => "the wait for the build cache was cancelled".to_owned(),
12747            Err(error) => format!("{error:#}"),
12748        };
12749        state.resource_block = Some(crate::run::ResourceBlock {
12750            cause,
12751            node: node.to_owned(),
12752            kind: kind.into(),
12753            detail: format!("{}: {detail}", cache_dir.display()),
12754            at: Timestamp::now(),
12755        });
12756        state.event(
12757            "resource",
12758            state.resource_block.as_ref().unwrap().description(),
12759        );
12760    }
12761    if let Err(error) = state.save() {
12762        tracing::warn!("could not persist cache acquisition outcome: {error:#}");
12763    }
12764    waited
12765}
12766
12767/// The lease state could not be read at all (unreadable lease file, a
12768/// permission problem). Unlike a busy lease that outlasts its bound, nothing is
12769/// known to be contended, so a wave degrades to running without a shared cache
12770/// instead of stopping on a hold that [`crate::triage`] could never release.
12771#[derive(Debug)]
12772struct CacheCheckError(String);
12773
12774impl std::fmt::Display for CacheCheckError {
12775    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12776        f.write_str(&self.0)
12777    }
12778}
12779
12780impl std::error::Error for CacheCheckError {}
12781
12782/// Keep a specific acquisition outcome when the caller adds command evidence.
12783fn record_cache_error(state: &mut RunState, node: &str, error: &anyhow::Error) {
12784    let kind = if crate::build_target::isolated(&state.config) {
12785        crate::build_target::KIND
12786    } else {
12787        "shared build cache"
12788    };
12789    state
12790        .resource_block
12791        .get_or_insert_with(|| crate::run::ResourceBlock {
12792            cause: crate::run::ResourceBlockCause::Other,
12793            node: node.to_owned(),
12794            kind: kind.into(),
12795            detail: format!("{error:#}"),
12796            at: Timestamp::now(),
12797        });
12798    if let Err(error) = state.save() {
12799        tracing::warn!("could not persist cache resource block: {error:#}");
12800    }
12801}
12802
12803tokio::task_local! {
12804    static VERIFY_TARGET: PathBuf;
12805}
12806
12807/// Run `body` — a verify command batch — while holding the shared build
12808/// cache's lease, so this run's own full verification (`e2e`, `gate`) can
12809/// never interleave with another borrower's build against the same
12810/// `CARGO_TARGET_DIR`: a different run, a lingering reviewer past its
12811/// timeout, or a human's own `magi review`. See the `cache` module doc for
12812/// why this matters more than Cargo's own per-target locking covers — two
12813/// *different* worktrees building the same package name/version into one
12814/// cache directory is a staleness bug, not a lock contention one.
12815///
12816/// Cache acquisition has its own bound, `timeout_resource_wait`, just as
12817/// agent waves do. Repository scheduling also has its own bounded,
12818/// cancellable resource-wait policy. Contention must not consume the
12819/// verification budget: `body` receives the full `budget` after both leases
12820/// are acquired and the cache is fresh. Without a shared cache, only
12821/// repository coordination is acquired before handing over the full budget.
12822///
12823/// A lease that cannot be acquired within the resource wait is reported as a single
12824/// synthetic [`CommandOutcome`] (`code: None`) rather than silently skipping
12825/// verification — the same shape a spawn failure already takes in
12826/// [`run_commands`], so a caller need not special-case it.
12827#[allow(clippy::too_many_arguments)]
12828async fn with_cache_lease<'s, F, Fut>(
12829    state: &'s mut RunState,
12830    cache_dir: Option<&Path>,
12831    node: &str,
12832    seat: &str,
12833    worktree: &Path,
12834    head: &str,
12835    budget: Duration,
12836    context: &str,
12837    wait: &crate::repo_lock::WaitPolicy,
12838    body: F,
12839) -> Result<(Vec<CommandOutcome>, bool)>
12840where
12841    F: FnOnce(&'s mut RunState, Duration) -> Fut,
12842    Fut: std::future::Future<Output = (Vec<CommandOutcome>, bool, Vec<u32>)>,
12843{
12844    // Match editing waves: cache first, repository second. In particular,
12845    // pre_gate must never hold the repository while waiting for a wave's cache.
12846    let started = Instant::now();
12847    let home = crate::run::home();
12848    let isolated = crate::build_target::isolated(&state.config);
12849    let planned_target = if isolated {
12850        let plan = (|| -> Result<PathBuf> {
12851            crate::build_target::supports(&state.config)?;
12852            crate::build_target::resolve(&home, worktree)
12853        })();
12854        match plan {
12855            Ok(path) => Some(path),
12856            Err(error) => {
12857                record_cache_error(state, node, &error);
12858                return Ok((
12859                    vec![CommandOutcome {
12860                        command: "(planning isolated build cache)".into(),
12861                        code: None,
12862                        output_tail: format!("{error:#}"),
12863                        duration_ms: 0,
12864                        resource_blocked: true,
12865                        ..Default::default()
12866                    }],
12867                    false,
12868                ));
12869            }
12870        }
12871    } else {
12872        None
12873    };
12874    let cache_dir = planned_target.as_deref().or(cache_dir);
12875    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
12876    let guard = if let Some(cache_dir) = cache_dir {
12877        let owner = crate::cache::Owner::here(&state.id, node, seat, worktree, head);
12878        match acquire_cache_lease(
12879            state,
12880            cache_dir,
12881            &owner,
12882            resource_limit,
12883            node,
12884            context,
12885            &|| wait.cancelled(),
12886        )
12887        .await
12888        .and_then(|g| {
12889            g.ok_or_else(|| anyhow::anyhow!("the wait for the build cache was cancelled"))
12890        }) {
12891            Ok(g) => Some(g),
12892            Err(e) => {
12893                record_cache_error(state, node, &e);
12894                return Ok((
12895                    vec![CommandOutcome {
12896                        command: if isolated {
12897                            "(waiting for the isolated build cache)"
12898                        } else {
12899                            "(waiting for the shared build cache)"
12900                        }
12901                        .into(),
12902                        code: None,
12903                        output_tail: e.to_string(),
12904                        duration_ms: started.elapsed().as_millis() as u64,
12905                        resource_blocked: true,
12906                        ..Default::default()
12907                    }],
12908                    false,
12909                ));
12910            }
12911        }
12912    } else {
12913        None
12914    };
12915    let _coordination = coordinate_operation(state, worktree, wait).await?;
12916    if let Some(path) = &planned_target {
12917        state.event(node, format!("isolated build target: {}", path.display()));
12918    }
12919    if let Some(cache_dir) = cache_dir.filter(|_| !isolated) {
12920        let identity = crate::cache::Identity::new(worktree, head);
12921        let fresh = crate::cache::ensure_fresh(
12922            &home,
12923            cache_dir,
12924            &identity,
12925            &state.config.verify.cargo_manifests(),
12926        );
12927        if let Err(e) = fresh {
12928            record_cache_error(state, node, &e);
12929            state.event(
12930                "verify",
12931                format!(
12932                    "{context}: could not confirm the build cache matches {} at {}: {e:#}",
12933                    worktree.display(),
12934                    short(head)
12935                ),
12936            );
12937            if let Some(guard) = guard {
12938                guard.release();
12939            }
12940            return Ok((
12941                vec![CommandOutcome {
12942                    command: "(confirming the build cache is fresh)".into(),
12943                    code: None,
12944                    output_tail: e.to_string(),
12945                    duration_ms: started.elapsed().as_millis() as u64,
12946                    resource_blocked: true,
12947                    ..Default::default()
12948                }],
12949                false,
12950            ));
12951        }
12952    }
12953    let future = body(state, budget);
12954    let (outcomes, retried, timed_out_pids) = if let Some(target) = planned_target {
12955        VERIFY_TARGET.scope(target, future).await
12956    } else {
12957        future.await
12958    };
12959    if !timed_out_pids.is_empty() {
12960        wait_for_timed_out_children_to_die(&timed_out_pids).await;
12961    }
12962    // Drop repository coordination before releasing the cache, reversing the
12963    // acquisition order. A cancelled/error future also drops both guards.
12964    drop(_coordination);
12965    if let Some(guard) = guard {
12966        guard.release();
12967    }
12968    Ok((outcomes, retried))
12969}
12970
12971/// Poll `pids` — commands [`run_commands`] reports as still running when its
12972/// own timeout elapsed — until every one is confirmed gone, or
12973/// [`LEASE_RELEASE_MAX_WAIT`] passes, whichever comes first.
12974///
12975/// Real confirmation where confirmation is possible, not a substitute for
12976/// full process-tree observation: a grandchild the timed-out process spawned
12977/// and that survives independently of it is invisible to a pid check the
12978/// same way it always was, and continuing to observe and collect *that*
12979/// stays a different piece of work with its own owner. This only narrows a
12980/// fixed blind wait into an actual check of the pids this process does know
12981/// about.
12982async fn wait_for_timed_out_children_to_die(pids: &[u32]) {
12983    wait_for_pids_with(
12984        pids,
12985        crate::proc::pid_alive,
12986        LEASE_RELEASE_POLL,
12987        LEASE_RELEASE_MAX_WAIT,
12988    )
12989    .await;
12990}
12991
12992/// [`wait_for_timed_out_children_to_die`] with its liveness query, poll
12993/// interval and ceiling supplied by the caller, so the polling *logic* -
12994/// returns as soon as every pid reports dead, gives up at the ceiling
12995/// otherwise - is testable on millisecond durations without asking the real
12996/// OS about a pid at all.
12997async fn wait_for_pids_with<F: Fn(u32) -> bool>(
12998    pids: &[u32],
12999    alive: F,
13000    poll: Duration,
13001    max_wait: Duration,
13002) {
13003    let deadline = Instant::now() + max_wait;
13004    loop {
13005        if pids.iter().all(|&pid| !alive(pid)) {
13006            return;
13007        }
13008        if Instant::now() >= deadline {
13009            return;
13010        }
13011        tokio::time::sleep(poll).await;
13012    }
13013}
13014
13015/// Are any of `outcomes` [`CommandOutcome::resource_blocked`] - magi's own
13016/// admission that it could not even get a verify command to run, as opposed
13017/// to evidence the command actually produced? A caller that would otherwise
13018/// read a resource-blocked outcome as a red command must check this first:
13019/// see [`Runner::gate`], which retries rather than records `Blocked` when
13020/// this is true.
13021fn verify_inconclusive(outcomes: &[CommandOutcome]) -> bool {
13022    outcomes.iter().any(|o| o.resource_blocked)
13023}
13024
13025/// What [`Runner::gate_fix_round`] decided.
13026pub(crate) enum GateFix {
13027    /// The tree changed and `verify.e2e` is still green: run the gate again.
13028    Retry,
13029    /// No more rounds, nothing to fix, or the fix did not hold: the gate's
13030    /// last failure stands and the run ends blocked.
13031    Stop,
13032    /// `verify.e2e` could not run after the fix (magi's own contention):
13033    /// decide nothing now, a later reentry retries.
13034    Defer,
13035}
13036
13037/// Is every red command in `outcomes` an ordinary failure the code could
13038/// explain: it ran, exited non-zero, and said something?
13039///
13040/// A timeout, a spawn failure and a killed process all leave `code` `None`;
13041/// 126 / 127 are the POSIX shell's "cannot execute" / "not found". Output-free
13042/// exits carry nothing for a fixer to act on. Language-agnostic on purpose:
13043/// what the command is stays the gate's business.
13044pub(crate) fn gate_fixable(outcomes: &[CommandOutcome]) -> bool {
13045    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
13046    red.peek().is_some()
13047        && red.all(|o| {
13048            !o.resource_blocked
13049                && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
13050                && !o.output_tail.trim().is_empty()
13051        })
13052}
13053
13054/// Describe one verify command's outcome for the event log, distinguishing a
13055/// build/link failure — the toolchain never produced a binary to run — from
13056/// an actual test failure, since only the latter is a verdict on the patch.
13057fn e2e_outcome_label(o: &CommandOutcome) -> String {
13058    if o.ok() {
13059        return "pass".to_owned();
13060    }
13061    let reason = if o.build_failed() {
13062        format!("COULD NOT RUN ({:?}, build/link failure)", o.code)
13063    } else {
13064        format!("FAIL ({:?})", o.code)
13065    };
13066    format!(
13067        "{reason}\n{}",
13068        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
13069    )
13070}
13071
13072/// Does `outcomes` hold a failure worth one more run on the same commit?
13073///
13074/// Only an ordinary test result qualifies: every red command ran, exited
13075/// non-zero and said which way (not a build/link failure, a timeout or kill,
13076/// a spawn failure, the shell's own 126 / 127, or a resource block). Those are
13077/// evidence about the machine or the toolchain, never about a flaky test.
13078fn rerunnable_failure(outcomes: &[CommandOutcome]) -> bool {
13079    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
13080    red.peek().is_some()
13081        && !verify_inconclusive(outcomes)
13082        && red.all(|o| {
13083            !o.build_failed() && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
13084        })
13085}
13086
13087/// Run `verify.e2e`, retrying once if the first attempt could not build or
13088/// link — a build/link failure is frequently a race against a shared
13089/// `CARGO_TARGET_DIR` (see AGENTS.md), not a verdict on the patch. Emits one
13090/// `verify` event per command, tagged with `context` (normally `"round N"`)
13091/// so the call sites that need this — the ordinary per-round leg in
13092/// `review_loop`, the deferred catch-up run `stop_reviewing` makes before it
13093/// will ever call a round green, `verify_current_head` and the gate-repair
13094/// check — read identically in the event log.
13095///
13096/// A failure that is a test result (see [`rerunnable_failure`]) is believed
13097/// only after the failed commands have run once more on the same commit, in
13098/// the same worktree and — because the caller holds it around this whole
13099/// function — under the same cache lease, with a full `timeout` of their own
13100/// (`[graph] rerun_failed_e2e`). A command that passes the second time is a
13101/// flake: the head is verified, the first failure is recorded and filed
13102/// (`crate::flake`, `RunState::verify_flakes`). A command that fails again
13103/// stays red and records a structured [`crate::verify_evidence::RerunComparison`]
13104/// preserving bounded evidence and artifact references for both attempts;
13105/// it claims a matching reproduction only when both attempts yield identical
13106/// confirmed terminal test failures. One verification is therefore run at most
13107/// three times: the build/link retry, then this one rerun. `round` is the
13108/// review round the verification belongs to, if any.
13109async fn run_e2e_with_retry(
13110    state: &mut RunState,
13111    shell: &[String],
13112    commands: &[String],
13113    worktree: &Path,
13114    timeout: Duration,
13115    context: &str,
13116    round: Option<usize>,
13117) -> (Vec<CommandOutcome>, bool, Vec<u32>) {
13118    let (mut e2e, mut timed_out_pids) = run_commands(
13119        state, "verify", "e2e", 0, shell, commands, worktree, timeout,
13120    )
13121    .await;
13122    for o in &e2e {
13123        state.event(
13124            "verify",
13125            format!("{context}: `{}` -> {}", o.command, e2e_outcome_label(o)),
13126        );
13127    }
13128    // A build/link failure is not a verdict on the patch — it is frequently a
13129    // race against a shared `CARGO_TARGET_DIR` (see AGENTS.md). Give verify
13130    // one retry before letting a red like that decide the round.
13131    let verify_retried = e2e.iter().any(CommandOutcome::build_failed);
13132    if verify_retried {
13133        state.event(
13134            "verify",
13135            format!(
13136                "{context}: verify could not build/link, not a test result — retrying once \
13137                 before concluding"
13138            ),
13139        );
13140        let retried = run_commands(
13141            state, "verify", "e2e", 1, shell, commands, worktree, timeout,
13142        )
13143        .await;
13144        e2e = retried.0;
13145        // Both attempts' timeouts matter, not just the last one: the first
13146        // attempt's descendants may still be alive alongside the retry's.
13147        timed_out_pids.extend(retried.1);
13148        for o in &e2e {
13149            state.event(
13150                "verify",
13151                format!(
13152                    "{context}: retry `{}` -> {}",
13153                    o.command,
13154                    e2e_outcome_label(o)
13155                ),
13156            );
13157        }
13158    }
13159    if state.config.graph.rerun_failed_e2e && rerunnable_failure(&e2e) {
13160        let failed: Vec<usize> = (0..e2e.len()).filter(|&i| !e2e[i].ok()).collect();
13161        let rerun_commands: Vec<String> = failed.iter().map(|&i| e2e[i].command.clone()).collect();
13162        let head = git::rev_parse(worktree, "HEAD").await.unwrap_or_default();
13163        state.event(
13164            "verify",
13165            format!(
13166                "{context}: {} failed with a test result — running it once more on the same \
13167                 commit {} before deciding",
13168                rerun_commands
13169                    .iter()
13170                    .map(|c| format!("`{c}`"))
13171                    .collect::<Vec<_>>()
13172                    .join(", "),
13173                short(&head)
13174            ),
13175        );
13176        let (second, pids) = run_commands(
13177            state,
13178            "verify",
13179            "e2e",
13180            1 + usize::from(verify_retried),
13181            shell,
13182            &rerun_commands,
13183            worktree,
13184            timeout,
13185        )
13186        .await;
13187        timed_out_pids.extend(pids);
13188        for o in &second {
13189            state.event(
13190                "verify",
13191                format!(
13192                    "{context}: rerun `{}` -> {}",
13193                    o.command,
13194                    e2e_outcome_label(o)
13195                ),
13196            );
13197        }
13198        for (slot, &i) in failed.iter().enumerate() {
13199            let Some(again) = second.get(slot) else {
13200                break;
13201            };
13202            let first = std::mem::replace(&mut e2e[i], again.clone());
13203            if again.ok() {
13204                let signature = crate::flake::signature(&first.output_tail, first.code);
13205                let flake = crate::run::VerifyFlake {
13206                    round,
13207                    context: context.to_owned(),
13208                    head: head.clone(),
13209                    command: first.command.clone(),
13210                    first_failure: summarize_verify(&first.output_tail, EVENT_OUTPUT_TAIL),
13211                    fingerprint: crate::flake::fingerprint(&state.repo, &signature),
13212                    at: Timestamp::now(),
13213                    task: None,
13214                    filed: false,
13215                    filing_error: None,
13216                };
13217                crate::flake::record(state, flake, &signature.label, &crate::queue::Queue::open());
13218            } else if !again.resource_blocked {
13219                let comparison = crate::verify_evidence::compare_attempts(&head, &first, again);
13220                let message = crate::verify_evidence::rerun_event_message(
13221                    context,
13222                    &e2e[i].command,
13223                    &comparison,
13224                );
13225                e2e[i].rerun_comparison = Some(comparison);
13226                state.event("verify", message);
13227            }
13228        }
13229    }
13230    (e2e, verify_retried, timed_out_pids)
13231}
13232
13233/// Run configured shell commands in `cwd`, in order. The second element is
13234/// the pid of every command that hit `timeout` and was still running when
13235/// this stopped waiting on it (best-effort: `None` when the platform did not
13236/// hand one back) — see [`with_cache_lease`]'s use of it for why a caller
13237/// that releases a shared resource afterward needs to know.
13238///
13239/// Records `task` into [`RunState::active`] at every command boundary
13240/// (`RunState::task_command`) and clears it once the whole list has run
13241/// (`RunState::task_finished`) — a `verify.e2e` / `verify.gate` list can run
13242/// for minutes with no seat and no output of its own to show for it (see
13243/// `CommandOutcome`'s doc on why an empty `e2e`/`gate` alone cannot be told
13244/// apart from "not yet run" without this), and this is the only place that
13245/// knows which command is running right now and how many are left. Three
13246/// saves per command — start, not per second — matching the same "only at a
13247/// boundary" rule [`wave`] already follows for seats.
13248#[allow(clippy::too_many_arguments)]
13249async fn run_commands(
13250    state: &mut RunState,
13251    node: &str,
13252    task: &str,
13253    attempt: usize,
13254    shell: &[String],
13255    commands: &[String],
13256    cwd: &Path,
13257    timeout: Duration,
13258) -> (Vec<CommandOutcome>, Vec<u32>) {
13259    let isolated = crate::build_target::isolated(&state.config);
13260    if isolated && let Some(block) = &state.resource_block {
13261        return (
13262            vec![CommandOutcome {
13263                command: "(isolated build admission)".into(),
13264                code: None,
13265                output_tail: block.description(),
13266                duration_ms: 0,
13267                resource_blocked: true,
13268                ..Default::default()
13269            }],
13270            Vec::new(),
13271        );
13272    }
13273    if commands.is_empty() {
13274        // Nothing to mark as running and nothing to clear — an empty list
13275        // means "not configured", and touching `active` (or the disk) over
13276        // that would be a write for every round of a repo with no
13277        // `verify.e2e` / `verify.gate` commands at all.
13278        return (Vec::new(), Vec::new());
13279    }
13280    let mut out = Vec::new();
13281    let mut timed_out_pids = Vec::new();
13282    let total = commands.len();
13283    for (idx, command) in commands.iter().enumerate() {
13284        state.task_command(task, node, attempt, command, idx + 1, total, timeout);
13285        if let Err(e) = state.save() {
13286            tracing::warn!("could not persist an in-progress {task} command: {e:#}");
13287        }
13288        let started = Instant::now();
13289        let mut cmd = tokio::process::Command::new(&shell[0]);
13290        cmd.quiet();
13291        // Verify the checkout as a standalone caller. Worker ownership and
13292        // pinned executable selection belong to this driver, not to tests or
13293        // tools it runs. Preserve home/seat context and Running's containment.
13294        for key in crate::worker::INVOCATION_ENV {
13295            cmd.env_remove(key);
13296        }
13297        cmd.env_remove(crate::build_id::EXPECT_ENV);
13298        cmd.args(&shell[1..])
13299            .current_dir(cwd)
13300            .stdin(std::process::Stdio::null())
13301            .stdout(std::process::Stdio::piped())
13302            .stderr(std::process::Stdio::piped())
13303            .kill_on_drop(true);
13304        let mut outputs = Vec::new();
13305        let mut cache = None;
13306        let home = crate::run::home();
13307        let head = if isolated {
13308            Some(git::rev_parse(cwd, "HEAD").await)
13309        } else {
13310            None
13311        };
13312        let protected = (|| -> Result<()> {
13313            crate::incremental::configure(&mut cmd, cwd)?;
13314            cache = if isolated {
13315                let target = VERIFY_TARGET
13316                    .try_with(Clone::clone)
13317                    .context("isolated verification has no target lease")?;
13318                cmd.arg(crate::build_target::command::normalize(command)?);
13319                crate::build_target::command::configure(&mut cmd, &target)?;
13320                Some(target)
13321            } else {
13322                crate::build_target::command::clear(&mut cmd)?;
13323                cmd.arg(command);
13324                state.config.cache_dir()
13325            };
13326            let mut paths = vec![cwd.to_owned()];
13327            if let Some(cache) = &cache {
13328                paths.push(cache.clone());
13329            }
13330            let admit = if isolated {
13331                crate::retention::OutputLease::admit_isolated
13332            } else {
13333                crate::retention::OutputLease::admit
13334            };
13335            outputs.extend(admit(&home, &paths, state.config.disk.min_free_bytes)?);
13336            if let Some(guard) = crate::retention::OutputLease::borrow(cwd)? {
13337                outputs.push(guard);
13338            }
13339            if let Some(cache) = &cache {
13340                outputs.push(crate::retention::OutputLease::cache(
13341                    &crate::run::home(),
13342                    cache,
13343                    false,
13344                )?);
13345                if let Some(head) = head {
13346                    crate::build_target::ensure_fresh(&home, cache, cwd, &head?, &state.config)?;
13347                    if task == "pre_gate" {
13348                        crate::cache::invalidate_identity(&home, cache);
13349                    }
13350                }
13351            }
13352            Ok(())
13353        })();
13354        if let Err(e) = protected {
13355            let detail = format!("execution admission unavailable: {e:#}");
13356            state.resource_block = Some(crate::run::ResourceBlock {
13357                cause: crate::run::ResourceBlockCause::Other,
13358                node: node.to_owned(),
13359                kind: if detail.contains("disk admission") {
13360                    "disk admission"
13361                } else {
13362                    "output ownership"
13363                }
13364                .to_owned(),
13365                detail: detail.clone(),
13366                at: Timestamp::now(),
13367            });
13368            out.push(CommandOutcome {
13369                command: command.clone(),
13370                code: None,
13371                output_tail: detail,
13372                duration_ms: 0,
13373                resource_blocked: true,
13374                ..Default::default()
13375            });
13376            break;
13377        }
13378        let spawned = if isolated {
13379            crate::seat_process::Running::spawn_build(cmd, None, outputs)
13380        } else {
13381            crate::seat_process::Running::spawn(cmd, None, outputs)
13382        };
13383        let (code, out_text, err_text, body) = match spawned {
13384            Ok(mut running) => {
13385                let pid = running.child().id();
13386                let (stdout, out_reader) = agent::drain(running.child().stdout.take());
13387                let (stderr, err_reader) = agent::drain(running.child().stderr.take());
13388                let mut paths = vec![cwd.to_owned()];
13389                if let Some(cache) = cache {
13390                    paths.push(cache);
13391                }
13392                let mut pressure = None;
13393                let status = tokio::select! {
13394                    status = tokio::time::timeout(timeout, running.child().wait()) => Some(status),
13395                    reason = crate::retention::emergency(paths, state.config.disk.min_free_bytes, isolated) => {
13396                        pressure = Some(reason); None
13397                    }
13398                };
13399                let (code, failure) = match status {
13400                    Some(Ok(Ok(status))) => (
13401                        status.code(),
13402                        status
13403                            .code()
13404                            .is_none()
13405                            .then(|| format!("command terminated: {status}")),
13406                    ),
13407                    Some(Ok(Err(error))) => {
13408                        (None, Some(format!("failed waiting for command: {error}")))
13409                    }
13410                    Some(Err(_)) => {
13411                        // Leased cleanup confirms process-tree death itself.
13412                        // Unleased commands still need the caller's PID check
13413                        // after kill-on-drop, before releasing cache ownership.
13414                        if !running.coordinated()
13415                            && let Some(pid) = pid
13416                        {
13417                            timed_out_pids.push(pid);
13418                        }
13419                        (
13420                            None,
13421                            Some(format!("timed out after {}s", timeout.as_secs())),
13422                        )
13423                    }
13424                    None => (None, None),
13425                };
13426                running.finish().await;
13427                if let Some(reason) = pressure {
13428                    state.resource_block = Some(crate::run::ResourceBlock {
13429                        cause: crate::run::ResourceBlockCause::Other,
13430                        node: node.to_owned(),
13431                        kind: "disk pressure".to_owned(),
13432                        detail: reason.clone(),
13433                        at: Timestamp::now(),
13434                    });
13435                    out.push(CommandOutcome {
13436                        command: command.clone(),
13437                        code: None,
13438                        output_tail: reason,
13439                        duration_ms: started.elapsed().as_millis() as u64,
13440                        resource_blocked: true,
13441                        ..Default::default()
13442                    });
13443                    break;
13444                }
13445                let out_text = agent::collect(&stdout, out_reader, Duration::from_secs(2)).await;
13446                let err_text = agent::collect(&stderr, err_reader, Duration::from_secs(2)).await;
13447                let mut body = out_text.clone();
13448                body.push_str(&err_text);
13449                if let Some(failure) = failure {
13450                    body.push('\n');
13451                    body.push_str(&failure);
13452                }
13453                (code, out_text, err_text, body)
13454            }
13455            Err(e) if isolated => {
13456                let e = anyhow::Error::new(e)
13457                    .context(format!("could not start managed build `{}`", shell[0]));
13458                record_cache_error(state, node, &e);
13459                out.push(CommandOutcome {
13460                    command: command.clone(),
13461                    code: None,
13462                    output_tail: format!("{e:#}"),
13463                    duration_ms: 0,
13464                    resource_blocked: true,
13465                    ..Default::default()
13466                });
13467                break;
13468            }
13469            Err(e) => (
13470                None,
13471                String::new(),
13472                String::new(),
13473                format!("failed to spawn `{}`: {e}", shell[0]),
13474            ),
13475        };
13476        let mut summary = summarize_verify(&body, crate::run::VERIFY_SUMMARY);
13477        let mut artifact = None;
13478        if !body.is_empty() {
13479            // The full text is kept whatever the summary dropped. A fresh
13480            // name per command so a resume or retry never overwrites an
13481            // earlier run's output. A failed write changes no verdict.
13482            match crate::run::write_verification_artifact(state, task, &body) {
13483                Ok(name) => {
13484                    let rel = format!("artifacts/{name}");
13485                    if summary != body {
13486                        summary = format!("[full output: {rel}]\n{summary}");
13487                    }
13488                    artifact = Some(rel);
13489                }
13490                Err(e) => {
13491                    let warning = format!("could not save the full {task} output: {e:#}");
13492                    tracing::warn!("{warning}");
13493                    state.event(node, warning);
13494                    if summary != body {
13495                        summary = format!("[full output could not be saved: {e:#}]\n{summary}");
13496                    }
13497                }
13498            }
13499        }
13500        let resource_blocked = code != Some(0) && body.contains(crate::incremental::BLOCKED);
13501        let mut outcome = CommandOutcome {
13502            command: command.clone(),
13503            code,
13504            output_tail: summary,
13505            duration_ms: started.elapsed().as_millis() as u64,
13506            resource_blocked,
13507            artifact,
13508            failure_evidence: None,
13509            rerun_comparison: None,
13510        };
13511        if !outcome.ok() && !outcome.resource_blocked {
13512            outcome.failure_evidence = Some(crate::verify_evidence::extract_streams(
13513                code,
13514                outcome.build_failed(),
13515                &out_text,
13516                &err_text,
13517            ));
13518        }
13519        out.push(outcome);
13520        if resource_blocked {
13521            state.resource_block = Some(crate::run::ResourceBlock {
13522                cause: crate::run::ResourceBlockCause::Other,
13523                node: node.to_owned(),
13524                kind: "incremental cache admission".into(),
13525                detail: body,
13526                at: Timestamp::now(),
13527            });
13528            break;
13529        }
13530    }
13531    state.task_finished(task);
13532    if let Err(e) = state.save() {
13533        tracing::warn!("could not persist the end of {task}: {e:#}");
13534    }
13535    (out, timed_out_pids)
13536}
13537
13538/// The shell command line `mode = "none"` prints — in `magi show`'s `merge`
13539/// section (`report::run`) and in the `merge` event this node records — for
13540/// the operator to run by hand.
13541///
13542/// Built from [`MergeStyle`] rather than always `git merge --no-ff`: a base
13543/// branch whose ruleset forbids merge commits (GitHub's "must not contain
13544/// merge commits", or "require linear history") rejects the push a `--no-ff`
13545/// merge would produce, which is exactly the guidance this function replaces.
13546/// `message`'s first line becomes the squash commit's subject, matching the
13547/// note `report::run` prints alongside this command — see that function for
13548/// why an explicit subject is not optional there.
13549fn manual_merge_command(style: MergeStyle, repo: &Path, branch: &str, message: &str) -> String {
13550    let repo = repo.display();
13551    match style {
13552        MergeStyle::Merge => format!("git -C {repo} merge --no-ff {branch}"),
13553        MergeStyle::Squash => {
13554            // The subject sits inside double quotes, and a title an agent
13555            // wrote may carry the characters that break out of them.
13556            let subject = message
13557                .lines()
13558                .next()
13559                .unwrap_or(branch)
13560                .replace(['\\', '"', '$', '`'], "");
13561            format!(
13562                "git -C {repo} merge --squash {branch} && git -C {repo} commit -m \"{subject}\""
13563            )
13564        }
13565        MergeStyle::Rebase => format!("git -C {repo} merge --ff-only {branch}"),
13566    }
13567}
13568
13569/// GitHub's `createPullRequest` GraphQL mutation, which `gh pr create` calls
13570/// under the hood, rejects a `title` over 256 characters and the whole
13571/// command fails — no PR at all, for a run whose body was otherwise fine
13572/// (this is what happened to run 2963; see AGENTS.md). 240 leaves room below
13573/// that limit: titles are counted in `chars()` (Unicode scalars), which is not
13574/// always how GitHub counts. [`english_title`] keeps its trailing `...` inside
13575/// this bound. It is a margin, not a guarantee — a title packed
13576/// with multi-unit characters could still in principle land close to the
13577/// edge, but a real task title's occasional emoji or accented letter fits
13578/// comfortably inside it.
13579const PR_TITLE_MAX: usize = 240;
13580
13581/// A pull request title from the opening line of `text`, or `None` when that
13582/// line is not English (GitHub text is) or has no letters.
13583///
13584/// A line within `max` is kept as is. A longer one is cut at the end of its
13585/// first sentence when that falls inside `max`, else at a word boundary with a
13586/// plain `...` (ASCII, unlike the `…` `queue::title_from` appends, which would
13587/// make every merely-truncated title look non-English). The language check
13588/// runs on the kept text before any mark is added, so only what GitHub will
13589/// show is judged: an English opening followed by non-ASCII far past the cut
13590/// still passes.
13591fn english_title(text: &str, max: usize, ascii_only: bool) -> Option<String> {
13592    let line = queue::first_line(text)?;
13593    let chars: Vec<char> = line.chars().collect();
13594    let (kept, mark) = if chars.len() <= max {
13595        (line.to_owned(), "")
13596    } else if let Some(end) = sentence_end(&chars, max) {
13597        (chars[..end].iter().collect::<String>(), "")
13598    } else {
13599        let room = max.saturating_sub(3);
13600        // Cut at the last space inside the room; when the char just past the
13601        // room is a space the room already ends on a word.
13602        let cut = if chars[room].is_whitespace() {
13603            room
13604        } else {
13605            chars[..room]
13606                .iter()
13607                .rposition(|c| c.is_whitespace())
13608                .unwrap_or(room)
13609        };
13610        let head: String = chars[..cut].iter().collect();
13611        let head = head.trim_end_matches(|c: char| c.is_whitespace() || ",;:-".contains(c));
13612        (head.to_owned(), "...")
13613    };
13614    if kept.is_empty() {
13615        return None;
13616    }
13617    if ascii_only && (!kept.is_ascii() || !kept.chars().any(|c| c.is_ascii_alphabetic())) {
13618        return None;
13619    }
13620    if !ascii_only && !kept.chars().any(char::is_alphabetic) {
13621        return None;
13622    }
13623    Some(format!("{kept}{mark}"))
13624}
13625
13626/// The char length of the first sentence of `chars` when it ends within `max`
13627/// (the closing `.`/`!`/`?` dropped), skipping very short stubs and common
13628/// abbreviations so `e.g. foo` does not end a title early.
13629fn sentence_end(chars: &[char], max: usize) -> Option<usize> {
13630    const MIN: usize = 20;
13631    for i in MIN..max.min(chars.len()) {
13632        if !matches!(chars[i], '.' | '!' | '?') {
13633            continue;
13634        }
13635        let Some(&next) = chars.get(i + 1) else {
13636            continue;
13637        };
13638        if !next.is_whitespace() {
13639            continue;
13640        }
13641        let after = chars[i + 1..].iter().find(|c| !c.is_whitespace());
13642        if after.is_some_and(|c| c.is_ascii_lowercase()) {
13643            continue;
13644        }
13645        let word: String = chars[..i]
13646            .iter()
13647            .rev()
13648            .take_while(|c| !c.is_whitespace())
13649            .collect::<Vec<_>>()
13650            .into_iter()
13651            .rev()
13652            .collect();
13653        let word = word.to_ascii_lowercase();
13654        if matches!(word.as_str(), "e.g" | "i.e" | "etc" | "vs" | "cf") {
13655            continue;
13656        }
13657        let end = chars[..i]
13658            .iter()
13659            .rposition(|c| !c.is_whitespace())
13660            .map_or(i, |p| p + 1);
13661        return Some(end);
13662    }
13663    None
13664}
13665
13666/// What `merge = "pr"` (and the merge commit of the other modes) says about a
13667/// change: a title and a body describing what was *implemented*, not the task
13668/// that asked for it. A task reads as a request; a reader of the merged
13669/// history wants the change.
13670struct PrMessage {
13671    title: String,
13672    body: String,
13673}
13674
13675impl PrMessage {
13676    /// Title, blank line, body. The first line is the squash/merge commit
13677    /// subject (`manual_merge_command` takes it via `lines().next()`), so it
13678    /// has to stay one sensible line.
13679    fn commit_message(&self) -> String {
13680        format!("{}\n\n{}", self.title, self.body)
13681    }
13682}
13683
13684/// The text after a leading `TITLE:` (any case) on `line`.
13685fn title_marker(line: &str) -> Option<&str> {
13686    let line = line.trim();
13687    let head = line.get(..6)?;
13688    head.eq_ignore_ascii_case("title:")
13689        .then(|| line[6..].trim())
13690}
13691
13692/// The implementer's own one-line title: the `TITLE:` line the implement
13693/// prompt asks for at the top of its SUMMARY. Candidate commits are all
13694/// `magi: candidate X (uncommitted work)`, so a commit subject is never a
13695/// source, and a title that says as much is refused here too.
13696fn summary_title(summary: &str) -> Option<String> {
13697    let first = summary.lines().find(|l| !l.trim().is_empty())?;
13698    let raw = title_marker(first)?;
13699    if raw.is_empty() {
13700        return None;
13701    }
13702    let title = queue::title_from(raw, PR_TITLE_MAX);
13703    let lower = title.to_ascii_lowercase();
13704    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
13705        return None;
13706    }
13707    Some(title)
13708}
13709
13710/// How `open_review`'s instruction begins; see [`landing_title`].
13711const REVIEW_PROMPT_OPENING: &str = "Review the work already on branch";
13712
13713/// Marker `open_review` gives a candidate that nothing in the roster wrote.
13714pub(crate) const EXISTING_BRANCH: &str = "(existing branch)";
13715
13716/// Does this run review work that already existed, rather than implement a
13717/// task? Runs recorded before `reviewed_commits` existed carry only the
13718/// candidate marker.
13719pub(crate) fn is_review_run(state: &RunState) -> bool {
13720    state.reviewed_commits.is_some() || state.candidates.iter().any(|c| c.agent == EXISTING_BRANCH)
13721}
13722
13723/// The title of a review-only run: the subject of the oldest commit under
13724/// review. Later commits are usually fixups, and `instruction` is the review
13725/// prompt, which says nothing about the change. GitHub text is English, so a
13726/// non-ASCII or blank subject yields `None` and the caller's neutral title.
13727fn review_title(state: &RunState) -> Option<String> {
13728    english_subject(
13729        state.reviewed_commits.as_ref()?.first()?,
13730        state.config.graph.github_english(),
13731    )
13732}
13733
13734/// `raw` as a pull request title, or `None` when it is blank, not English
13735/// (GitHub text is), or one of magi's own candidate commit subjects.
13736fn english_subject(raw: &str, ascii_only: bool) -> Option<String> {
13737    let raw = raw.trim();
13738    if raw.is_empty() {
13739        return None;
13740    }
13741    if ascii_only && (!raw.is_ascii() || !raw.chars().any(|c| c.is_ascii_alphabetic())) {
13742        return None;
13743    }
13744    if !ascii_only && !raw.chars().any(char::is_alphabetic) {
13745        return None;
13746    }
13747    let title = queue::title_from(raw, PR_TITLE_MAX);
13748    let lower = title.to_ascii_lowercase();
13749    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
13750        return None;
13751    }
13752    Some(title)
13753}
13754
13755/// What a review-only run's branch says about itself, read at the moment the
13756/// pull request is opened.
13757#[derive(Debug, Clone, PartialEq, Eq)]
13758struct BranchFacts {
13759    /// `(subject, body)` of each commit, oldest first.
13760    commits: Vec<(String, String)>,
13761    /// Trimmed `git diff --stat`.
13762    stat: String,
13763}
13764
13765/// Longest diff stat shown: this many file lines plus the summary line.
13766const STAT_FILE_LINES: usize = 25;
13767/// Cap on the commit list, well inside GitHub's 65536-character body limit.
13768const COMMITS_MAX_CHARS: usize = 20_000;
13769
13770/// Read the commits and diff stat of `base..branch`. `None` when git cannot
13771/// say or finds nothing, so the caller falls back to what the run recorded.
13772async fn branch_facts(repo: &Path, base: &str, branch: &str) -> Option<BranchFacts> {
13773    let commits = git::commit_log(repo, base, branch).await.ok()?;
13774    if commits.is_empty() {
13775        return None;
13776    }
13777    let stat = git::diff_stat(repo, base, branch).await.unwrap_or_default();
13778    let lines: Vec<&str> = stat.lines().collect();
13779    let stat = if lines.len() > STAT_FILE_LINES + 1 {
13780        let omitted = lines.len() - 1 - STAT_FILE_LINES;
13781        let more = format!(" ... {omitted} more file(s)");
13782        let mut kept: Vec<&str> = lines[..STAT_FILE_LINES].to_vec();
13783        kept.push(&more);
13784        kept.push(lines[lines.len() - 1]);
13785        kept.join("\n")
13786    } else {
13787        lines.join("\n")
13788    };
13789    Some(BranchFacts { commits, stat })
13790}
13791
13792/// Defang what would break the surrounding markdown: a closing `</details>`
13793/// and a code fence.
13794fn markdown_safe(text: &str) -> String {
13795    text.replace("</details>", "&lt;/details&gt;")
13796        .replace("\x60\x60\x60", "~~~")
13797}
13798
13799fn neutral_title(state: &RunState, winner: char) -> String {
13800    format!(
13801        "chore: land candidate {} of run {}",
13802        winner.to_ascii_uppercase(),
13803        state.id
13804    )
13805}
13806
13807/// Reuse the graph's bounded fixer without starting another graph or driver.
13808/// Copy the working state back even on errors so spent rounds remain visible.
13809pub(crate) async fn repair_landing_gate(
13810    state: &mut RunState,
13811    winner: &Candidate,
13812    outcomes: &[CommandOutcome],
13813) -> Result<GateFix> {
13814    if state.gate_fixes.len() >= state.config.graph.gate_fix_rounds || !gate_fixable(outcomes) {
13815        return Ok(GateFix::Stop);
13816    }
13817    let mut runner = Runner {
13818        roles: state.config.resolve_roles()?,
13819        sem: Arc::new(Semaphore::new(state.config.graph.max_parallel.max(1))),
13820        state: state.clone(),
13821        pause: Pause::new(),
13822        interrupt: Pause::new(),
13823    };
13824    let result = runner.gate_fix_round(winner, outcomes).await;
13825    *state = runner.state;
13826    result
13827}
13828
13829/// Review judgment survives a clean rebase; command evidence belongs to a SHA.
13830/// A completed failure is terminal on that SHA. Resource waits remain retryable.
13831pub(crate) async fn verify_current_head(
13832    state: &mut RunState,
13833    winner: &Candidate,
13834    wait: &crate::repo_lock::WaitPolicy,
13835) -> Result<bool> {
13836    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13837    // Preserve the previous record before replacing it, including on crash recovery.
13838    if state.head_e2e.as_ref().is_some_and(|e| e.head != head) {
13839        state
13840            .verification_history
13841            .push(crate::run::VerificationEvidence {
13842                superseded_by: Some(head.clone()),
13843                archived_at: Some(Timestamp::now()),
13844                fixes_spent: Some(state.gate_fixes.len()),
13845                gate_head: None,
13846                gate_ran: false,
13847                gate: Vec::new(),
13848                e2e: state.head_e2e.take(),
13849            });
13850    }
13851    if let Some(e) = &state.head_e2e
13852        && e.head == head
13853    {
13854        if e.passed {
13855            return Ok(true);
13856        }
13857        if !e.outcomes.is_empty() && !verify_inconclusive(&e.outcomes) {
13858            state.status = RunStatus::Blocked;
13859            state.save()?;
13860            return Ok(false);
13861        }
13862    } else if state.reviews.last().is_some_and(|r| {
13863        r.verified_head.as_deref() == Some(head.as_str())
13864            && (r.e2e_status() == E2eStatus::Passed
13865                || (r.e2e_status() == E2eStatus::NotConfigured
13866                    && state.config.verify.e2e.is_empty()))
13867    }) || state
13868        .gate_repair_e2e
13869        .as_ref()
13870        .is_some_and(|e| e.head == head && e.passed)
13871    {
13872        return Ok(true);
13873    }
13874    if let Some(e) = &state.gate_repair_e2e
13875        && e.head == head
13876        && !e.passed
13877        && !e.outcomes.is_empty()
13878        && !verify_inconclusive(&e.outcomes)
13879    {
13880        state.status = RunStatus::Blocked;
13881        state.save()?;
13882        return Ok(false);
13883    }
13884    // Bind the result to the base used by the candidate, not a tracking ref
13885    // that the background fetch can advance independently of verification.
13886    let base_commit = state
13887        .base_sync
13888        .as_ref()
13889        .map(|s| s.tip.clone())
13890        .filter(|tip| !tip.is_empty())
13891        .or_else(|| (!state.base_commit.is_empty()).then(|| state.base_commit.clone()));
13892    state.head_e2e = Some(crate::run::GateRepairE2e::new(
13893        head.clone(),
13894        false,
13895        Vec::new(),
13896    ));
13897    state.save()?;
13898    let commands = state.config.verify.e2e.clone();
13899    let shell = state.config.shell();
13900    let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13901    let cache_dir = state.config.cache_dir();
13902    let outcomes = if commands.is_empty() {
13903        Vec::new()
13904    } else {
13905        let (outcomes, _) = with_cache_lease(
13906            state,
13907            cache_dir.as_deref(),
13908            "e2e",
13909            "e2e",
13910            &winner.worktree,
13911            &head,
13912            timeout,
13913            "current head e2e",
13914            wait,
13915            |state, budget| async move {
13916                run_e2e_with_retry(
13917                    state,
13918                    &shell,
13919                    &commands,
13920                    &winner.worktree,
13921                    budget,
13922                    "current head e2e",
13923                    None,
13924                )
13925                .await
13926            },
13927        )
13928        .await?;
13929        outcomes
13930    };
13931    let unresolved = verify_inconclusive(&outcomes);
13932    let passed = !unresolved
13933        && outcomes.iter().all(CommandOutcome::ok)
13934        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
13935    if !outcomes.is_empty() && !unresolved {
13936        state.record_base_progress(&head);
13937    }
13938    let generation = Some(state.verification_history.len());
13939    let pass = state.passes.last().map(|p| p.index);
13940    let recorded_at = Some(Timestamp::now());
13941    let resumption_generation = state.entry_resumption_generation;
13942    let mut record = crate::run::GateRepairE2e::new(head.clone(), passed, outcomes);
13943    record.base_commit = base_commit;
13944    record.generation = generation;
13945    record.pass = pass;
13946    record.recorded_at = recorded_at;
13947    record.resumption_generation = resumption_generation;
13948    if !passed && !unresolved {
13949        let detail = state
13950            .head_e2e
13951            .as_ref()
13952            .and_then(|e| crate::verify_evidence::summarize_failed_outcomes(&e.outcomes))
13953            .map(|d| format!(" ({d})"))
13954            .unwrap_or_default();
13955        state.status = RunStatus::Blocked;
13956        state.event(
13957            "e2e",
13958            format!("verify.e2e failed on head {head}{detail}; nothing published"),
13959        );
13960        record.recorded_events = Some(state.events.len());
13961    }
13962    state.head_e2e = Some(record);
13963    state.save()?;
13964    Ok(passed)
13965}
13966
13967/// Recheck a repair's e2e requirement across failures, resource deferrals and
13968/// process interruptions. A successful result only applies to its exact SHA.
13969pub(crate) async fn check_gate_repair_e2e(
13970    state: &mut RunState,
13971    winner: &Candidate,
13972    wait: &crate::repo_lock::WaitPolicy,
13973) -> Result<GateFix> {
13974    if state.gate_repair_e2e.is_none() && state.gate_fixes.is_empty() {
13975        return Ok(GateFix::Retry);
13976    }
13977    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13978    if let Some(record) = &state.gate_repair_e2e
13979        && record.head == head
13980    {
13981        if record.passed {
13982            return Ok(GateFix::Retry);
13983        }
13984        if !record.outcomes.is_empty()
13985            && record.outcomes.iter().all(|o| {
13986                !o.resource_blocked && matches!(o.code, Some(code) if code != 126 && code != 127)
13987            })
13988        {
13989            return Ok(GateFix::Stop);
13990        }
13991    }
13992    state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
13993        head.clone(),
13994        false,
13995        Vec::new(),
13996    ));
13997    state.save()?;
13998    let commands = state.config.verify.e2e.clone();
13999    let outcomes = if commands.is_empty() {
14000        Vec::new()
14001    } else {
14002        let shell = state.config.shell();
14003        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
14004        let cache_dir = state.config.cache_dir();
14005        let (outcomes, _) = with_cache_lease(
14006            state,
14007            cache_dir.as_deref(),
14008            "e2e",
14009            "e2e",
14010            &winner.worktree,
14011            &head,
14012            timeout,
14013            "gate repair e2e",
14014            wait,
14015            |state, budget| async move {
14016                run_e2e_with_retry(
14017                    state,
14018                    &shell,
14019                    &commands,
14020                    &winner.worktree,
14021                    budget,
14022                    "gate repair e2e",
14023                    None,
14024                )
14025                .await
14026            },
14027        )
14028        .await?;
14029        outcomes
14030    };
14031    let deferred = verify_inconclusive(&outcomes);
14032    let passed = outcomes.iter().all(CommandOutcome::ok)
14033        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
14034    state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(head, passed, outcomes));
14035    state.save()?;
14036    if deferred {
14037        Ok(GateFix::Defer)
14038    } else if !passed {
14039        let detail = state
14040            .gate_repair_e2e
14041            .as_ref()
14042            .and_then(|e| crate::verify_evidence::summarize_failed_outcomes(&e.outcomes))
14043            .map(|d| format!(" ({d})"))
14044            .unwrap_or_default();
14045        state.event(
14046            "gate",
14047            format!("verify.e2e failed after gate repair{detail}; nothing published"),
14048        );
14049        Ok(GateFix::Stop)
14050    } else {
14051        Ok(GateFix::Retry)
14052    }
14053}
14054
14055/// Run the same configured gate for a landing head and a fresh graph.
14056pub(crate) async fn run_landing_gate(
14057    state: &mut RunState,
14058    winner: &Candidate,
14059    wait: &crate::repo_lock::WaitPolicy,
14060) -> Result<Vec<CommandOutcome>> {
14061    let shell = state.config.shell();
14062    let gate_commands = state.config.verify.gate.clone();
14063    let has_pre_gate = !state.config.verify.pre_gate.is_empty();
14064    let outcomes = if gate_commands.is_empty() && !has_pre_gate {
14065        state.gate_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
14066        Vec::new()
14067    } else {
14068        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
14069        let cache_dir = state.config.cache_dir();
14070        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
14071        let (outcomes, _) = with_cache_lease(
14072            state,
14073            cache_dir.as_deref(),
14074            "gate",
14075            "gate",
14076            &winner.worktree,
14077            &head,
14078            timeout,
14079            "final gate",
14080            wait,
14081            |state, budget| {
14082                let shell = shell.clone();
14083                let gate_commands = gate_commands.clone();
14084                let winner = winner.clone();
14085                async move {
14086                    Runner::run_pre_gate(state, &winner).await;
14087                    // Bind command evidence after mechanical fixes, before commands start.
14088                    state.gate_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
14089                    let (outcomes, timed_out_pids) = run_commands(
14090                        state,
14091                        "gate",
14092                        "gate",
14093                        0,
14094                        &shell,
14095                        &gate_commands,
14096                        &winner.worktree,
14097                        budget,
14098                    )
14099                    .await;
14100                    (outcomes, false, timed_out_pids)
14101                }
14102            },
14103        )
14104        .await?;
14105        outcomes
14106    };
14107    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
14108    if !verify_inconclusive(&outcomes) && state.gate_head.as_deref() != Some(current.as_str()) {
14109        let mut outcomes = outcomes;
14110        outcomes.push(CommandOutcome {
14111            command: "gate head stability".into(), code: None,
14112            output_tail: "winner changed during gate, or checked head is unknown; fresh verification required".into(),
14113            duration_ms: 0, resource_blocked: false,
14114            ..Default::default()
14115        });
14116        return Ok(outcomes);
14117    }
14118    if outcomes.is_empty() {
14119        // Nothing configured to check — distinct from every other
14120        // silence in this run's event log, since an empty `gate` alone
14121        // no longer says whether the gate ran at all (see
14122        // `RunState::gate_ran`'s own doc).
14123        state.event("gate", "no gate commands configured; not tested");
14124    }
14125    for o in &outcomes {
14126        state.event(
14127            "gate",
14128            format!(
14129                "`{}` -> {}",
14130                o.command,
14131                if o.ok() {
14132                    "pass".to_owned()
14133                } else {
14134                    format!(
14135                        "FAIL ({:?})\n{}",
14136                        o.code,
14137                        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
14138                    )
14139                }
14140            ),
14141        );
14142    }
14143    Ok(outcomes)
14144}
14145
14146/// The pull request title to hand to `land::merge_subject`. A review-only run
14147/// opened by an earlier build titled its pull request with the review prompt;
14148/// that title is dropped (empty, so the fallback applies) rather than landed.
14149/// Any other title, including an operator's rename, passes through untouched,
14150/// and so does every title of a run that implements a task.
14151pub fn landing_title<'a>(state: &RunState, pr_title: &'a str) -> &'a str {
14152    if is_review_run(state) && pr_title.trim_start().starts_with(REVIEW_PROMPT_OPENING) {
14153        ""
14154    } else {
14155        pr_title
14156    }
14157}
14158
14159/// What the squash subject falls back to when the pull request title is empty
14160/// or candidate-shaped: for a review-only run the derived title, never the
14161/// review prompt held in `instruction`.
14162pub fn landing_subject_source(state: &RunState) -> String {
14163    if is_review_run(state) {
14164        let winner = state.candidates.first().map_or('A', |c| c.label);
14165        return review_title(state).unwrap_or_else(|| neutral_title(state, winner));
14166    }
14167    state.instruction.clone()
14168}
14169
14170/// `summary` without its `TITLE:` line, which the pull request title already
14171/// carries.
14172fn summary_without_title(summary: &str) -> String {
14173    let mut lines = summary.trim().lines().peekable();
14174    if lines.peek().is_some_and(|l| title_marker(l).is_some()) {
14175        lines.next();
14176    }
14177    lines.collect::<Vec<_>>().join("\n").trim().to_owned()
14178}
14179
14180/// The pull request title and body for the winning candidate.
14181///
14182/// Title: the implementer's `TITLE:` line ([`summary_title`]), falling back to
14183/// the task's own opening line via [`queue::title_from`] when there is none.
14184/// `state.instruction` can open with blank lines (`task_text` only rejects a
14185/// body that is blank *entirely*), which `title_from` skips.
14186///
14187/// Publishing uses an independent description generated from the final diff
14188/// and structured evidence. Internal summaries and reports remain local.
14189/// Non-publishing previews may display the original task and candidate summary.
14190/// The footer retains the run and candidate provenance.
14191#[cfg(test)]
14192fn pr_message(state: &RunState, winner: char) -> PrMessage {
14193    pr_message_with(state, winner, None)
14194}
14195
14196/// [`pr_message`] with what the branch of a review-only run says about itself.
14197/// `facts` is ignored for a run that implements a task.
14198#[cfg(test)]
14199fn pr_message_with(state: &RunState, winner: char, facts: Option<&BranchFacts>) -> PrMessage {
14200    let raw = pr_message_raw(
14201        state,
14202        winner,
14203        facts,
14204        crate::pr_outcome::FinalHead::Unreported,
14205        ChangeNote::NotAsked,
14206    );
14207    let id = crate::scrub::Identity::current();
14208    PrMessage {
14209        title: crate::scrub::scrub(&raw.title, &id),
14210        body: crate::scrub::scrub(&raw.body, &id),
14211    }
14212}
14213
14214/// What the public description may say about the change itself.
14215#[derive(Debug, Clone, Copy)]
14216enum ChangeNote<'a> {
14217    /// A local preview or non-publishing merge mode: no public generation needed.
14218    NotAsked,
14219    /// A summary written from the final diff.
14220    Summary(&'a crate::run::ChangeSummary),
14221    /// A summary was asked for and could not be produced; the text says why.
14222    Unavailable(&'a str),
14223}
14224
14225fn pr_message_raw(
14226    state: &RunState,
14227    winner: char,
14228    facts: Option<&BranchFacts>,
14229    head: crate::pr_outcome::FinalHead<'_>,
14230    change: ChangeNote<'_>,
14231) -> PrMessage {
14232    if !matches!(change, ChangeNote::NotAsked) {
14233        let (title, mut body) = match change {
14234            ChangeNote::Summary(c) => (
14235                c.title.clone(),
14236                format!("## Summary\n\n{}\n\n", c.body.trim()),
14237            ),
14238            ChangeNote::Unavailable(why) => (
14239                neutral_title(state, winner),
14240                format!(
14241                    "## Summary\n\nNo description of what this change does could be generated ({why}). Review the final diff; internal reports remain in local records.\n\n"
14242                ),
14243            ),
14244            ChangeNote::NotAsked => unreachable!(),
14245        };
14246        body.push_str(&public_pr_evidence(state, head));
14247        body.push_str(&format!(
14248            "\n---\nmagi:run/{} magi:candidate-{}\n",
14249            state.id,
14250            winner.to_ascii_lowercase()
14251        ));
14252        return PrMessage { title, body };
14253    }
14254    pr_preview(state, winner, facts, head)
14255}
14256
14257/// Append public facts from the run records after every prose generation,
14258/// including posting-gate rewrites. The agent cannot drop this provenance.
14259fn public_pr_evidence(state: &RunState, head: crate::pr_outcome::FinalHead<'_>) -> String {
14260    let mut body = crate::pr_outcome::review_rounds(state);
14261    body.push_str(&crate::pr_outcome::final_verification(state, head));
14262    let open = state.last_round_findings();
14263    if !open.is_empty() {
14264        body.push_str("## Open review findings\n\n");
14265        for f in open {
14266            body.push_str(&format!("- `{}` [{:?}]\n", f.id, f.severity));
14267        }
14268        body.push('\n');
14269    }
14270    if let Some(c) = state.change_summary.as_ref()
14271        && head == crate::pr_outcome::FinalHead::At(&c.head)
14272    {
14273        body.push_str(&format!(
14274            "Evidence: final diff `{}`..`{}`; review and verification records from this run.\n",
14275            c.base, c.head
14276        ));
14277    }
14278    body
14279}
14280
14281/// Local-only preview of the operator's task and candidate summary.
14282fn pr_preview(
14283    state: &RunState,
14284    winner: char,
14285    facts: Option<&BranchFacts>,
14286    head: crate::pr_outcome::FinalHead<'_>,
14287) -> PrMessage {
14288    let summary = state
14289        .candidates
14290        .iter()
14291        .find(|c| c.label == winner)
14292        .map(|c| c.summary.as_str())
14293        .unwrap_or_default();
14294    // The fallback is the operator's own words and may not be English; GitHub
14295    // text always is, so a non-English task gets a neutral title instead.
14296    let review = is_review_run(state);
14297    let title = if review {
14298        facts
14299            .and_then(|f| {
14300                english_subject(&f.commits.first()?.0, state.config.graph.github_english())
14301            })
14302            .or_else(|| review_title(state))
14303            .or_else(|| {
14304                state
14305                    .candidates
14306                    .iter()
14307                    .find(|c| c.label == winner)
14308                    .filter(|c| !c.branch.starts_with("magi/"))
14309                    .and_then(|c| english_subject(&c.branch, state.config.graph.github_english()))
14310            })
14311            .unwrap_or_else(|| neutral_title(state, winner))
14312    } else {
14313        summary_title(summary).unwrap_or_else(|| {
14314            english_title(
14315                &state.instruction,
14316                PR_TITLE_MAX,
14317                state.config.graph.github_english(),
14318            )
14319            .unwrap_or_else(|| neutral_title(state, winner))
14320        })
14321    };
14322
14323    let mut body = String::new();
14324    let what = summary_without_title(summary);
14325    if !what.is_empty() {
14326        body.push_str("## Summary\n\n");
14327        body.push_str(&what);
14328        body.push_str("\n\n");
14329    }
14330
14331    // Review history uses structured facts across all rounds, never reports.
14332    body.push_str(&crate::pr_outcome::review_rounds(state));
14333    body.push_str(&crate::pr_outcome::final_verification(state, head));
14334    let fix = state.reviews.iter().rev().find_map(|r| r.fix.as_ref());
14335
14336    let open = state.open_findings();
14337    if !open.is_empty() {
14338        body.push_str("## Open review findings\n\n");
14339        for f in &open {
14340            body.push_str(&format!(
14341                "- `{}` [{:?}] {}\n",
14342                f.id, f.severity, "Context retained in local review records."
14343            ));
14344        }
14345        body.push('\n');
14346    }
14347
14348    if let Some(fix) = fix
14349        && !fix.rejected.is_empty()
14350    {
14351        body.push_str("## Declined by the fixer\n\n");
14352        for r in &fix.rejected {
14353            body.push_str(&format!(
14354                "- `{}`: {}\n",
14355                r.id, "Reason retained in local review records."
14356            ));
14357        }
14358        body.push('\n');
14359    }
14360
14361    if review {
14362        // The review prompt is not the task; list what the branch carries.
14363        body.push_str("## Commits under review\n\n");
14364        if let Some(facts) = facts {
14365            let mut left = COMMITS_MAX_CHARS;
14366            for (i, (subject, text)) in facts.commits.iter().enumerate() {
14367                let mut entry = format!("- {}\n", markdown_safe(subject));
14368                for l in markdown_safe(text).lines() {
14369                    entry.push_str(format!("  {l}\n").trim_end_matches(' '));
14370                }
14371                if left == 0 {
14372                    body.push_str(&format!(
14373                        "- ... {} more commit(s)\n",
14374                        facts.commits.len() - i
14375                    ));
14376                    break;
14377                }
14378                if entry.len() > left {
14379                    // Even the first commit is cut: one huge body must not
14380                    // push the whole description past GitHub's limit.
14381                    let mut end = left;
14382                    while !entry.is_char_boundary(end) {
14383                        end -= 1;
14384                    }
14385                    entry.truncate(end);
14386                    entry.push_str("\n  ... (truncated)\n");
14387                    left = 0;
14388                } else {
14389                    left -= entry.len();
14390                }
14391                body.push_str(&entry);
14392            }
14393            if !facts.stat.trim().is_empty() {
14394                body.push_str(&format!(
14395                    "\n## Diff stat\n\n```\n{}\n```\n",
14396                    markdown_safe(facts.stat.trim())
14397                ));
14398            }
14399        } else {
14400            match &state.reviewed_commits {
14401                Some(subjects) => {
14402                    for s in subjects {
14403                        body.push_str(&format!("- {}\n", s.trim()));
14404                    }
14405                }
14406                None => {
14407                    // An older run kept only the prompt, with the commit list
14408                    // after its first paragraph.
14409                    let rest = state.instruction.split_once("\n\n").map_or("", |(_, r)| r);
14410                    body.push_str(rest.trim());
14411                    body.push('\n');
14412                }
14413            }
14414        }
14415    } else {
14416        let task = state.instruction.trim();
14417        let task = if task.is_empty() {
14418            "(empty task)"
14419        } else {
14420            task
14421        };
14422        body.push_str(&format!(
14423            "<details>\n<summary>Original task</summary>\n\n{}\n\n</details>\n",
14424            task.replace("</details>", "&lt;/details&gt;")
14425        ));
14426    }
14427
14428    body.push_str(&format!(
14429        "\n---\nmagi:run/{} magi:candidate-{}\n",
14430        state.id,
14431        winner.to_ascii_lowercase()
14432    ));
14433
14434    PrMessage { title, body }
14435}
14436
14437/// Source imports have already been prepared from structured inputs. Legacy
14438/// inferred references must never instruct a seat to reconstruct those imports.
14439fn seeded_instruction(state: &RunState) -> String {
14440    let mut inputs = Vec::new();
14441    if let Some(start) = &state.sources.start_from {
14442        inputs.push(format!(
14443            "Start from `{}` at `{}` (including ancestry).",
14444            start.token, start.sha
14445        ));
14446    }
14447    for pick in &state.sources.pick_commits {
14448        inputs.push(format!(
14449            "Pick `{}` at `{}` (single commit).",
14450            pick.token, pick.sha
14451        ));
14452    }
14453    if inputs.is_empty() {
14454        state.instruction.clone()
14455    } else {
14456        format!(
14457            "{}\n\n# Explicit source inputs already prepared\n\n{}",
14458            state.instruction,
14459            inputs.join("\n")
14460        )
14461    }
14462}
14463
14464/// Does the winner have no commits ahead of the base it would land on?
14465/// Any failure to find out reads as "not empty": the merge then behaves as it
14466/// always did rather than refusing on a guess.
14467async fn merge_is_empty(repo: &Path, state: &RunState, branch: &str, mode: MergeMode) -> bool {
14468    let base = &state.base_branch;
14469    let mut against = base.clone();
14470    if mode == MergeMode::Pr {
14471        // A pull request lands on the remote's base, never the local branch
14472        // of the same name: if that cannot be read, "not empty" is the safe
14473        // answer.
14474        let remote = &state.config.merge.remote;
14475        let tracking = format!("{remote}/{base}");
14476        let fetched = git::fetch(repo, remote, base).await;
14477        if fetched.is_ok_and(|o| o.ok()) && git::rev_exists(repo, &tracking).await {
14478            against = tracking;
14479        } else {
14480            return false;
14481        }
14482    }
14483    matches!(git::commits_ahead(repo, &against, branch).await, Ok(0))
14484}
14485
14486/// Why nothing was opened for an empty winner, with what the task's own
14487/// references resolved to.
14488fn empty_candidate_detail(_state: &RunState, base: &str) -> String {
14489    let mut detail = format!(
14490        "empty candidate: the winning branch has 0 commits ahead of {base}, so there is \
14491         nothing to open a pull request for"
14492    );
14493    detail.push_str(
14494        "\nSource imports require explicit --start-from or --pick-commit options on a new task.",
14495    );
14496    detail
14497}
14498
14499/// What the `Pr` merge does once it knows whether the branch already has an
14500/// open pull request.
14501#[derive(Debug, PartialEq, Eq)]
14502enum PrPlan {
14503    Create,
14504    Adopt { url: String, title: String },
14505    Stop(String),
14506}
14507
14508/// Pure decision behind the `Pr` merge: none -> create, one -> adopt, many or
14509/// a failed lookup -> stop with the real reason. Never guesses.
14510fn pr_merge_plan(found: Result<land::OpenPr>) -> PrPlan {
14511    match found {
14512        Ok(land::OpenPr::None) => PrPlan::Create,
14513        Ok(land::OpenPr::One { url, title }) => PrPlan::Adopt { url, title },
14514        Ok(land::OpenPr::Many(urls)) => PrPlan::Stop(format!(
14515            "several open pull requests exist for this branch, not picking one: {}",
14516            urls.join(" ")
14517        )),
14518        Err(e) => PrPlan::Stop(format!("could not look up open pull requests: {e:#}")),
14519    }
14520}
14521
14522/// `gh pr create`, returning the PR url.
14523pub(crate) async fn gh_pr_create(
14524    cwd: &Path,
14525    base: &str,
14526    head: &str,
14527    title: &str,
14528    body: &str,
14529) -> Result<String> {
14530    let out = tokio::process::Command::new("gh")
14531        .args([
14532            "pr", "create", "--base", base, "--head", head, "--title", title, "--body", body,
14533        ])
14534        .current_dir(cwd)
14535        .quiet()
14536        .stdin(std::process::Stdio::null())
14537        .output()
14538        .await
14539        .context("spawn gh")?;
14540    if out.status.success() {
14541        Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
14542    } else {
14543        bail!("{}", String::from_utf8_lossy(&out.stderr).trim().to_owned())
14544    }
14545}
14546
14547/// Never force deletion of uncommitted work, including unknown legacy trees.
14548async fn remove_preserved_worktree(repo: &Path, path: &Path) -> Result<()> {
14549    match std::fs::symlink_metadata(path) {
14550        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
14551            // A previous cleanup may have removed the tree before a branch
14552            // deletion or state save failed. Unregister it if still present.
14553            git::worktree_remove_clean(repo, path).await?;
14554            return Ok(());
14555        }
14556        Err(e) => return Err(e.into()),
14557        Ok(_) => {}
14558    }
14559    if !git::is_clean(path).await? {
14560        bail!(
14561            "worktree has uncommitted work; refusing removal: {}",
14562            path.display()
14563        );
14564    }
14565    if !git::worktree_remove_clean(repo, path).await? {
14566        bail!("worktree removal refused: {}", path.display());
14567    }
14568    Ok(())
14569}
14570
14571/// Read seats return replies, not working-tree changes. Only registered,
14572/// detached seats directly inside this run's root may discard those changes.
14573async fn remove_read_seat_worktree(state: &mut RunState, path: &Path) -> Result<()> {
14574    if !crate::retention::read_seat(path) || !path.exists() {
14575        return remove_preserved_worktree(&state.repo, path).await;
14576    }
14577    let owned = std::fs::symlink_metadata(path)?.is_dir()
14578        && path.parent().map(Path::canonicalize).transpose()?
14579            == Some(state.worktree_root().canonicalize()?)
14580        && crate::retention::worktrees(state)
14581            .await?
14582            .contains(&path.canonicalize()?);
14583    let common = crate::repo_lock::common_dir(&state.repo).await?;
14584    if !owned
14585        || common.is_none()
14586        || crate::repo_lock::common_dir(path).await? != common
14587        || git::git_raw(path, &["symbolic-ref", "-q", "HEAD"])
14588            .await?
14589            .ok()
14590        || state.candidates.iter().any(|c| c.worktree == path)
14591    {
14592        return remove_preserved_worktree(&state.repo, path).await;
14593    }
14594    let changes = git::status_porcelain(path).await?;
14595    if !git::worktree_remove(&state.repo, path).await? {
14596        bail!(
14597            "read-only seat worktree removal refused: {}",
14598            path.display()
14599        );
14600    }
14601    if !changes.is_empty() {
14602        let paths = changes.lines().take(20).collect::<Vec<_>>().join("; ");
14603        let paths: String = paths.chars().take(1024).collect();
14604        state.event(
14605            "fold",
14606            format!(
14607                "discarded read-only seat {} changes ({} status entries; first 20, at most 1024 chars): {paths}",
14608                path.file_name().unwrap_or_default().to_string_lossy(),
14609                changes.lines().count()
14610            ),
14611        );
14612    }
14613    Ok(())
14614}
14615
14616fn fold_target(
14617    home: &Path,
14618    root: &Path,
14619    path: &Path,
14620    isolated: bool,
14621) -> Option<crate::build_target::FoldTarget> {
14622    if !isolated {
14623        return None;
14624    }
14625    match crate::build_target::FoldTarget::for_checkout(home, path, root) {
14626        Ok(target) => target,
14627        Err(error) => {
14628            tracing::warn!(checkout = %path.display(), %error, "isolated target binding not proved at fold");
14629            None
14630        }
14631    }
14632}
14633
14634fn reclaim_fold_target(home: &Path, target: Option<crate::build_target::FoldTarget>) {
14635    if let Some(target) = target
14636        && let Err(error) = target.reclaim_orphaned_target(home)
14637    {
14638        tracing::warn!(%error, "isolated target retained after fold");
14639    }
14640}
14641
14642/// Why a fold left a run alone. A typed refusal lets the automatic callers
14643/// (`clean::fold_one`, and through it the idle janitor and the busy-time fold
14644/// turn) say *why* in their receipts; it never changes what is deleted.
14645#[derive(Debug, Clone, PartialEq, Eq)]
14646pub enum FoldRefusal {
14647    /// A lease or lock a live owner holds - the run's execution lease or
14648    /// ownership lock, a source's output lease, a Cargo build, the repository's
14649    /// coordination lease - or a live daemon claim on the run.
14650    Live(String),
14651    /// A resumable status: someone may still continue this run.
14652    Resumable,
14653    /// Finished less than the fold grace period ago.
14654    WithinGrace,
14655    /// An explicitly retained recovery source (`pr_recovery`).
14656    Retained(String),
14657    /// The proof that nothing is lost is not complete: startup or candidate
14658    /// preservation unfinished, or the confirmed-merge source proof (Cargo
14659    /// residue, Git checkpoints, the fetched base) could not be established.
14660    ProofIncomplete(String),
14661    /// The run's record is gone, or is not the record that was locked: it was
14662    /// deleted while the fold waited for its locks. Nothing is touched and
14663    /// nothing is recreated.
14664    RecordGone,
14665    /// The record was readable when the caller first looked and cannot be read
14666    /// once the run's locks are held.
14667    Unreadable(String),
14668}
14669
14670impl std::fmt::Display for FoldRefusal {
14671    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
14672        match self {
14673            Self::Live(detail) | Self::ProofIncomplete(detail) => f.write_str(detail),
14674            Self::Resumable => f.write_str("refusing fold: the run is resumable"),
14675            Self::WithinGrace => f.write_str("refusing fold: the run finished within its grace"),
14676            Self::Retained(reason) => write!(f, "refusing fold: {reason}"),
14677            Self::RecordGone => f.write_str("refusing fold: record gone"),
14678            Self::Unreadable(detail) => {
14679                write!(
14680                    f,
14681                    "refusing fold: the run record became unreadable: {detail}"
14682                )
14683            }
14684        }
14685    }
14686}
14687
14688impl std::error::Error for FoldRefusal {}
14689
14690/// Is `error` somebody else holding a lock or lease right now? Only
14691/// contention is: any other failure of a lock call is a real failure.
14692pub(crate) fn held_by_live_owner(error: &anyhow::Error) -> bool {
14693    error.chain().any(|cause| {
14694        cause.is::<crate::retention::OutputsInUse>()
14695            || cause.is::<crate::repo_lock::ResourceBlocked>()
14696            || cause.downcast_ref::<std::io::Error>().is_some_and(|io| {
14697                io.kind() == std::io::ErrorKind::WouldBlock
14698                    || cfg!(windows) && io.raw_os_error() == Some(33)
14699            })
14700    })
14701}
14702
14703/// `error`, marked as [`FoldRefusal::Live`] when it is a held lock.
14704///
14705/// The refusal is *added to* the error as context, never substituted for it:
14706/// callers match the error underneath (`repo_lock::ResourceBlocked` for a
14707/// coordination wait, which several of them treat as a resource stop), and the
14708/// receipt's classification reads the refusal. Both downcasts succeed.
14709fn live_or(error: anyhow::Error) -> anyhow::Error {
14710    if held_by_live_owner(&error) {
14711        error.context(FoldRefusal::Live(
14712            "a lock or lease is held by another owner".into(),
14713        ))
14714    } else {
14715        error
14716    }
14717}
14718
14719/// A failure to take a run's owner lock or execution lease. A run directory
14720/// that is not there (deleted, or never was) is `record gone` and is *not*
14721/// created for the lock's sake; contention is `live`; anything else stays a
14722/// failure with its own text.
14723fn lock_refusal(error: anyhow::Error) -> anyhow::Error {
14724    if is_missing(&error) {
14725        FoldRefusal::RecordGone.into()
14726    } else {
14727        live_or(error)
14728    }
14729}
14730
14731fn is_missing(error: &anyhow::Error) -> bool {
14732    error.chain().any(|cause| {
14733        cause
14734            .downcast_ref::<std::io::Error>()
14735            .is_some_and(|io| io.kind() == std::io::ErrorKind::NotFound)
14736    })
14737}
14738
14739fn preservation_refusal() -> anyhow::Error {
14740    FoldRefusal::ProofIncomplete("candidate preservation incomplete; refusing cleanup".into())
14741        .into()
14742}
14743
14744/// The record's own preconditions for the explicit recovery-retention override.
14745fn ensure_overridable(state: &RunState) -> Result<()> {
14746    anyhow::ensure!(
14747        state.status.done() && !state.status.resumable(),
14748        "recovery retention override requires a finished, non-resumable run"
14749    );
14750    Ok(())
14751}
14752
14753/// How a failure of the confirmed-merge source verification reaches the fold's
14754/// caller: somebody else holding a lock is `live`; a lock call that failed for
14755/// another reason is a failure of its own (`failed` in the receipt), not
14756/// evidence that the sources are unproven; anything else - missing or changed
14757/// evidence - is an incomplete proof.
14758fn source_proof_failure(error: anyhow::Error) -> anyhow::Error {
14759    if held_by_live_owner(&error) {
14760        live_or(error)
14761    } else if error
14762        .chain()
14763        .any(|cause| cause.is::<crate::retention::LockCallFailed>())
14764    {
14765        error
14766    } else {
14767        FoldRefusal::ProofIncomplete(format!("{error:#}")).into()
14768    }
14769}
14770
14771/// Which loader a fold uses on the record it reads again under its locks.
14772#[derive(Clone, Copy, PartialEq, Eq)]
14773enum Reload {
14774    /// Housekeeping: the record as saved, whatever schema wrote it
14775    /// ([`RunState::load_tolerant_under`]), exactly as `clean::fold_due` has
14776    /// always read it.
14777    Tolerant,
14778    /// An explicit fold (`magi fold`, the phone's route): the migrating loader
14779    /// the caller itself used ([`RunState::load_under`]), whose derived fields
14780    /// the preservation checks and the saved record then rest on.
14781    Strict,
14782}
14783
14784/// Why a record read under the locks is no longer the one that was locked.
14785fn reload_refusal(error: &anyhow::Error) -> FoldRefusal {
14786    if is_missing(error) {
14787        FoldRefusal::RecordGone
14788    } else {
14789        FoldRefusal::Unreadable(format!("{error:#}"))
14790    }
14791}
14792
14793/// What a test does after a fold's first look at the record and before it
14794/// takes the run's locks: where a deletion or a handover falls.
14795#[cfg(test)]
14796type BeforeLocks = Box<dyn FnOnce(&Path, &str)>;
14797
14798#[cfg(test)]
14799thread_local! {
14800    static BEFORE_LOCKS: std::cell::RefCell<Option<BeforeLocks>> =
14801        const { std::cell::RefCell::new(None) };
14802}
14803
14804/// Tear a run's worktrees and branches down.
14805///
14806/// `home` is where the updated `run.json` is saved (via
14807/// [`RunState::save_under`]), never the process-global [`crate::run::home`]:
14808/// a housekeeping pass already has its own honest `home` handed to it, and
14809/// falling through to the global here would write back through whichever
14810/// directory some other process or test pinned into that `OnceLock` first,
14811/// not the one the caller actually resolved its `runs` and `state` from.
14812///
14813/// Every deletion decision is made on the record as it is on disk once the
14814/// owner lock and execution lease are held, not on the `state` the caller read
14815/// earlier: see [`fold_run_when`].
14816pub async fn fold_run(state: &mut RunState, drop_winner: bool, home: &Path) -> Result<Vec<String>> {
14817    fold_run_with_policy(state, home, &|_| Ok(drop_winner), Reload::Strict, false).await
14818}
14819
14820/// [`fold_run`] for the automatic callers, which decide whether the run may be
14821/// folded at all, and whether its winner goes too, from the run record.
14822///
14823/// `decide` is called on the caller's earlier read by the caller itself, and
14824/// again here on the record reloaded after taking the run's owner lock and
14825/// execution lease. A handover (`handover::release`) records `released_to` /
14826/// `released_branches` under that owner lock and removes the old worktree while
14827/// keeping the branch; a fold that acted on a record read before the handover
14828/// would delete the branch already given to the successor and save the stale
14829/// record over the handover. A run no longer eligible under the fresh record
14830/// is left alone and the refusal says why. The reload is tolerant of older
14831/// schemas, as `clean::fold_due` always was; the explicit entry points
14832/// ([`fold_run`], [`fold_run_overriding_recovery_retention`]) use the
14833/// migrating loader.
14834pub async fn fold_run_when(
14835    state: &mut RunState,
14836    home: &Path,
14837    decide: &(dyn Fn(&RunState) -> Result<bool, FoldRefusal> + Sync),
14838) -> Result<Vec<String>> {
14839    fold_run_with_policy(state, home, decide, Reload::Tolerant, false).await
14840}
14841
14842/// Explicit CLI-only retention override; automatic callers use [`fold_run`].
14843pub async fn fold_run_overriding_recovery_retention(
14844    state: &mut RunState,
14845    drop_winner: bool,
14846    home: &Path,
14847) -> Result<Vec<String>> {
14848    fold_run_with_policy(state, home, &|_| Ok(drop_winner), Reload::Strict, true).await
14849}
14850
14851async fn fold_run_with_policy(
14852    state: &mut RunState,
14853    home: &Path,
14854    decide: &(dyn Fn(&RunState) -> Result<bool, FoldRefusal> + Sync),
14855    reload: Reload,
14856    override_recovery_retention: bool,
14857) -> Result<Vec<String>> {
14858    // Cheap refusals on the caller's snapshot, before any lock is taken.
14859    if let Some(reason) = crate::pr_recovery::source_retention_reason(home, state)
14860        && !override_recovery_retention
14861    {
14862        return Err(FoldRefusal::Retained(reason).into());
14863    }
14864    if !state.candidate_preservation.is_empty() || !state.interrupted_implementations.is_empty() {
14865        return Err(preservation_refusal());
14866    }
14867    // A fold needs the saved record of the run it locks. Nothing below may
14868    // bring a deleted run's directory back, and a fold is never entitled to
14869    // write a record of its own making: the caller's `state` is only a first
14870    // look, and every decision is made on what is read under the locks.
14871    let id = state.id.clone();
14872    let record = home.join("runs").join(&id).join("run.json");
14873    if !record.try_exists()? {
14874        return Err(FoldRefusal::RecordGone.into());
14875    }
14876    #[cfg(test)]
14877    if let Some(hook) = BEFORE_LOCKS.with(|hook| hook.borrow_mut().take()) {
14878        hook(home, &id);
14879    }
14880    // Serialize ordinary folding with the same starts/resumes as target-only
14881    // eviction. Otherwise a second janitor could remove the whole worktree
14882    // around a live output borrower even though target eviction was fenced.
14883    // Deleting a run record takes these same two locks (`clean::delete_run`).
14884    // The lock files are opened where they are and never created in a
14885    // directory that is not there: a refusal changes nothing, and the lock
14886    // files are never unlinked (`pr_head::owner_lock`).
14887    let _owner = crate::pr_head::owner_lock(home, &id).map_err(lock_refusal)?;
14888    // An override must use current durable ownership, not a pre-lock snapshot.
14889    // Its liveness assessment has to be made before this fold holds the
14890    // execution lease itself (a held lease reads as a live driver); the record
14891    // it is made on is checked for identity like every other, and the final
14892    // record, read once both locks are held, is checked again below.
14893    if override_recovery_retention {
14894        let current =
14895            RunState::load_under(&id, home).map_err(|e| anyhow::Error::from(reload_refusal(&e)))?;
14896        if current.id != id {
14897            return Err(FoldRefusal::RecordGone.into());
14898        }
14899        ensure_overridable(&current)?;
14900        let claimed = crate::daemon::is_working_on_other(home, &id, Timestamp::now())?;
14901        anyhow::ensure!(
14902            current.liveness_under(home, claimed) == crate::run::Liveness::Dead,
14903            "run is live or its ownership is unknown"
14904        );
14905    }
14906    let _driver = crate::driver::maintenance(home, &id).map_err(lock_refusal)?;
14907    // Both locks are held, so no handover, driver claim, deletion or other
14908    // fold can change the record from here on: act on it, not on the earlier
14909    // read. There is no fallback to that read - a record that cannot be read
14910    // again, or is not this run's, ends the fold and touches nothing.
14911    let loaded = match reload {
14912        Reload::Tolerant => RunState::load_tolerant_under(&id, home),
14913        Reload::Strict => RunState::load_under(&id, home),
14914    };
14915    match loaded {
14916        Ok(fresh) if fresh.id == id => *state = fresh,
14917        Ok(_) => return Err(FoldRefusal::RecordGone.into()),
14918        Err(e) => return Err(reload_refusal(&e).into()),
14919    }
14920    if override_recovery_retention {
14921        ensure_overridable(state)?;
14922    }
14923    let drop_winner = decide(state)?;
14924    if !state.candidate_preservation.is_empty() || !state.interrupted_implementations.is_empty() {
14925        return Err(preservation_refusal());
14926    }
14927    let retention_reason = crate::pr_recovery::source_retention_reason(home, state);
14928    if let Some(reason) = &retention_reason
14929        && !override_recovery_retention
14930    {
14931        return Err(FoldRefusal::Retained(reason.clone()).into());
14932    }
14933    let mut output_guards = Vec::new();
14934    for entry in std::fs::read_dir(state.worktree_root())
14935        .into_iter()
14936        .flatten()
14937        .flatten()
14938    {
14939        if entry.path().join(".git").is_file() {
14940            output_guards
14941                .push(crate::retention::OutputLease::take(&entry.path(), true).map_err(live_or)?);
14942        }
14943    }
14944    let repo = state.repo.clone();
14945    // CLI, Web and automatic cleanup all enter here, independently of
14946    // Runner::fold_losers. Protect deletion and shared config release too.
14947    //
14948    // Lock order. A handover (`handover::release`, a review taking a branch
14949    // over) holds repository coordination and then asks for this run's owner
14950    // lock; this fold already holds the owner lock. An automatic fold must not
14951    // *wait* for coordination here: the handover would wait for the owner lock
14952    // while the fold waited for coordination, and neither bound (the handover's
14953    // short retry, the fold's `timeout_resource_wait`) resolves that inversion
14954    // - the handover fails its startup, which costs the task an attempt. So it
14955    // asks once; when the lease is busy it gives way: everything it holds is
14956    // released on return, nothing was changed or saved, and the run is `live`
14957    // for this pass and judged again on a later one. The explicit callers
14958    // (`magi fold`, the phone's route) were asked for by a person and still
14959    // wait, bounded as before.
14960    let _coordination = if reload == Reload::Tolerant {
14961        match crate::repo_lock::SeatLease::operation_with(
14962            &repo,
14963            state.config.coordination.as_ref(),
14964            &crate::repo_lock::WaitPolicy::immediate(),
14965        )
14966        .await
14967        {
14968            Ok(lease) => lease,
14969            Err(e) => return Err(live_or(e)),
14970        }
14971    } else {
14972        let wait = repository_wait(state, None);
14973        match coordinate_operation(state, &repo, &wait).await {
14974            Ok(lease) => lease,
14975            Err(e) => {
14976                state.save_under(home)?;
14977                return Err(live_or(e));
14978            }
14979        }
14980    };
14981    // Confirmed merges dispose of their owned sources after durable evidence
14982    // capture. Preflight every source before removing anything. A failure of
14983    // this stage is, by what the stage is for, an incomplete proof - unless
14984    // it is only a lock somebody else holds.
14985    let _source_outputs = if retention_reason.is_some()
14986        || (state.status == RunStatus::Merged && state.merge.as_ref().is_some_and(|merge| merge.ok))
14987    {
14988        match verify_merged_fold_sources(state, drop_winner, home).await {
14989            Ok(held) => held,
14990            Err(e) => return Err(source_proof_failure(e)),
14991        }
14992    } else {
14993        Vec::new()
14994    };
14995    if let Some(reason) = retention_reason {
14996        state.event(
14997            "fold",
14998            format!(
14999                "operator CLI --override-recovery-retention authorized deletion for run {}: bypassed {reason}",
15000                state.id
15001            ),
15002        );
15003        state.save_under(home)?;
15004    }
15005    let root = state.worktree_root();
15006    let winner = state.tally.as_ref().map(|t| t.winner);
15007    let mut removed = Vec::new();
15008    let isolated = crate::build_target::isolated(&state.config);
15009
15010    for i in 0..state.candidates.len() {
15011        let c = state.candidates[i].clone();
15012        let is_winner = Some(c.label) == winner;
15013        if is_winner && !drop_winner {
15014            continue;
15015        }
15016        let existed = c.worktree.exists();
15017        let target = fold_target(home, &root, &c.worktree, isolated);
15018        // A vanished directory can still have a Git registration that keeps
15019        // its branch checked out. Remove that registration before the branch.
15020        remove_preserved_worktree(&repo, &c.worktree).await?;
15021        reclaim_fold_target(home, target);
15022        if existed {
15023            removed.push(c.worktree.to_string_lossy().into_owned());
15024        }
15025        // A branch handed to a later run (and its pull request) is not this
15026        // run's to delete.
15027        let handed_over = state.released_branches.contains(&c.branch);
15028        if !handed_over && git::branch_exists(&repo, &c.branch).await? {
15029            if !git::branch_delete(&repo, &c.branch).await? {
15030                bail!("candidate branch removal refused");
15031            }
15032            removed.push(c.branch.clone());
15033        }
15034        state.candidates[i].folded = true;
15035    }
15036
15037    for name in std::fs::read_dir(&root).into_iter().flatten().flatten() {
15038        let path = name.path();
15039        let keep = !drop_winner
15040            && winner.is_some_and(|w| {
15041                path.file_name()
15042                    .is_some_and(|n| n == format!("cand-{w}").as_str())
15043            });
15044        if keep {
15045            continue;
15046        }
15047        let target = fold_target(home, &root, &path, isolated);
15048        remove_read_seat_worktree(state, &path).await?;
15049        reclaim_fold_target(home, target);
15050        removed.push(path.to_string_lossy().into_owned());
15051    }
15052
15053    // `root` (`wt/<...>/<short>/`) held nothing but this run's candidate and
15054    // judge worktrees, so once the loop above has cleared all of them out,
15055    // the parent is a bare directory nobody else was ever going to remove -
15056    // git only ever managed what was inside it. Left alone, one of these
15057    // accumulates per fully-folded run; the operator's own machine had 74.
15058    // `remove_if_empty` re-checks rather than assuming: a run whose winner
15059    // was kept (`!drop_winner`) leaves its directory behind on purpose, and
15060    // so does anything a run never claimed that happens to share the bay.
15061    remove_if_empty(&root);
15062
15063    if state.enabled_worktree_config && drop_winner {
15064        // A release, not a raw disable: some sibling run in this repository
15065        // may still hold its own reference (see `git::acquire_worktree_config`),
15066        // and only the last release actually turns the setting back off.
15067        git::release_worktree_config(&repo).await.ok();
15068        state.enabled_worktree_config = false;
15069    }
15070    // What this fold itself found, written in the same locked save: nothing
15071    // left to remove and no bay on disk (a failed or erroring check is not
15072    // "gone"). The busy-time fold turn skips such a run only while the bay is
15073    // still confirmed absent; any fold that found work clears the mark.
15074    state.fold_settled_at =
15075        (removed.is_empty() && matches!(root.try_exists(), Ok(false))).then(Timestamp::now);
15076    state.save_under(home)?;
15077    Ok(removed)
15078}
15079
15080async fn verify_merged_fold_sources(
15081    state: &RunState,
15082    drop_winner: bool,
15083    home: &Path,
15084) -> Result<Vec<std::fs::File>> {
15085    let winner = state.tally.as_ref().map(|t| t.winner);
15086    let mut heads = BTreeSet::new();
15087    for candidate in &state.candidates {
15088        if Some(candidate.label) == winner && !drop_winner {
15089            continue;
15090        }
15091        anyhow::ensure!(
15092            candidate.worktree.parent() == Some(state.worktree_root().as_path()),
15093            "candidate recovery source is outside the inventoried run root: {}",
15094            candidate.worktree.display()
15095        );
15096        match std::fs::symlink_metadata(&candidate.worktree) {
15097            Ok(_) => {}
15098            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
15099            Err(error) => return Err(error.into()),
15100        }
15101        if !state.released_branches.contains(&candidate.branch)
15102            && git::branch_exists(&state.repo, &candidate.branch).await?
15103        {
15104            heads.insert(git::rev_parse(&state.repo, &candidate.branch).await?);
15105        }
15106    }
15107    let mut cargo_guards = Vec::new();
15108    let entries = match std::fs::read_dir(state.worktree_root()) {
15109        Ok(entries) => Some(entries),
15110        Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
15111        Err(error) => return Err(error.into()),
15112    };
15113    for entry in entries.into_iter().flatten() {
15114        let path = entry?.path();
15115        let metadata = std::fs::symlink_metadata(&path)?;
15116        anyhow::ensure!(
15117            metadata.is_dir() && !metadata.file_type().is_symlink(),
15118            "non-directory or symlink recovery source retained: {}",
15119            path.display()
15120        );
15121        if !drop_winner
15122            && winner.is_some_and(|w| {
15123                path.file_name()
15124                    .is_some_and(|name| name == format!("cand-{w}").as_str())
15125            })
15126        {
15127            continue;
15128        }
15129        anyhow::ensure!(
15130            path.join(".git").is_file(),
15131            "unregistered recovery source retained: {}",
15132            path.display()
15133        );
15134        anyhow::ensure!(
15135            git::git(
15136                &path,
15137                &[
15138                    "status",
15139                    "--porcelain",
15140                    "--untracked-files=all",
15141                    "--ignored",
15142                    "--",
15143                    ".",
15144                    ":(exclude)target"
15145                ]
15146            )
15147            .await?
15148            .is_empty(),
15149            "source changes or ignored recovery files retained: {}",
15150            path.display()
15151        );
15152        match std::fs::symlink_metadata(path.join("target")) {
15153            Ok(_) => {
15154                cargo_guards.extend(crate::retention::verify_residue(home, &state.id, &path).await?)
15155            }
15156            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
15157            Err(error) => return Err(error.into()),
15158        }
15159        for checkpoint in [
15160            "rebase-merge",
15161            "rebase-apply",
15162            "sequencer",
15163            "CHERRY_PICK_HEAD",
15164            "MERGE_HEAD",
15165            "REBASE_HEAD",
15166            "REVERT_HEAD",
15167            "BISECT_LOG",
15168            "AUTO_MERGE",
15169            "MERGE_MSG",
15170        ] {
15171            let location = git::git(
15172                &path,
15173                &[
15174                    "rev-parse",
15175                    "--path-format=absolute",
15176                    "--git-path",
15177                    checkpoint,
15178                ],
15179            )
15180            .await?;
15181            anyhow::ensure!(
15182                matches!(std::fs::symlink_metadata(location.trim()), Err(ref e)
15183                if e.kind() == std::io::ErrorKind::NotFound),
15184                "Git recovery checkpoint retained: {checkpoint}"
15185            );
15186        }
15187        heads.insert(git::rev_parse(&path, "HEAD").await?);
15188    }
15189    crate::fold_evidence::preserve(state, home, &heads).await?;
15190
15191    Ok(cargo_guards)
15192}
15193
15194/// Remove `dir` if it exists and has nothing in it.
15195///
15196/// Best-effort and silent by design: a directory that is not empty (a run
15197/// whose winner is still parked there, a stray file some other process left)
15198/// is exactly the case this must refuse, and a directory that is already gone
15199/// is not a failure worth reporting either. `std::fs::remove_dir` itself
15200/// already refuses a non-empty directory, so the emptiness check below is
15201/// belt, not suspenders - it is what keeps this from ever attempting the
15202/// removal in the case that matters, rather than trusting `remove_dir`'s
15203/// error path to have no side effects if it ever changed.
15204fn remove_if_empty(dir: &Path) {
15205    if dir.is_dir() && std::fs::read_dir(dir).is_ok_and(|mut entries| entries.next().is_none()) {
15206        std::fs::remove_dir(dir).ok();
15207    }
15208}
15209
15210/// Severity of the worst open finding in the last review round, for reporting.
15211pub fn worst_open(state: &RunState) -> Option<Severity> {
15212    state
15213        .reviews
15214        .last()?
15215        .reviews
15216        .iter()
15217        .flat_map(|r| r.findings.iter())
15218        .map(|f| f.severity)
15219        .max()
15220}
15221
15222/// `[worktree] setup` hides its products per worktree, which needs
15223/// `extensions.worktreeConfig`. Taken once per run and released with the run's
15224/// worktrees, like the hook's; every place that runs setup calls this first.
15225async fn ensure_setup_config(state: &mut RunState, repo: &Path) -> Result<()> {
15226    if !state.config.worktree.setup.is_empty() && !state.enabled_worktree_config {
15227        git::acquire_worktree_config(repo).await?;
15228        state.enabled_worktree_config = true;
15229    }
15230    Ok(())
15231}
15232
15233#[cfg(test)]
15234mod tests {
15235    #[tokio::test]
15236    async fn launcher_base_fetch_requires_remote_success() {
15237        let tmp = tempfile::tempdir().unwrap();
15238        let repo = tmp.path().join("repo");
15239        let remote = tmp.path().join("remote");
15240        std::fs::create_dir(&repo).unwrap();
15241        std::fs::create_dir(&remote).unwrap();
15242        git::git(&remote, &["init", "--bare", "-b", "main"])
15243            .await
15244            .unwrap();
15245        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
15246        git::git(
15247            &repo,
15248            &[
15249                "-c",
15250                "user.name=Fixture",
15251                "-c",
15252                "user.email=fixture@example.invalid",
15253                "commit",
15254                "--allow-empty",
15255                "-m",
15256                "fixture",
15257            ],
15258        )
15259        .await
15260        .unwrap();
15261        git::git(
15262            &repo,
15263            &["remote", "add", "origin", remote.to_str().unwrap()],
15264        )
15265        .await
15266        .unwrap();
15267        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
15268        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
15269        assert_eq!(
15270            resolve_base(&repo, "main", "origin", None)
15271                .await
15272                .unwrap()
15273                .commit,
15274            head
15275        );
15276        #[cfg(unix)]
15277        {
15278            let policy: crate::config::Coordination = toml::from_str(
15279                "contract_file='fixture.contract'\ncontract_token='fixture-v1'\nlock_file='fixture.lock'",
15280            ).unwrap();
15281            std::fs::write(repo.join(".git/fixture.contract"), "fixture-v1").unwrap();
15282            std::fs::remove_file(repo.join(".git/FETCH_HEAD")).unwrap();
15283            let held = crate::repo_lock::SeatLease::operation_with(
15284                &repo,
15285                Some(&policy),
15286                &crate::repo_lock::WaitPolicy::default(),
15287            )
15288            .await
15289            .unwrap();
15290            assert!(held.is_some());
15291            let fetch = resolve_base(&repo, "main", "origin", Some(&policy));
15292            tokio::pin!(fetch);
15293            assert!(
15294                tokio::time::timeout(Duration::from_millis(50), &mut fetch)
15295                    .await
15296                    .is_err()
15297            );
15298            assert!(
15299                !repo.join(".git/FETCH_HEAD").exists(),
15300                "no fetch before admission"
15301            );
15302            drop(held);
15303            let fetched = fetch.await.unwrap();
15304            assert_eq!(fetched.commit, head);
15305            assert_eq!(fetched.remote, "origin");
15306            assert_eq!(fetched.branch, "main");
15307        }
15308        // A surviving tracking ref is not successful fetch evidence.
15309        git::git(
15310            &repo,
15311            &[
15312                "remote",
15313                "set-url",
15314                "origin",
15315                tmp.path().join("missing").to_str().unwrap(),
15316            ],
15317        )
15318        .await
15319        .unwrap();
15320        let error = resolve_base(&repo, "main", "origin", None)
15321            .await
15322            .unwrap_err()
15323            .to_string();
15324        assert!(error.contains("cannot read origin/main"));
15325        assert!(error.contains("refusing to branch off"));
15326    }
15327
15328    #[test]
15329    fn should_retitle_only_replaces_magi_shaped_or_leaked_titles() {
15330        let leaked = vec!["chore(deps): update a crate".to_owned()];
15331        let own = "fix(daemon): apply a chosen action";
15332        assert!(should_retitle("", own, &leaked));
15333        assert!(should_retitle(
15334            &format!("{REVIEW_PROMPT_OPENING} `x`"),
15335            own,
15336            &leaked
15337        ));
15338        assert!(should_retitle(
15339            "chore: land candidate A of run 1",
15340            own,
15341            &leaked
15342        ));
15343        assert!(should_retitle(
15344            "magi: candidate A (uncommitted work)",
15345            own,
15346            &leaked
15347        ));
15348        assert!(should_retitle("chore(deps): update a crate", own, &leaked));
15349        assert!(!should_retitle("feat: renamed by hand", own, &leaked));
15350        assert!(!should_retitle("", "chore(deps): update a crate", &leaked));
15351    }
15352
15353    #[test]
15354    fn pr_merge_plan_creates_adopts_or_stops() {
15355        assert_eq!(pr_merge_plan(Ok(land::OpenPr::None)), PrPlan::Create);
15356        assert_eq!(
15357            pr_merge_plan(Ok(land::OpenPr::One {
15358                url: "u".into(),
15359                title: "t".into()
15360            })),
15361            PrPlan::Adopt {
15362                url: "u".into(),
15363                title: "t".into()
15364            }
15365        );
15366        let PrPlan::Stop(many) =
15367            pr_merge_plan(Ok(land::OpenPr::Many(vec!["a".into(), "b".into()])))
15368        else {
15369            panic!("many must stop");
15370        };
15371        assert!(many.contains('a') && many.contains('b'));
15372        let PrPlan::Stop(err) = pr_merge_plan(Err(anyhow::anyhow!("bad token"))) else {
15373            panic!("a failed lookup must stop");
15374        };
15375        assert!(err.contains("bad token"));
15376    }
15377
15378    use super::*;
15379    use crate::run::GateStatus;
15380    use std::collections::BTreeMap;
15381    use std::time::Duration;
15382
15383    fn conductor() -> AgentSpec {
15384        AgentSpec {
15385            id: "conductor".to_owned(),
15386            kind: crate::config::AgentKind::Command,
15387            model: None,
15388            command: vec!["true".to_owned()],
15389            extra_args: Vec::new(),
15390            env: BTreeMap::new(),
15391            prompt_delivery: None,
15392            max_turn_secs: None,
15393        }
15394    }
15395
15396    fn spec(id: &str) -> AgentSpec {
15397        AgentSpec {
15398            id: id.to_owned(),
15399            kind: crate::config::AgentKind::Command,
15400            model: None,
15401            command: vec!["true".to_owned()],
15402            extra_args: Vec::new(),
15403            env: BTreeMap::new(),
15404            prompt_delivery: None,
15405            max_turn_secs: None,
15406        }
15407    }
15408
15409    fn ids(xs: &[&str]) -> BTreeSet<String> {
15410        xs.iter().map(|s| (*s).to_owned()).collect()
15411    }
15412
15413    #[test]
15414    fn pick_successor_skips_an_agent_another_seat_holds() {
15415        // Seats a and b of roster [a, b, c]; a fails, b holds the other seat.
15416        let roster = [spec("a"), spec("b"), spec("c")];
15417        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
15418        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
15419    }
15420
15421    #[test]
15422    fn pick_successor_respects_the_occupant_after_an_earlier_handover() {
15423        // The other seat started on c but was handed to d; c is free again.
15424        let roster = [spec("a"), spec("b"), spec("c"), spec("d")];
15425        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
15426        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
15427        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b", "c"]));
15428        assert_eq!(next.map(|s| s.id.as_str()), Some("d"));
15429    }
15430
15431    #[test]
15432    fn pick_successor_falls_back_to_a_duplicate_when_no_distinct_agent_remains() {
15433        let roster = [spec("a"), spec("b")];
15434        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
15435        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15436        let carried = ids(&["b"]);
15437        let next = pick_successor(&roster, 0, &ids(&["a"]), Some(&carried), &ids(&["b"]));
15438        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15439    }
15440
15441    #[test]
15442    fn pick_successor_returns_none_without_any_untried_successor() {
15443        let roster = [spec("a"), spec("b")];
15444        assert!(pick_successor(&roster, 1, &ids(&["b"]), None, &ids(&["a"])).is_none());
15445        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), None, &ids(&[])).is_none());
15446        let carried = ids(&["a"]);
15447        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), Some(&carried), &ids(&[])).is_none());
15448    }
15449
15450    #[test]
15451    fn pick_successor_rescue_avoids_another_seats_occupant() {
15452        // b is a carried failure and free; a is held by the other seat.
15453        let roster = [spec("a"), spec("b"), spec("c")];
15454        let carried = ids(&["b", "c"]);
15455        let next = pick_successor(&roster, 2, &ids(&["c"]), Some(&carried), &ids(&["a"]));
15456        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15457    }
15458
15459    #[test]
15460    fn next_for_seat_prefers_an_agent_that_has_not_failed() {
15461        let roster = [spec("a"), spec("b"), spec("c")];
15462        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["b"]));
15463        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
15464    }
15465
15466    #[test]
15467    fn next_for_seat_rescues_a_failed_agent_only_when_nothing_else_is_left() {
15468        let roster = [spec("a"), spec("b"), spec("c")];
15469        let failed = ids(&["a", "b", "c"]);
15470        // Rescue looks at the whole roster, once per id, then runs out.
15471        let mut tried = ids(&["b"]);
15472        let first = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
15473        assert_eq!(first.id, "a");
15474        tried.insert(first.id.clone());
15475        let second = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
15476        assert_eq!(second.id, "c");
15477        tried.insert(second.id.clone());
15478        assert!(next_for_seat(&roster, 1, &tried, &failed).is_none());
15479    }
15480
15481    #[test]
15482    fn next_for_seat_ignores_failed_ids_no_longer_on_the_roster() {
15483        let roster = [spec("a"), spec("b")];
15484        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["gone"]));
15485        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15486    }
15487
15488    #[test]
15489    fn pick_start_spec_starts_on_the_last_answerer_when_still_eligible() {
15490        let roster = [spec("a"), spec("b"), spec("c")];
15491        let h = SeatHistory {
15492            failed: ids(&["a"]),
15493            last_ok: Some("b".to_owned()),
15494            last_fail: None,
15495        };
15496        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&h)).id, "b");
15497        // A last answerer that left the roster, or later failed, is ignored.
15498        let gone = SeatHistory {
15499            last_ok: Some("zzz".to_owned()),
15500            ..h.clone()
15501        };
15502        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&gone)).id, "b");
15503        let failed = SeatHistory {
15504            failed: ids(&["a", "b"]),
15505            last_ok: Some("b".to_owned()),
15506            last_fail: None,
15507        };
15508        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&failed)).id, "c");
15509    }
15510
15511    #[test]
15512    fn handover_seat_mints_a_session_id_distinct_from_the_previous_agents() {
15513        let first = SeatState::new("review-1", "alpha", 7);
15514        let next = handover_seat("review-1", "gamma", 7);
15515        assert_ne!(first.claude_session, next.claude_session);
15516    }
15517
15518    #[test]
15519    fn re_handing_a_seat_to_the_same_agent_mints_a_new_session_id() {
15520        let mut state = state_with_summary("x", "y");
15521        let a = handover_seat("review-1", "beta", state.next_seat_seed());
15522        let b = handover_seat("review-1", "beta", state.next_seat_seed());
15523        assert_ne!(a.claude_session, b.claude_session);
15524    }
15525
15526    #[test]
15527    fn pick_start_spec_falls_back_to_the_spec_when_the_whole_roster_failed() {
15528        let roster = [spec("a"), spec("b")];
15529        let h = SeatHistory {
15530            failed: ids(&["a", "b"]),
15531            ..SeatHistory::default()
15532        };
15533        assert_eq!(pick_start_spec(&roster, spec("b"), Some(&h)).id, "b");
15534        assert_eq!(pick_start_spec(&roster, spec("b"), None).id, "b");
15535        assert_eq!(pick_start_spec(&[], spec("b"), Some(&h)).id, "b");
15536    }
15537
15538    // `next_untried_in_roster` is the property `resume_seat_handovers`'s own
15539    // fallback loop depends on to terminate: it must walk forward from the
15540    // seat's own position, never restart at the front of the roster, and it
15541    // must never hand back an id already tried, however many times that id
15542    // happens to appear.
15543
15544    #[test]
15545    fn failure_signature_ignores_numbers_and_paths() {
15546        assert_eq!(
15547            failure_signature("exited with Some(2) and no usable output"),
15548            failure_signature("exited with Some(137) and no usable output")
15549        );
15550        assert_eq!(
15551            failure_signature("process exited with no usable output (exit code 2)"),
15552            failure_signature("process exited with no usable output (exit code 137)")
15553        );
15554        for (old, new) in [
15555            (
15556                "exited with Some(2) and no usable output",
15557                "process exited with no usable output (exit code 2)",
15558            ),
15559            (
15560                "exited with None and no usable output",
15561                "process exited with no usable output (exit code unavailable)",
15562            ),
15563        ] {
15564            let previous = FailClass::Other(failure_signature(old));
15565            let current = FailClass::Other(failure_signature(new));
15566            assert_eq!(previous, current, "resumption retains the failure class");
15567            assert!(!should_hand_over(Some(&previous), &current));
15568        }
15569        assert_eq!(
15570            failure_signature("cannot open /tmp/a/b.txt: denied\nsecond line"),
15571            failure_signature("cannot open /var/x.txt: denied")
15572        );
15573        assert_ne!(failure_signature("boom"), failure_signature("bang"));
15574    }
15575
15576    #[test]
15577    fn quota_and_timeout_always_hand_over_other_failures_stop_on_a_repeat() {
15578        let other = FailClass::Other("x".into());
15579        assert!(should_hand_over(None, &FailClass::Quota));
15580        assert!(should_hand_over(Some(&other), &FailClass::Quota));
15581        assert!(should_hand_over(
15582            Some(&FailClass::Timeout),
15583            &FailClass::Timeout
15584        ));
15585        assert!(should_hand_over(None, &other));
15586        assert!(!should_hand_over(Some(&other), &other));
15587        assert!(should_hand_over(
15588            Some(&other),
15589            &FailClass::Other("y".into())
15590        ));
15591        // A quota or timeout in between ends the run of identical failures.
15592        assert!(should_hand_over(Some(&FailClass::Timeout), &other));
15593        assert!(should_hand_over(Some(&FailClass::Quota), &other));
15594    }
15595
15596    #[test]
15597    fn a_handover_seat_never_reuses_the_previous_agents_session_id() {
15598        let a = SeatState::new("judge-1", "alpha", 7);
15599        let b = handover_seat("judge-1", "beta", 7);
15600        assert_ne!(a.claude_session, b.claude_session);
15601        assert_eq!(b.turns, 0);
15602    }
15603
15604    #[test]
15605    fn a_timeout_is_classified_apart_from_other_failures() {
15606        assert_eq!(
15607            FailClass::of(&AgentOutcome::Failed(TIMED_OUT.to_owned())),
15608            Some(FailClass::Timeout)
15609        );
15610        assert!(matches!(
15611            FailClass::of(&AgentOutcome::Failed("boom".to_owned())),
15612            Some(FailClass::Other(_))
15613        ));
15614    }
15615
15616    #[test]
15617    fn next_untried_in_roster_walks_forward_from_the_seats_own_position() {
15618        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
15619        let tried = BTreeSet::from(["beta".to_owned()]);
15620        // beta sits at index 1; the next candidate is gamma, never alpha —
15621        // which is very likely a different candidate slot's own agent.
15622        let next = next_untried_in_roster(&roster, 1, &tried);
15623        assert_eq!(next.map(|s| s.id.as_str()), Some("gamma"));
15624    }
15625
15626    #[test]
15627    fn next_untried_in_roster_does_not_wrap_back_past_its_own_start() {
15628        let roster = vec![spec("alpha"), spec("beta")];
15629        let tried = BTreeSet::from(["beta".to_owned()]);
15630        // beta is the roster's last entry: nothing follows it, and alpha —
15631        // earlier in the roster, almost certainly a different candidate
15632        // slot's own agent — must not be reached by wrapping back to it.
15633        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
15634    }
15635
15636    #[test]
15637    fn next_untried_in_roster_stops_once_the_tail_is_exhausted_even_if_earlier_ids_are_untried() {
15638        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
15639        let tried = BTreeSet::from(["beta".to_owned(), "gamma".to_owned()]);
15640        // beta (index 1) and gamma (index 2, the only entry after it) have
15641        // both been tried; alpha (index 0) never has, but it comes before
15642        // beta's own position, so there is nothing further for this seat.
15643        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
15644    }
15645
15646    #[test]
15647    fn next_untried_in_roster_skips_ids_already_tried_even_when_duplicated() {
15648        let roster = vec![spec("a"), spec("a"), spec("b")];
15649        let tried = BTreeSet::from(["a".to_owned()]);
15650        let next = next_untried_in_roster(&roster, 0, &tried);
15651        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15652    }
15653
15654    #[test]
15655    fn next_untried_in_roster_returns_none_once_every_id_is_tried() {
15656        let roster = vec![spec("a"), spec("b")];
15657        let tried = BTreeSet::from(["a".to_owned(), "b".to_owned()]);
15658        assert!(next_untried_in_roster(&roster, 0, &tried).is_none());
15659    }
15660
15661    #[test]
15662    fn remove_if_empty_only_ever_takes_a_bare_directory() {
15663        let dir = tempfile::tempdir().unwrap();
15664        let bay = dir.path().join("ffff");
15665
15666        // Not there yet: nothing to do, nothing to panic on.
15667        remove_if_empty(&bay);
15668        assert!(!bay.exists());
15669
15670        // Something still inside - the winner's worktree, or a stray file -
15671        // keeps the directory standing.
15672        std::fs::create_dir_all(bay.join("cand-A")).unwrap();
15673        remove_if_empty(&bay);
15674        assert!(bay.exists(), "non-empty directory must survive");
15675
15676        // Once the last entry is gone, so is the directory itself.
15677        std::fs::remove_dir(bay.join("cand-A")).unwrap();
15678        remove_if_empty(&bay);
15679        assert!(!bay.exists(), "an empty bay is a leftover, not a record");
15680    }
15681
15682    // `round_is_clean` is the exact decision this task fixed: a round with a
15683    // seat that never answered must not read the same as a round every seat
15684    // actually reviewed. These are deterministic and process-free by design —
15685    // the equivalent end-to-end check (a real reviewer timing out under a
15686    // live graph run) is a genuine race against wall-clock contention, and a
15687    // spawn slow enough to blow even a generous budget under a loaded test
15688    // run must not turn this specific regression check flaky.
15689
15690    #[test]
15691    fn a_full_panel_that_found_nothing_is_clean() {
15692        assert!(round_is_clean(
15693            0,
15694            true,
15695            2,
15696            2,
15697            0,
15698            IncompleteReviewPolicy::Block
15699        ));
15700    }
15701
15702    #[test]
15703    fn a_missing_seat_is_never_clean_under_the_default_policy() {
15704        assert!(!round_is_clean(
15705            0,
15706            true,
15707            1,
15708            2,
15709            0,
15710            IncompleteReviewPolicy::Block
15711        ));
15712    }
15713
15714    #[test]
15715    fn warn_policy_still_refuses_a_missing_seat_with_open_findings() {
15716        assert!(!round_is_clean(
15717            1,
15718            true,
15719            1,
15720            2,
15721            0,
15722            IncompleteReviewPolicy::Warn
15723        ));
15724    }
15725
15726    #[test]
15727    fn warn_policy_gates_a_missing_seat_once_what_answered_is_clean() {
15728        assert!(round_is_clean(
15729            0,
15730            true,
15731            1,
15732            2,
15733            0,
15734            IncompleteReviewPolicy::Warn
15735        ));
15736    }
15737
15738    #[test]
15739    fn a_full_panel_with_an_open_finding_is_not_clean() {
15740        assert!(!round_is_clean(
15741            1,
15742            true,
15743            2,
15744            2,
15745            0,
15746            IncompleteReviewPolicy::Block
15747        ));
15748    }
15749
15750    #[test]
15751    fn a_full_panel_with_a_red_e2e_is_not_clean() {
15752        assert!(!round_is_clean(
15753            0,
15754            false,
15755            2,
15756            2,
15757            0,
15758            IncompleteReviewPolicy::Block
15759        ));
15760    }
15761
15762    // The stall this task closes: under the default `block` policy, a seat
15763    // missing only because it was rate limited must not force a wait for a
15764    // session limit that will not lift by the next round. `round_is_clean`
15765    // is where that quorum carve-out lives; the review loop around it never
15766    // changes what a reviewer's vote or a finding's severity means.
15767
15768    #[test]
15769    fn a_seat_missing_only_to_its_own_quota_is_clean_under_the_default_policy() {
15770        // 1 of 2 answered, and the one missing was quota'd — the exact
15771        // "review-2 rate limited (quota)" shape from the field report.
15772        assert!(round_is_clean(
15773            0,
15774            true,
15775            1,
15776            2,
15777            1,
15778            IncompleteReviewPolicy::Block
15779        ));
15780    }
15781
15782    #[test]
15783    fn a_seat_missing_for_a_reason_other_than_quota_still_waits() {
15784        // 1 of 2 answered, but the miss was a crash/timeout/parse failure,
15785        // not a quota loss (`quota_missing` stays 0) — worth another try.
15786        assert!(!round_is_clean(
15787            0,
15788            true,
15789            1,
15790            2,
15791            0,
15792            IncompleteReviewPolicy::Block
15793        ));
15794    }
15795
15796    #[test]
15797    fn a_quota_loss_does_not_excuse_an_open_finding_or_a_red_e2e() {
15798        assert!(!round_is_clean(
15799            1,
15800            true,
15801            1,
15802            2,
15803            1,
15804            IncompleteReviewPolicy::Block
15805        ));
15806        assert!(!round_is_clean(
15807            0,
15808            false,
15809            1,
15810            2,
15811            1,
15812            IncompleteReviewPolicy::Block
15813        ));
15814    }
15815
15816    #[test]
15817    fn a_panel_lost_entirely_to_quota_still_waits_rather_than_deciding_on_nobody() {
15818        // Every seat quota'd, nobody answered: there is no panel to decide
15819        // on, so this must fall through to the existing block-and-retry
15820        // fallback rather than call an unreviewed patch clean.
15821        assert!(!round_is_clean(
15822            0,
15823            true,
15824            0,
15825            2,
15826            2,
15827            IncompleteReviewPolicy::Block
15828        ));
15829    }
15830
15831    fn outcome(code: Option<i32>, resource_blocked: bool) -> CommandOutcome {
15832        CommandOutcome {
15833            command: "test".to_owned(),
15834            code,
15835            output_tail: String::new(),
15836            duration_ms: 0,
15837            resource_blocked,
15838            ..Default::default()
15839        }
15840    }
15841
15842    #[cfg(unix)]
15843    #[tokio::test]
15844    async fn incremental_admission_is_a_resource_hold_without_a_build_retry() {
15845        ask_test_home();
15846        let temp = tempfile::tempdir().unwrap();
15847        let mut runner = runner_at(RunStatus::Gating);
15848        let shell = vec!["sh".to_owned(), "-c".to_owned()];
15849        let commands = vec![
15850            "printf '%s\\n' 'incremental cache admission blocked: budget exhausted' 'error: could not compile fixture'; exit 101".to_owned(),
15851            "touch must-not-run".to_owned(),
15852        ];
15853        let (outcomes, retried, pids) = run_e2e_with_retry(
15854            &mut runner.state,
15855            &shell,
15856            &commands,
15857            temp.path(),
15858            Duration::from_secs(5),
15859            "fixture",
15860            None,
15861        )
15862        .await;
15863        assert_eq!(outcomes.len(), 1);
15864        assert!(outcomes[0].resource_blocked);
15865        assert!(!outcomes[0].build_failed());
15866        assert!(!retried);
15867        assert!(pids.is_empty());
15868        assert!(!temp.path().join("must-not-run").exists());
15869        assert_eq!(
15870            runner.state.resource_block.as_ref().unwrap().kind,
15871            "incremental cache admission"
15872        );
15873    }
15874
15875    #[test]
15876    fn verify_is_inconclusive_only_when_a_resource_blocked_outcome_is_present() {
15877        assert!(!verify_inconclusive(&[outcome(Some(0), false)]));
15878        assert!(
15879            !verify_inconclusive(&[outcome(Some(1), false)]),
15880            "an ordinary failure is still evidence about the patch"
15881        );
15882        assert!(verify_inconclusive(&[outcome(None, true)]));
15883        assert!(
15884            verify_inconclusive(&[outcome(Some(0), false), outcome(None, true)]),
15885            "one inconclusive outcome taints the whole batch"
15886        );
15887        assert!(!verify_inconclusive(&[]));
15888    }
15889
15890    #[tokio::test]
15891    async fn timed_out_pid_waiting_returns_as_soon_as_every_pid_is_confirmed_dead() {
15892        // Alive for the first two checks, then dead - confirms the loop
15893        // actually re-polls rather than deciding once and sleeping out the
15894        // ceiling regardless.
15895        let calls = std::sync::atomic::AtomicUsize::new(0);
15896        let started = Instant::now();
15897        wait_for_pids_with(
15898            &[123],
15899            |_| calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 2,
15900            Duration::from_millis(5),
15901            Duration::from_secs(5),
15902        )
15903        .await;
15904        assert!(
15905            calls.load(std::sync::atomic::Ordering::SeqCst) >= 3,
15906            "must keep checking rather than deciding on the first answer"
15907        );
15908        assert!(
15909            started.elapsed() < Duration::from_secs(1),
15910            "must return the moment it is confirmed dead, not wait out the ceiling"
15911        );
15912    }
15913
15914    #[tokio::test]
15915    async fn timed_out_pid_waiting_gives_up_at_its_ceiling_if_never_confirmed_dead() {
15916        let started = Instant::now();
15917        wait_for_pids_with(
15918            &[123],
15919            |_| true, // never reports dead
15920            Duration::from_millis(5),
15921            Duration::from_millis(30),
15922        )
15923        .await;
15924        let elapsed = started.elapsed();
15925        assert!(
15926            elapsed >= Duration::from_millis(30),
15927            "must not give up before its own ceiling: {elapsed:?}"
15928        );
15929        assert!(
15930            elapsed < Duration::from_secs(1),
15931            "must not wait past its own ceiling either: {elapsed:?}"
15932        );
15933    }
15934
15935    #[tokio::test]
15936    async fn timed_out_pid_waiting_is_a_no_op_when_nothing_was_still_running() {
15937        let started = Instant::now();
15938        wait_for_pids_with(
15939            &[],
15940            |_| true,
15941            Duration::from_secs(5),
15942            Duration::from_secs(5),
15943        )
15944        .await;
15945        assert!(
15946            started.elapsed() < Duration::from_millis(200),
15947            "an empty pid list has nothing to confirm"
15948        );
15949    }
15950
15951    // `review_conclusion` is the exact decision the review hand-off task
15952    // fixed: a round budget spent (or a tree that stopped moving) must not
15953    // collapse into `Blocked` regardless of what verification actually
15954    // said. Deterministic and process-free for the same reason the
15955    // `round_is_clean` family above is.
15956    fn review_round(
15957        clean: bool,
15958        blocking: usize,
15959        answered: usize,
15960        expected: usize,
15961        progressed: bool,
15962        e2e_ok: bool,
15963    ) -> ReviewRound {
15964        ReviewRound {
15965            round: 1,
15966            head: "h".to_owned(),
15967            verified_head: None,
15968            verified_at: None,
15969            reviews: Vec::new(),
15970            e2e: vec![CommandOutcome {
15971                command: "test".to_owned(),
15972                code: Some(if e2e_ok { 0 } else { 1 }),
15973                output_tail: String::new(),
15974                duration_ms: 0,
15975                resource_blocked: false,
15976                ..Default::default()
15977            }],
15978            verify_retried: false,
15979            e2e_deferred: false,
15980            e2e_defer_reason: None,
15981            fix: None,
15982            blocking,
15983            answered,
15984            expected,
15985            clean,
15986            progressed,
15987            vote_split: false,
15988            reconsideration: Vec::new(),
15989            verdict: None,
15990        }
15991    }
15992
15993    #[test]
15994    fn review_conclusion_is_none_when_nothing_has_run() {
15995        assert_eq!(review_conclusion(&[], 3), None);
15996    }
15997
15998    #[test]
15999    fn review_conclusion_is_none_while_rounds_remain() {
16000        let rounds = vec![review_round(false, 1, 2, 2, true, true)];
16001        assert_eq!(review_conclusion(&rounds, 3), None);
16002    }
16003
16004    #[test]
16005    fn review_conclusion_is_gating_once_a_round_is_clean() {
16006        let rounds = vec![review_round(true, 0, 2, 2, false, true)];
16007        assert_eq!(review_conclusion(&rounds, 3), Some(RunStatus::Gating));
16008    }
16009
16010    #[test]
16011    fn review_conclusion_hands_off_when_the_budget_is_spent_and_e2e_is_green() {
16012        let rounds = vec![
16013            review_round(false, 1, 2, 2, true, true),
16014            review_round(false, 1, 2, 2, true, true),
16015        ];
16016        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Gating));
16017    }
16018
16019    #[test]
16020    fn review_conclusion_blocks_when_the_budget_is_spent_and_e2e_is_red() {
16021        let rounds = vec![
16022            review_round(false, 1, 2, 2, true, true),
16023            review_round(false, 1, 2, 2, true, false),
16024        ];
16025        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Blocked));
16026    }
16027
16028    #[test]
16029    fn review_conclusion_stays_none_when_the_budget_is_spent_but_the_last_round_could_not_run() {
16030        // Magi never got a command to run against this round's own head — a
16031        // resource-blocked attempt, not a red one — so this must never
16032        // settle on `Blocked` the way a genuine e2e failure would. `None`
16033        // here is what tells `Runner::review_loop` to retry the check
16034        // itself rather than trust this cheap recomputation with a verdict
16035        // it cannot actually produce.
16036        let mut blocked = review_round(false, 1, 2, 2, true, false);
16037        blocked.e2e[0].resource_blocked = true;
16038        let rounds = vec![review_round(false, 1, 2, 2, true, true), blocked];
16039        assert_eq!(review_conclusion(&rounds, 2), None);
16040    }
16041
16042    #[test]
16043    fn review_conclusion_blocks_an_incomplete_panel_that_raised_nothing_even_with_green_e2e() {
16044        // Missing input, not a verified tree — never a hand-off candidate.
16045        let rounds = vec![review_round(false, 0, 1, 2, false, true)];
16046        assert_eq!(review_conclusion(&rounds, 1), Some(RunStatus::Blocked));
16047    }
16048
16049    #[test]
16050    fn review_conclusion_hands_off_when_the_tree_stagnates_before_the_budget_is_spent() {
16051        let rounds = vec![
16052            review_round(false, 1, 2, 2, false, true),
16053            review_round(false, 1, 2, 2, false, true),
16054        ];
16055        assert_eq!(review_conclusion(&rounds, 10), Some(RunStatus::Gating));
16056    }
16057
16058    fn secs(n: u64) -> Duration {
16059        Duration::from_secs(n)
16060    }
16061
16062    /// A throwaway repo with one commit on `main`, for tests that need `merge`
16063    /// to make real (and, if it runs at all, real*ly fail*) git calls.
16064    #[tokio::test]
16065    async fn selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync() {
16066        const CHILD: &str = "MAGI_SELECTED_PUBLIC_ANCESTRY_TEST";
16067        if std::env::var_os(CHILD).is_none() {
16068            // Other tests reconcile every run in the process-global home,
16069            // briefly taking owner locks. This ancestry test expects an idle
16070            // predecessor, so give it its own process and pinned test home.
16071            let output = std::process::Command::new(std::env::current_exe().unwrap())
16072                .args([
16073                    "--exact",
16074                    "graph::tests::selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync",
16075                    "--nocapture",
16076                ])
16077                .env(CHILD, "1")
16078                .env_remove("MAGI_WORKER_HOME")
16079                .env_remove("MAGI_WORKER_ID")
16080                .output()
16081                .unwrap();
16082            assert!(
16083                output.status.success()
16084                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
16085                "{}\n{}",
16086                String::from_utf8_lossy(&output.stdout),
16087                String::from_utf8_lossy(&output.stderr)
16088            );
16089            return;
16090        }
16091        ask_test_home();
16092        let tmp = tempfile::tempdir().unwrap();
16093        let repo = tmp.path().join("repo");
16094        std::fs::create_dir_all(&repo).unwrap();
16095        init_repo(&repo);
16096        let g = |args: &[&str]| {
16097            let out = std::process::Command::new("git")
16098                .args(args)
16099                .current_dir(&repo)
16100                .quiet()
16101                .output()
16102                .unwrap();
16103            assert!(
16104                out.status.success(),
16105                "{}",
16106                String::from_utf8_lossy(&out.stderr)
16107            );
16108        };
16109        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
16110        g(&["checkout", "-b", "historical"]);
16111        std::fs::write(repo.join("implementation"), "incompatible alternative").unwrap();
16112        g(&["add", "."]);
16113        g(&["commit", "-m", "old alternative"]);
16114        let obsolete = git::rev_parse(&repo, "HEAD").await.unwrap();
16115        g(&["checkout", "-b", "magi/task-selected", &base]);
16116        std::fs::write(repo.join("infrastructure"), "prerequisite").unwrap();
16117        g(&["add", "."]);
16118        g(&["commit", "-m", "measurement infrastructure"]);
16119        let prerequisite = git::rev_parse(&repo, "HEAD").await.unwrap();
16120        std::fs::write(repo.join("implementation"), "measured implementation").unwrap();
16121        g(&["add", "."]);
16122        g(&["commit", "-m", "dependent implementation"]);
16123        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
16124        g(&["checkout", "main"]);
16125        std::fs::write(repo.join("unrelated"), "current main change").unwrap();
16126        g(&["add", "."]);
16127        g(&["commit", "-m", "unrelated base change"]);
16128        let current = git::rev_parse(&repo, "HEAD").await.unwrap();
16129        let origin = tmp.path().join("origin.git");
16130        g(&[
16131            "clone",
16132            "--bare",
16133            repo.to_str().unwrap(),
16134            origin.to_str().unwrap(),
16135        ]);
16136        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
16137        g(&["fetch", "origin"]);
16138        let selection = crate::pr_recovery::Selection {
16139            url: "https://example.test/project/pull/1".into(),
16140            branch: "magi/task-selected".into(),
16141            head: head.clone(),
16142            source_head: None,
16143            source_run: None,
16144            source_proof: None,
16145            disposition: Some(crate::pr_recovery::Disposition::Review),
16146            instruction: "preserve measured behavior".into(),
16147            approved_at: jiff::Timestamp::now(),
16148        };
16149        let mut template = runner_at(RunStatus::Reviewing);
16150        template.state.repo = repo.clone();
16151        template.state.base_commit = current.clone();
16152        template.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
16153        template.state.origin = Some(crate::run::Origin::queue("selected"));
16154        template.state.pr_head = Some(selection.branch.clone());
16155        template.state.pr_recovery = Some(selection.clone());
16156        let mut runner =
16157            Runner::open_selected(&repo, template.state, template.roles, 1, current, selection)
16158                .await
16159                .unwrap();
16160        let wt = runner.state.winner().unwrap().worktree.clone();
16161        assert_eq!(git::rev_parse(&wt, "HEAD").await.unwrap(), head);
16162        assert!(git::is_ancestor(&wt, &prerequisite, "HEAD").await);
16163        assert!(!git::is_ancestor(&wt, &obsolete, "HEAD").await);
16164        assert!(runner.state.seeds.is_empty());
16165        assert_eq!(runner.state.instruction, "preserve measured behavior");
16166        runner.sync_to_base().await.unwrap();
16167        assert_eq!(
16168            std::fs::read_to_string(wt.join("infrastructure")).unwrap(),
16169            "prerequisite"
16170        );
16171        assert_eq!(
16172            std::fs::read_to_string(wt.join("implementation")).unwrap(),
16173            "measured implementation"
16174        );
16175        assert_eq!(
16176            std::fs::read_to_string(wt.join("unrelated")).unwrap(),
16177            "current main change"
16178        );
16179        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
16180        assert_eq!(
16181            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
16182            head
16183        );
16184
16185        // A failed selected-source setup stays inspectable, never resumable as a new competition.
16186        let mut partial = runner_at(RunStatus::Reviewing);
16187        partial.state.repo = repo.clone();
16188        partial.state.config.graph.worktree_root = Some(tmp.path().join("failed-worktrees"));
16189        partial.state.config.worktree.setup = vec![crate::config::SetupStep {
16190            run: Some("exit 1".into()),
16191            ..Default::default()
16192        }];
16193        let selection = runner.state.pr_recovery.clone().unwrap();
16194        partial.state.pr_recovery = Some(selection.clone());
16195        partial.state.pr_head = Some(selection.branch.clone());
16196        partial.state.origin = Some(crate::run::Origin::queue("selected"));
16197        let id = partial.state.id.clone();
16198        let error = match Runner::open_selected(
16199            &repo,
16200            partial.state,
16201            partial.roles,
16202            1,
16203            runner.state.base_commit.clone(),
16204            selection,
16205        )
16206        .await
16207        {
16208            Ok(_) => panic!("setup must fail"),
16209            Err(e) => e,
16210        };
16211        assert_eq!(
16212            error
16213                .downcast_ref::<crate::run::StartupFailure>()
16214                .unwrap()
16215                .run,
16216            id
16217        );
16218        let failed = RunState::load(&id).unwrap();
16219        assert_eq!(failed.status, RunStatus::Failed);
16220        assert_eq!(failed.liveness(false), crate::run::Liveness::Dead);
16221        assert!(Runner::resume(&id).is_err());
16222        runner.state.status = RunStatus::Ready;
16223        runner.state.driver_exited = true;
16224        runner.state.save().unwrap();
16225        let mut retry = runner_at(RunStatus::Reviewing);
16226        retry.state.repo = repo.clone();
16227        retry.state.config.graph.worktree_root = Some(tmp.path().join("retry-worktrees"));
16228        let mut reselected = runner.state.pr_recovery.clone().unwrap();
16229        reselected.approved_at = jiff::Timestamp::now();
16230        retry.state.origin = Some(crate::run::Origin::queue("selected"));
16231        retry.state.pr_head = Some(reselected.branch.clone());
16232        retry.state.pr_recovery = Some(reselected.clone());
16233        crate::pr_head::check_predecessors(&retry.state, &reselected.branch)
16234            .await
16235            .unwrap();
16236        let restarted = Runner::open_selected(
16237            &repo,
16238            retry.state,
16239            retry.roles,
16240            1,
16241            runner.state.base_commit.clone(),
16242            reselected,
16243        )
16244        .await
16245        .unwrap();
16246        assert_eq!(
16247            git::rev_parse(&restarted.state.winner().unwrap().worktree, "HEAD")
16248                .await
16249                .unwrap(),
16250            head
16251        );
16252        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
16253        assert_eq!(
16254            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
16255            head
16256        );
16257    }
16258
16259    #[tokio::test]
16260    #[cfg(unix)]
16261    async fn fallback_and_interrupted_restoration_require_coordination() {
16262        use std::os::fd::AsRawFd as _;
16263        ask_test_home();
16264        let tmp = tempfile::tempdir().unwrap();
16265        let mut runner = registered_runner(tmp.path()).await;
16266        runner.state.config.graph.timeout_resource_wait = 1;
16267        let winner = runner.state.candidates[0].clone();
16268        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16269        let leftover = winner.worktree.join("leftover");
16270        std::fs::write(&leftover, "untrusted edits").unwrap();
16271        let next = tmp.path().join("next-fixer");
16272        let mut failed = spec("first");
16273        failed.command = vec!["sh".into(), "-c".into(), "exit 1".into()];
16274        let mut successor = spec("second");
16275        successor.command = vec![
16276            "sh".into(),
16277            "-c".into(),
16278            format!("touch '{}'; echo done", next.display()),
16279        ];
16280        let attempts = vec![
16281            (failed.clone(), "first".into()),
16282            (successor.clone(), "second".into()),
16283        ];
16284        let lock_path = runner.state.repo.join(".git/updater.lock");
16285        let external = std::fs::File::create(&lock_path).unwrap();
16286        assert_eq!(
16287            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16288            0
16289        );
16290        let artifacts = tmp.path().join("artifacts");
16291        let build = |spec, seat| SeatJob {
16292            spec,
16293            seat,
16294            cwd: winner.worktree.clone(),
16295            prompt: "fixture".into(),
16296            timeout: Duration::from_secs(10),
16297            allow_write: true,
16298            sessions: false,
16299            artifacts: artifacts.clone(),
16300            stem: "fix".into(),
16301            handover: None,
16302        };
16303        let (_, _, out) = runner
16304            .ask_fixer_among(
16305                attempts.clone(),
16306                "graft",
16307                None,
16308                Some((&winner.worktree, &head)),
16309                build,
16310            )
16311            .await;
16312        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
16313        assert!(leftover.exists(), "contention must prevent clean");
16314        assert!(!next.exists());
16315        assert!(runner.state.handovers.is_empty());
16316        // Early interrupted-repair rollback uses the same protected route.
16317        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
16318            from_run: "earlier".into(),
16319            generation: 1,
16320            mode: crate::recovery::Mode::VerifyRepair,
16321            reasons: Vec::new(),
16322            reviewed_head: None,
16323            rounds: Vec::new(),
16324            open_findings: Vec::new(),
16325            evidence: None,
16326            criteria_inherited: true,
16327            repair: crate::recovery::Repair::Started {
16328                before: head.clone(),
16329            },
16330        });
16331        assert!(
16332            runner
16333                .recovery_repair(&winner)
16334                .await
16335                .unwrap_err()
16336                .is::<crate::repo_lock::ResourceBlocked>()
16337        );
16338        assert!(matches!(
16339            runner.state.recovery.as_ref().unwrap().repair,
16340            crate::recovery::Repair::Started { .. }
16341        ));
16342        assert!(leftover.exists());
16343        drop(external);
16344        runner.recovery_repair(&winner).await.unwrap();
16345        assert!(!leftover.exists());
16346        assert!(matches!(
16347            runner.state.recovery.as_ref().unwrap().repair,
16348            crate::recovery::Repair::Done { .. }
16349        ));
16350        // A hard lock-open failure also leaves HEAD and untracked work intact.
16351        std::fs::remove_file(&lock_path).unwrap();
16352        std::fs::create_dir(&lock_path).unwrap();
16353        std::fs::write(&leftover, "untrusted edits").unwrap();
16354        let (_, _, out) = runner
16355            .ask_fixer_among(
16356                attempts,
16357                "graft",
16358                None,
16359                Some((&winner.worktree, &head)),
16360                build,
16361            )
16362            .await;
16363        assert!(matches!(out, AgentOutcome::Failed(_)));
16364        assert!(leftover.exists());
16365        assert!(!next.exists());
16366        assert_eq!(
16367            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16368            head
16369        );
16370    }
16371
16372    #[cfg(unix)]
16373    async fn registered_runner(root: &Path) -> Runner {
16374        repository_runner(root, crate::config::test_coordination()).await
16375    }
16376
16377    async fn repository_runner(
16378        root: &Path,
16379        coordination: Option<crate::config::Coordination>,
16380    ) -> Runner {
16381        ask_test_home();
16382        let repo = root.join("repo");
16383        std::fs::create_dir_all(&repo).unwrap();
16384        init_repo(&repo);
16385        if coordination.is_some() {
16386            std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
16387        }
16388        let mut runner = runner_at(RunStatus::Prep);
16389        runner.state.repo = repo.clone();
16390        runner.state.config.coordination = coordination;
16391        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16392        runner.state.config.graph.worktree_root = Some(root.join("wt"));
16393        runner.state.config.graph.advise = false;
16394        runner.roles.implementers = vec![spec("implement")];
16395        runner.roles.judges = vec![spec("judge")];
16396        runner.prep().await.unwrap();
16397        runner
16398    }
16399
16400    const AUTH_OUTAGE: &str = r#"{"is_error":true,"terminal_reason":"api_error","result":"Failed to authenticate: OAuth session expired and could not be refreshed"}"#;
16401
16402    #[tokio::test]
16403    async fn all_unauthenticated_wave_stops_the_node_without_nudges() {
16404        let tmp = tempfile::tempdir().unwrap();
16405        let mut runner = repository_runner(tmp.path(), None).await;
16406        let prompts = runner.state.config.prompts.clone();
16407        let run = runner.state.id.clone();
16408        let ctx = WaveCtx {
16409            carry_seats: false,
16410            pauses: None,
16411            run: &run,
16412            node: "advise",
16413            prompts: &prompts,
16414            cache: None,
16415            round: None,
16416        };
16417        let jobs: Vec<_> = ["alpha", "beta"]
16418            .into_iter()
16419            .map(|id| SeatJob {
16420                spec: scripted(id, AUTH_OUTAGE),
16421                seat: SeatState::new(id, id, 7),
16422                prompt: "propose".into(),
16423                cwd: runner.state.candidates[0].worktree.clone(),
16424                timeout: Duration::from_secs(10),
16425                allow_write: false,
16426                sessions: false,
16427                artifacts: agent::artifacts_dir(&runner.state.dir()),
16428                stem: id.into(),
16429                handover: None,
16430            })
16431            .collect();
16432        let mut losses = Vec::new();
16433        let results = ask_wave_with(
16434            jobs.clone(),
16435            runner.sem.clone(),
16436            2,
16437            &[],
16438            &ctx,
16439            &mut losses,
16440            &mut runner.state,
16441            &|_: &str| Ok(()),
16442        )
16443        .await;
16444        assert!(
16445            results
16446                .iter()
16447                .all(|(seat, result, nudges)| seat.turns == 1 && result.is_err() && *nudges == 0)
16448        );
16449        assert_eq!(runner.state.quota.len(), 2);
16450        assert!(
16451            runner
16452                .state
16453                .quota
16454                .iter()
16455                .all(|q| q.cause == agent::QuotaCause::Authentication && !q.agent.is_empty())
16456        );
16457        assert!(!runner.state.advise_attempted);
16458        runner.stop_for_resource().unwrap();
16459        assert_eq!(runner.state.status, RunStatus::Blocked);
16460        assert_eq!(runner.state.resource_block.as_ref().unwrap().node, "advise");
16461        assert_eq!(
16462            runner.state.resource_block.as_ref().unwrap().kind,
16463            "agent authentication"
16464        );
16465        // A machine loss followed by an ordinary failure is not evidence
16466        // that the whole node was unavailable, and must not earn a refund.
16467        runner.state.resource_block = None;
16468        runner.state.quota.clear();
16469        let mut mixed = jobs;
16470        mixed[1].spec.command = vec!["false".into()];
16471        let results = ask_wave_with(
16472            mixed,
16473            runner.sem.clone(),
16474            0,
16475            &[],
16476            &ctx,
16477            &mut losses,
16478            &mut runner.state,
16479            &|_: &str| Ok(()),
16480        )
16481        .await;
16482        assert!(results.iter().all(|(_, res, _)| res.is_err()));
16483        assert!(runner.state.resource_block.is_none());
16484        assert_eq!(losses.len(), 1);
16485    }
16486
16487    #[tokio::test]
16488    async fn unauthenticated_implementation_keeps_its_candidate_pending() {
16489        let tmp = tempfile::tempdir().unwrap();
16490        let mut runner = repository_runner(tmp.path(), None).await;
16491        let implementer = scripted("implement", AUTH_OUTAGE);
16492        runner.roles.implementers = vec![implementer.clone()];
16493        runner.state.config.agents = vec![implementer];
16494        runner.implement().await.unwrap();
16495        assert_eq!(runner.state.status, RunStatus::Blocked);
16496        assert_eq!(runner.state.quota.len(), 1);
16497        assert_eq!(
16498            runner.state.quota[0].cause,
16499            agent::QuotaCause::Authentication
16500        );
16501        let candidate = &runner.state.candidates[0];
16502        assert!(candidate.failed.is_none() && !candidate.empty && candidate.commits == 0);
16503        assert_eq!(runner.state.seats["impl-A"].turns, 1);
16504    }
16505
16506    #[tokio::test]
16507    #[cfg(unix)]
16508    async fn parked_implementer_persists_completed_work() {
16509        for registered in [false, true] {
16510            let tmp = tempfile::tempdir().unwrap();
16511            let mut runner = registered_runner(tmp.path()).await;
16512            if !registered {
16513                std::fs::remove_file(runner.state.repo.join(".git/updater.contract")).unwrap();
16514            }
16515            let marker = tmp.path().join("started");
16516            let release = tmp.path().join("release");
16517            let mut implementer = spec("implement");
16518            implementer.command = vec![
16519                "sh".into(),
16520                "-c".into(),
16521                format!(
16522                    "touch '{}'; while [ ! -f '{}' ]; do sleep 0.01; done; echo completed > completed; echo saved-result",
16523                    marker.display(),
16524                    release.display()
16525                ),
16526            ];
16527            runner.roles.implementers = vec![implementer.clone()];
16528            runner.state.config.agents = vec![implementer];
16529            let pause = runner.pause.clone();
16530            let (result, ()) = tokio::join!(runner.implement(), async {
16531                tokio::time::timeout(Duration::from_secs(10), async {
16532                    while !marker.exists() {
16533                        tokio::time::sleep(Duration::from_millis(10)).await;
16534                    }
16535                })
16536                .await
16537                .unwrap();
16538                pause.park();
16539                std::fs::write(&release, "go").unwrap();
16540            });
16541            result.unwrap();
16542            let candidate = &runner.state.candidates[0];
16543            assert!(candidate.commits > 0, "{candidate:?}");
16544            assert!(candidate.summary.contains("saved-result"));
16545            assert_eq!(candidate.files, 1);
16546            let before = candidate.commits;
16547            runner.implement().await.unwrap();
16548            assert_eq!(runner.state.candidates[0].commits, before);
16549        }
16550    }
16551
16552    #[tokio::test]
16553    #[cfg(unix)]
16554    async fn resource_blocked_recovery_retries_the_unstarted_fixer() {
16555        let tmp = tempfile::tempdir().unwrap();
16556        let mut runner = registered_runner(tmp.path()).await;
16557        let winner = runner.state.candidates[0].clone();
16558        let cache = tmp.path().join("cache");
16559        runner.state.config.verify.e2e = vec![format!("CARGO_TARGET_DIR={} true", cache.display())];
16560        runner.state.config.graph.timeout_resource_wait = 0;
16561        let owner = crate::cache::Owner::here("other", "e2e", "e2e", &cache, "abc");
16562        let crate::cache::AcquireOutcome::Acquired(held) =
16563            crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap()
16564        else {
16565            panic!("cache must be free")
16566        };
16567        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
16568            from_run: "earlier".into(),
16569            generation: 1,
16570            mode: crate::recovery::Mode::VerifyRepair,
16571            reasons: Vec::new(),
16572            reviewed_head: None,
16573            rounds: Vec::new(),
16574            open_findings: Vec::new(),
16575            evidence: None,
16576            criteria_inherited: true,
16577            repair: crate::recovery::Repair::NotStarted,
16578        });
16579        runner.recovery_repair(&winner).await.unwrap();
16580        assert!(matches!(
16581            runner.state.recovery.as_ref().unwrap().repair,
16582            crate::recovery::Repair::WaitingForRestore { .. }
16583        ));
16584        drop(held);
16585        runner.state.resource_block = None;
16586        runner.state.config.graph.timeout_resource_wait = 1;
16587        runner.recovery_repair(&winner).await.unwrap();
16588        assert!(matches!(
16589            runner.state.recovery.as_ref().unwrap().repair,
16590            crate::recovery::Repair::Done { .. }
16591        ));
16592        assert!(runner.state.seats.values().any(|seat| seat.turns > 0));
16593    }
16594
16595    #[tokio::test]
16596    #[cfg(unix)]
16597    async fn repository_blocked_graft_and_recovery_retry_after_deferred_restore() {
16598        use std::os::fd::AsRawFd as _;
16599        for graft in [false, true] {
16600            let tmp = tempfile::tempdir().unwrap();
16601            let mut runner = registered_runner(tmp.path()).await;
16602            runner.state.config.graph.timeout_resource_wait = 1;
16603            let winner = runner.state.candidates[0].clone();
16604            let marker = tmp.path().join("fixer-started");
16605            let mut fixer = spec("fixer");
16606            fixer.command = vec![
16607                "sh".into(),
16608                "-c".into(),
16609                format!("echo started >> '{}'; echo done", marker.display()),
16610            ];
16611            runner.roles.fixer = Some(vec![fixer]);
16612            if graft {
16613                let mut loser = winner.clone();
16614                loser.label = 'B';
16615                loser.index = 1;
16616                runner.state.candidates.push(loser);
16617                runner.state.config.graph.graft_runner_up = true;
16618                runner.state.tally = Some(Tally {
16619                    first_choice: BTreeMap::new(),
16620                    borda: BTreeMap::new(),
16621                    winner: winner.label,
16622                    rankings: 1,
16623                    unanimous_initial: true,
16624                    deliberated: false,
16625                    changed_votes: 0,
16626                    unanimous_final: true,
16627                    tie_break: None,
16628                    judges: 1,
16629                    present: 1,
16630                    quorum: 1,
16631                    met_quorum: true,
16632                    uncontested: None,
16633                });
16634                runner.state.judgements.push(crate::run::Judgement {
16635                    judge: 1,
16636                    seat: "judge-1".into(),
16637                    agent: "judge".into(),
16638                    ranking: vec![winner.label, 'B'],
16639                    reasons: BTreeMap::new(),
16640                    confidence: None,
16641                    strengths: BTreeMap::from([("B".into(), vec!["handles empty input".into()])]),
16642                    order: vec![0, 1],
16643                    failed: None,
16644                    duration_ms: 0,
16645                });
16646            } else {
16647                runner.state.recovery = Some(crate::recovery::RecoveryRecord {
16648                    from_run: "earlier".into(),
16649                    generation: 1,
16650                    mode: crate::recovery::Mode::VerifyRepair,
16651                    reasons: Vec::new(),
16652                    reviewed_head: None,
16653                    rounds: Vec::new(),
16654                    open_findings: Vec::new(),
16655                    evidence: None,
16656                    criteria_inherited: true,
16657                    repair: crate::recovery::Repair::NotStarted,
16658                });
16659            }
16660            let reader = crate::repo_lock::SeatLease::for_checkout(
16661                &winner.worktree,
16662                false,
16663                crate::config::test_coordination().as_ref(),
16664            )
16665            .await
16666            .unwrap();
16667            let pause = runner.pause.clone();
16668            let (result, ()) = tokio::join!(
16669                async {
16670                    if graft {
16671                        runner.graft().await
16672                    } else {
16673                        runner.recovery_repair(&winner).await
16674                    }
16675                },
16676                async {
16677                    tokio::time::sleep(Duration::from_millis(100)).await;
16678                    pause.park();
16679                }
16680            );
16681            result.unwrap();
16682            assert!(!marker.exists(), "a blocked seat must not spawn");
16683            // Exercise the persisted state, as a binary replacement/resume does.
16684            runner.state = RunState::load(&runner.state.id).unwrap();
16685            if graft {
16686                assert_eq!(
16687                    runner.state.graft.as_ref().unwrap().outcome,
16688                    GraftOutcome::WaitingForRestore
16689                );
16690            } else {
16691                assert!(matches!(
16692                    runner.state.recovery.as_ref().unwrap().repair,
16693                    crate::recovery::Repair::WaitingForRestore { .. }
16694                ));
16695            }
16696            drop(reader);
16697            runner.pause = Pause::new();
16698            runner.state.resource_block = None;
16699            // Deferred restoration must still respect an external lock owner.
16700            let external =
16701                std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16702            assert_eq!(
16703                unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16704                0
16705            );
16706            let leftover = winner.worktree.join("leftover");
16707            std::fs::write(&leftover, "earlier fallback edits").unwrap();
16708            let result = if graft {
16709                runner.graft().await
16710            } else {
16711                runner.recovery_repair(&winner).await
16712            };
16713            assert!(
16714                result
16715                    .unwrap_err()
16716                    .is::<crate::repo_lock::ResourceBlocked>()
16717            );
16718            assert!(leftover.exists());
16719            assert!(!marker.exists());
16720            drop(external);
16721            runner.state.resource_block = None;
16722            let result = if graft {
16723                runner.graft().await
16724            } else {
16725                runner.recovery_repair(&winner).await
16726            };
16727            result.unwrap();
16728            assert!(!leftover.exists(), "restore must precede retry");
16729            assert_eq!(std::fs::read_to_string(&marker).unwrap(), "started\n");
16730            if graft {
16731                assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
16732            } else {
16733                assert!(matches!(
16734                    runner.state.recovery.as_ref().unwrap().repair,
16735                    crate::recovery::Repair::Done { .. }
16736                ));
16737            }
16738        }
16739    }
16740
16741    #[tokio::test]
16742    #[cfg(unix)]
16743    async fn interrupted_graft_restore_waits_and_preserves_its_record() {
16744        use std::os::fd::AsRawFd as _;
16745        let tmp = tempfile::tempdir().unwrap();
16746        let mut runner = registered_runner(tmp.path()).await;
16747        runner.state.config.graph.timeout_resource_wait = 1;
16748        let winner = runner.state.candidates[0].clone();
16749        let pre = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16750        runner.state.tally = Some(Tally {
16751            first_choice: BTreeMap::new(),
16752            borda: BTreeMap::new(),
16753            winner: winner.label,
16754            rankings: 0,
16755            unanimous_initial: false,
16756            deliberated: false,
16757            changed_votes: 0,
16758            unanimous_final: false,
16759            tie_break: None,
16760            judges: 0,
16761            present: 0,
16762            quorum: 0,
16763            met_quorum: true,
16764            uncontested: Some("fixture".into()),
16765        });
16766        runner.state.graft = Some(GraftRecord {
16767            pre: pre.clone(),
16768            post: None,
16769            lines: None,
16770            limit: None,
16771            agent: None,
16772            outcome: GraftOutcome::Running,
16773            requested: Vec::new(),
16774            adoption: None,
16775            adoption_error: None,
16776        });
16777        std::fs::write(winner.worktree.join("README.md"), "unfinished graft\n").unwrap();
16778        git::commit_all(&winner.worktree, "unfinished graft")
16779            .await
16780            .unwrap();
16781        let unfinished = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16782        let leftover = winner.worktree.join("leftover");
16783        std::fs::write(&leftover, "untrusted edits").unwrap();
16784        let path = runner.state.repo.join(".git/updater.lock");
16785        let external = std::fs::File::create(&path).unwrap();
16786        assert_eq!(
16787            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16788            0
16789        );
16790        assert!(
16791            runner
16792                .graft()
16793                .await
16794                .unwrap_err()
16795                .is::<crate::repo_lock::ResourceBlocked>()
16796        );
16797        assert!(matches!(
16798            runner.state.graft.as_ref().unwrap().outcome,
16799            GraftOutcome::Running
16800        ));
16801        assert_eq!(
16802            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16803            unfinished
16804        );
16805        assert!(leftover.exists());
16806        drop(external);
16807        std::fs::remove_file(&path).unwrap();
16808        std::fs::create_dir(&path).unwrap();
16809        assert!(runner.graft().await.is_err());
16810        assert!(matches!(
16811            runner.state.graft.as_ref().unwrap().outcome,
16812            GraftOutcome::Running
16813        ));
16814        assert_eq!(
16815            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16816            unfinished
16817        );
16818        assert!(leftover.exists());
16819        std::fs::remove_dir(&path).unwrap();
16820        runner.graft().await.unwrap();
16821        assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
16822        assert_eq!(git::rev_parse(&winner.worktree, "HEAD").await.unwrap(), pre);
16823        assert!(!leftover.exists());
16824    }
16825
16826    #[tokio::test]
16827    #[cfg(unix)]
16828    async fn repository_contention_blocks_and_parks_without_poisoning_preparation() {
16829        use std::os::fd::AsRawFd as _;
16830        let tmp = tempfile::tempdir().unwrap();
16831        let mut runner = registered_runner(tmp.path()).await;
16832        runner.state.prep_complete = Some(false);
16833        runner.state.config.graph.timeout_resource_wait = 1;
16834        runner.state.save().unwrap();
16835        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16836        assert_eq!(
16837            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16838            0
16839        );
16840        runner.execute().await.unwrap();
16841        let disk = RunState::load(&runner.state.id).unwrap();
16842        assert!(disk.driver_exited);
16843        assert_eq!(disk.driver_pid, None);
16844        assert_eq!(runner.state.status, RunStatus::Blocked);
16845        assert_eq!(
16846            runner.state.resource_block.as_ref().unwrap().kind,
16847            "repository coordination"
16848        );
16849        assert!(runner.state.prep_failure.is_none());
16850        assert!(runner.state.seats.is_empty());
16851        runner.pause.park();
16852        // Include headroom for Git subprocesses under parallel test load;
16853        // the repository contention deadline itself remains one second.
16854        tokio::time::timeout(Duration::from_secs(10), runner.execute())
16855            .await
16856            .unwrap()
16857            .unwrap();
16858        assert!(runner.state.parked);
16859        assert!(runner.state.prep_failure.is_none());
16860        let disk = RunState::load(&runner.state.id).unwrap();
16861        assert!(disk.driver_exited);
16862        assert_eq!(disk.driver_pid, None);
16863    }
16864
16865    #[tokio::test]
16866    #[cfg(unix)]
16867    async fn dropping_execute_during_a_repository_wait_releases_the_driver() {
16868        use std::os::fd::AsRawFd as _;
16869        let tmp = tempfile::tempdir().unwrap();
16870        let mut runner = registered_runner(tmp.path()).await;
16871        runner.state.prep_complete = Some(false);
16872        runner.state.config.graph.timeout_resource_wait = 30;
16873        runner.state.save().unwrap();
16874        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16875        assert_eq!(
16876            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16877            0
16878        );
16879        assert!(
16880            tokio::time::timeout(Duration::from_millis(100), runner.execute())
16881                .await
16882                .is_err()
16883        );
16884        let disk = RunState::load(&runner.state.id).unwrap();
16885        assert!(disk.driver_exited);
16886        assert_eq!(disk.driver_pid, None);
16887        assert!(disk.status.resumable());
16888        assert!(runner.state.driver_exited);
16889        assert_eq!(runner.state.driver_pid, None);
16890        runner.state.save().unwrap();
16891        assert_eq!(RunState::load(&runner.state.id).unwrap().driver_pid, None);
16892    }
16893
16894    #[tokio::test]
16895    #[cfg(unix)]
16896    async fn gate_takes_cache_before_repository_so_an_editing_wave_can_finish() {
16897        let tmp = tempfile::tempdir().unwrap();
16898        let mut runner = registered_runner(tmp.path()).await;
16899        let winner = runner.state.candidates[0].clone();
16900        let cache = tmp.path().join("cache");
16901        let started = tmp.path().join("pre-gate-started");
16902        runner.state.config.verify.pre_gate = vec![format!("touch '{}'", started.display())];
16903        runner.state.config.verify.gate =
16904            vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
16905        let home = crate::run::home();
16906        let owner =
16907            crate::cache::Owner::here("editing-wave", "implement", "*", &winner.worktree, "HEAD");
16908        let guard = match crate::cache::try_acquire(&home, &cache, &owner).unwrap() {
16909            crate::cache::AcquireOutcome::Acquired(g) => g,
16910            crate::cache::AcquireOutcome::Busy(busy) => panic!("cache must be free: {busy:?}"),
16911        };
16912        let mut gate = Box::pin(runner.run_gate(&winner));
16913        assert!(
16914            tokio::time::timeout(Duration::from_millis(150), &mut gate)
16915                .await
16916                .is_err()
16917        );
16918        assert!(!started.exists(), "pre-gate must wait for the cache too");
16919        // Simulate the wave that already owns the cache entering invoke.
16920        // It must obtain the editor reservation and finish without waiting
16921        // for the gate that is queued behind its cache.
16922        let wait = crate::repo_lock::WaitPolicy::new(Duration::from_millis(200), || false);
16923        let editor = crate::repo_lock::SeatLease::checkout_with(
16924            &winner.worktree,
16925            true,
16926            crate::config::test_coordination().as_ref(),
16927            &wait,
16928        )
16929        .await
16930        .unwrap();
16931        drop(editor);
16932        guard.release();
16933        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
16934            .await
16935            .unwrap()
16936            .unwrap();
16937        drop(gate);
16938        assert!(outcomes.iter().all(CommandOutcome::ok));
16939        assert!(started.exists());
16940    }
16941
16942    #[tokio::test]
16943    #[cfg(unix)]
16944    async fn post_seat_rescue_and_gate_wait_for_shared_lock() {
16945        use std::os::fd::AsRawFd as _;
16946
16947        ask_test_home();
16948        let tmp = tempfile::tempdir().unwrap();
16949        let repo = tmp.path().join("repo");
16950        std::fs::create_dir_all(&repo).unwrap();
16951        init_repo(&repo);
16952        let common = repo.join(".git");
16953        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
16954        let mut runner = runner_at(RunStatus::Prep);
16955        runner.state.repo = repo.clone();
16956        runner.state.config.coordination = crate::config::test_coordination();
16957        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16958        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16959        runner.state.config.graph.advise = false;
16960        runner.roles.implementers = vec![spec("implement")];
16961        runner.roles.judges = vec![spec("judge")];
16962        runner.prep().await.unwrap();
16963        let winner = runner.state.candidates[0].clone();
16964        // Emulate edits already left by a completed seat. The fixture CLI
16965        // only reports completion; it performs no repository operations.
16966        std::fs::write(winner.worktree.join("leftover"), "seat work\n").unwrap();
16967        let completed = tmp.path().join("seat-completed");
16968        runner.roles.implementers[0].command = vec![
16969            "sh".into(),
16970            "-c".into(),
16971            format!("touch '{}'; echo completed", completed.display()),
16972        ];
16973        let outsider = std::fs::File::create(common.join("updater.lock")).unwrap();
16974        assert_eq!(
16975            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16976            0
16977        );
16978        let before = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16979        let mut implement = Box::pin(runner.implement());
16980        tokio::select! {
16981            result = &mut implement => panic!("rescue must wait: {result:?}"),
16982            result = tokio::time::timeout(Duration::from_secs(10), async {
16983                while !completed.exists() {
16984                    tokio::time::sleep(Duration::from_millis(20)).await;
16985                }
16986            }) => result.unwrap(),
16987        }
16988        assert!(
16989            tokio::time::timeout(Duration::from_millis(200), &mut implement)
16990                .await
16991                .is_err()
16992        );
16993        assert_eq!(
16994            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16995            before
16996        );
16997        assert_eq!(
16998            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
16999            0
17000        );
17001        tokio::time::timeout(Duration::from_secs(10), &mut implement)
17002            .await
17003            .unwrap()
17004            .unwrap();
17005        drop(implement);
17006        assert_ne!(
17007            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
17008            before
17009        );
17010        assert!(git::is_clean(&winner.worktree).await.unwrap());
17011
17012        let started = tmp.path().join("pre-gate-started");
17013        let proceed = tmp.path().join("pre-gate-proceed");
17014        let checked = tmp.path().join("gate-ran");
17015        runner.state.config.verify.pre_gate = vec![format!(
17016            "echo mechanical >> README.md; touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
17017            started.display(),
17018            proceed.display()
17019        )];
17020        runner.state.config.verify.gate = vec![format!("touch '{}'", checked.display())];
17021        assert_eq!(
17022            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17023            0
17024        );
17025        let mut gate = Box::pin(runner.run_gate(&winner));
17026        assert!(
17027            tokio::time::timeout(Duration::from_millis(200), &mut gate)
17028                .await
17029                .is_err()
17030        );
17031        assert!(!started.exists());
17032        assert!(!checked.exists());
17033        assert!(git::is_clean(&winner.worktree).await.unwrap());
17034        assert_eq!(
17035            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
17036            0
17037        );
17038        tokio::select! {
17039            result = &mut gate => panic!("pre-gate must wait for signal: {result:?}"),
17040            result = tokio::time::timeout(Duration::from_secs(10), async {
17041                while !started.exists() {
17042                    tokio::time::sleep(Duration::from_millis(20)).await;
17043                }
17044            }) => result.unwrap(),
17045        }
17046        assert_eq!(
17047            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17048            -1,
17049            "mechanical edits must hold the real lock"
17050        );
17051        std::fs::write(proceed, "ready").unwrap();
17052        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
17053            .await
17054            .unwrap()
17055            .unwrap();
17056        drop(gate);
17057        assert!(outcomes.iter().all(CommandOutcome::ok));
17058        assert!(checked.exists());
17059        assert!(runner.state.pre_gate_commit.is_some());
17060        assert!(git::is_clean(&winner.worktree).await.unwrap());
17061        assert_eq!(
17062            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17063            0,
17064            "gate completion must release coordination"
17065        );
17066        drop(outsider);
17067        std::fs::remove_file(common.join("updater.lock")).unwrap();
17068        std::fs::create_dir(common.join("updater.lock")).unwrap();
17069        std::fs::remove_file(&started).unwrap();
17070        std::fs::remove_file(&checked).unwrap();
17071        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
17072        let error = runner.run_gate(&winner).await.unwrap_err();
17073        assert!(
17074            error
17075                .to_string()
17076                .contains("acquire mandatory repository lock")
17077        );
17078        assert!(
17079            !started.exists(),
17080            "failed acquisition must prevent pre-gate"
17081        );
17082        assert!(!checked.exists(), "failed acquisition must prevent gate");
17083        assert!(git::is_clean(&winner.worktree).await.unwrap());
17084        assert_eq!(
17085            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
17086            head
17087        );
17088    }
17089
17090    #[tokio::test]
17091    #[cfg(unix)]
17092    async fn preparation_waits_for_shared_lock_before_checkout_and_holds_it_through_setup() {
17093        use std::os::fd::AsRawFd as _;
17094        use std::time::Duration;
17095
17096        ask_test_home();
17097        let tmp = tempfile::tempdir().unwrap();
17098        let repo = tmp.path().join("repo");
17099        std::fs::create_dir_all(&repo).unwrap();
17100        init_repo(&repo);
17101        let common = repo.join(".git");
17102        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
17103        let lock = std::fs::File::create(common.join("updater.lock")).unwrap();
17104        assert_eq!(
17105            unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17106            0
17107        );
17108        let mut runner = runner_at(RunStatus::Prep);
17109        runner.state.repo = repo.clone();
17110        runner.state.config.coordination = crate::config::test_coordination();
17111        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17112        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17113        runner.state.config.graph.advise = true;
17114        runner.state.config.graph.advisors = 1;
17115        runner.roles.implementers = vec![spec("implement")];
17116        runner.roles.judges = vec![spec("judge")];
17117        let root = runner.state.worktree_root();
17118        let started = tmp.path().join("setup-started");
17119        let proceed = tmp.path().join("setup-proceed");
17120        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
17121            run: Some(format!(
17122                "touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
17123                started.display(),
17124                proceed.display()
17125            )),
17126            ..Default::default()
17127        }];
17128        let branches = git::git(&repo, &["branch", "--list"]).await.unwrap();
17129        let config = git::git(&repo, &["config", "--local", "--list"])
17130            .await
17131            .unwrap();
17132        let mut prep = Box::pin(runner.prep());
17133        assert!(
17134            tokio::time::timeout(Duration::from_millis(200), &mut prep)
17135                .await
17136                .is_err()
17137        );
17138        assert!(
17139            !root.exists(),
17140            "contention must prevent even checkout creation"
17141        );
17142        assert!(!started.exists(), "contention must prevent setup");
17143        assert_eq!(
17144            git::git(&repo, &["branch", "--list"]).await.unwrap(),
17145            branches
17146        );
17147        assert_eq!(
17148            git::git(&repo, &["config", "--local", "--list"])
17149                .await
17150                .unwrap(),
17151            config
17152        );
17153        drop(lock);
17154        tokio::select! {
17155            result = &mut prep => panic!("setup must wait for its signal: {result:?}"),
17156            result = tokio::time::timeout(Duration::from_secs(10), async {
17157                while !started.exists() {
17158                    tokio::time::sleep(Duration::from_millis(20)).await;
17159                }
17160            }) => result.unwrap(),
17161        }
17162        let outsider = std::fs::File::open(common.join("updater.lock")).unwrap();
17163        assert_eq!(
17164            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17165            -1
17166        );
17167        assert!(
17168            tokio::time::timeout(
17169                Duration::from_millis(100),
17170                crate::repo_lock::SeatLease::for_checkout(
17171                    &repo,
17172                    true,
17173                    crate::config::test_coordination().as_ref()
17174                )
17175            )
17176            .await
17177            .is_err(),
17178            "preparation must also exclude local editors"
17179        );
17180        std::fs::write(proceed, "ready").unwrap();
17181        tokio::time::timeout(Duration::from_secs(10), &mut prep)
17182            .await
17183            .unwrap()
17184            .unwrap();
17185        drop(prep);
17186        assert_eq!(runner.state.prep_complete, Some(true));
17187        assert!(root.join("judge-1").exists());
17188        assert!(root.join("advisor-1").exists());
17189        assert_eq!(
17190            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
17191            0
17192        );
17193    }
17194
17195    #[tokio::test]
17196    #[cfg(unix)]
17197    async fn preparation_lock_failure_prevents_repository_changes() {
17198        ask_test_home();
17199        let tmp = tempfile::tempdir().unwrap();
17200        let repo = tmp.path().join("repo");
17201        std::fs::create_dir_all(&repo).unwrap();
17202        init_repo(&repo);
17203        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
17204        // A directory at the required lock path makes opening the real lock
17205        // fail, rather than merely exercising an invalid registration.
17206        std::fs::create_dir(repo.join(".git/updater.lock")).unwrap();
17207        let mut runner = runner_at(RunStatus::Prep);
17208        runner.state.repo = repo.clone();
17209        runner.state.config.coordination = crate::config::test_coordination();
17210        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17211        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17212        runner.roles.implementers = vec![spec("implement")];
17213        let error = runner.prep().await.unwrap_err();
17214        assert!(
17215            error
17216                .to_string()
17217                .contains("acquire mandatory repository lock")
17218        );
17219        assert!(!runner.state.worktree_root().exists());
17220        assert!(runner.state.candidates.is_empty());
17221        assert!(!repo.join(".git/config.worktree").exists());
17222        assert_eq!(
17223            git::git(&repo, &["branch", "--list"]).await.unwrap().trim(),
17224            "* main"
17225        );
17226    }
17227
17228    #[tokio::test]
17229    async fn preparation_records_creation_intent_before_git_can_fail() {
17230        ask_test_home();
17231        let tmp = tempfile::tempdir().unwrap();
17232        let repo = tmp.path().join("repo");
17233        std::fs::create_dir_all(&repo).unwrap();
17234        init_repo(&repo);
17235        let mut runner = runner_at(RunStatus::Prep);
17236        runner.state.repo = repo.clone();
17237        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17238        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17239        runner.state.config.blind.commit_msg_hook = false;
17240        runner.roles.implementers = vec![spec("one")];
17241        let label = blind::assign_labels(1, runner.state.seed)[0];
17242        let branch = runner.state.branch_for(label);
17243        // A conflicting branch makes Git refuse creation before a candidate
17244        // can be registered. The durable intent must still identify it.
17245        git::git(&repo, &["branch", &branch]).await.unwrap();
17246        assert!(runner.prep().await.is_err());
17247        let saved = RunState::load(&runner.state.id).unwrap();
17248        assert!(saved.candidates.is_empty());
17249        let event = saved
17250            .events
17251            .iter()
17252            .find(|e| e.node == "prep-intent")
17253            .unwrap();
17254        let intent: serde_json::Value = serde_json::from_str(&event.message).unwrap();
17255        assert_eq!(intent["branch"], branch);
17256        assert_eq!(intent["start"], runner.state.base_commit);
17257        assert_eq!(
17258            intent["worktree"],
17259            runner
17260                .state
17261                .worktree_root()
17262                .join(format!("cand-{label}"))
17263                .to_string_lossy()
17264                .as_ref()
17265        );
17266        assert_eq!(intent["picks"], serde_json::json!([]));
17267    }
17268
17269    #[tokio::test]
17270    async fn invalid_pinned_sources_create_no_partial_worktrees() {
17271        ask_test_home();
17272        let tmp = tempfile::tempdir().unwrap();
17273        let repo = tmp.path().join("repo");
17274        std::fs::create_dir_all(&repo).unwrap();
17275        init_repo(&repo);
17276        let mut runner = runner_at(RunStatus::Prep);
17277        runner.state.repo = repo.clone();
17278        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17279        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
17280        runner.state.sources.pick_commits.push(refs::Input {
17281            token: "missing".into(),
17282            sha: "0".repeat(40),
17283            provenance: refs::Provenance::ExplicitCli,
17284        });
17285        assert!(runner.prep().await.is_err());
17286        assert!(runner.state.candidates.is_empty());
17287        assert!(!runner.state.worktree_root().exists());
17288    }
17289
17290    #[tokio::test]
17291    async fn prose_and_legacy_inference_never_import_into_candidates() {
17292        ask_test_home();
17293        let tmp = tempfile::tempdir().unwrap();
17294        let repo = tmp.path().join("repo");
17295        std::fs::create_dir_all(&repo).unwrap();
17296        init_repo(&repo);
17297        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
17298        git::git(&repo, &["checkout", "-b", "magi/history/A"])
17299            .await
17300            .unwrap();
17301        std::fs::write(repo.join("unwanted"), "do not import").unwrap();
17302        git::git(&repo, &["add", "."]).await.unwrap();
17303        git::git(&repo, &["commit", "-m", "historical implementation"])
17304            .await
17305            .unwrap();
17306        let source = git::rev_parse(&repo, "HEAD").await.unwrap();
17307        git::git(&repo, &["checkout", "main"]).await.unwrap();
17308        for instruction in [
17309            format!("Example: magi/history/A at {source}"),
17310            format!("Quoted failure: cannot apply referenced commit {source} from magi/history/A"),
17311            format!("Never import magi/history/A or {source}"),
17312            format!("Conversation answer: I mentioned {source} only as background"),
17313        ] {
17314            let mut runner = runner_at(RunStatus::Prep);
17315            runner.state.repo = repo.clone();
17316            runner.state.base_commit = base.clone();
17317            runner.state.instruction = instruction.clone();
17318            runner.state.config.graph.worktree_root = Some(tmp.path().join(&runner.state.id));
17319            runner.state.config.blind.commit_msg_hook = false;
17320            runner.state.seeds = vec![refs::Seed {
17321                token: "magi/history/A".into(),
17322                sha: source.clone(),
17323                kind: refs::SeedKind::Unmerged,
17324                branch: true,
17325                detail: String::new(),
17326            }];
17327            runner.roles.implementers = vec![spec("one")];
17328            assert_eq!(seeded_instruction(&runner.state), instruction);
17329            // Model an old record with inferred seeds but no structured input field.
17330            let mut legacy = serde_json::to_value(&runner.state).unwrap();
17331            legacy.as_object_mut().unwrap().remove("sources");
17332            runner.state = serde_json::from_value(legacy).unwrap();
17333            assert_eq!(runner.state.sources, refs::Sources::default());
17334            runner.state.save().unwrap();
17335            runner.state = RunState::load(&runner.state.id).unwrap();
17336            runner.prep().await.unwrap();
17337            for candidate in &runner.state.candidates {
17338                assert_eq!(
17339                    git::rev_parse(&candidate.worktree, "HEAD").await.unwrap(),
17340                    base
17341                );
17342                assert!(!candidate.worktree.join("unwanted").exists());
17343            }
17344        }
17345    }
17346
17347    #[tokio::test]
17348    async fn preparation_retries_after_explicit_release_and_rebuilds_partial_candidates() {
17349        ask_test_home();
17350        let tmp = tempfile::tempdir().unwrap();
17351        let repo = tmp.path().join("repo");
17352        std::fs::create_dir_all(&repo).unwrap();
17353        init_repo(&repo);
17354        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
17355        git::git(&repo, &["checkout", "-b", "seed"]).await.unwrap();
17356        std::fs::write(repo.join("referenced"), "required commit").unwrap();
17357        git::git(&repo, &["add", "."]).await.unwrap();
17358        git::git(&repo, &["commit", "-m", "required seed"])
17359            .await
17360            .unwrap();
17361        let seed = git::rev_parse(&repo, "HEAD").await.unwrap();
17362        git::git(&repo, &["checkout", "main"]).await.unwrap();
17363        let mut runner = runner_at(RunStatus::Prep);
17364        runner.state.repo = repo.clone();
17365        runner.state.base_commit = base.clone();
17366        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17367        runner.state.config.graph.advise = false;
17368        runner.state.config.blind.commit_msg_hook = false;
17369        runner.state.sources =
17370            refs::Sources::resolve(&repo, "origin", None, std::slice::from_ref(&seed))
17371                .await
17372                .unwrap();
17373        runner.roles.implementers = vec![spec("one"), spec("two")];
17374        runner.roles.judges = vec![spec("judge")];
17375        let label = blind::assign_labels(2, runner.state.seed)[0];
17376        let branch = runner.state.branch_for(label);
17377        let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
17378        git::worktree_add_branch(&repo, &worktree, &branch, &base)
17379            .await
17380            .unwrap();
17381        runner.state.candidates.push(Candidate {
17382            index: 0,
17383            label,
17384            agent: "one".into(),
17385            branch,
17386            worktree,
17387            summary: String::new(),
17388            stat: String::new(),
17389            files: 0,
17390            commits: 0,
17391            empty: false,
17392            failed: None,
17393            verified_noop: None,
17394            duration_ms: 0,
17395            folded: false,
17396        });
17397        runner.state.save().unwrap();
17398        // Reload the checkpoint immediately before its first cherry-pick.
17399        runner.state = RunState::load(&runner.state.id).unwrap();
17400        assert_eq!(runner.state.prep_complete, Some(false));
17401        runner.prep().await.unwrap();
17402        assert_eq!(runner.state.prep_complete, Some(true));
17403        assert_eq!(runner.state.candidates.len(), 2);
17404        for candidate in &runner.state.candidates {
17405            assert_eq!(
17406                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
17407                git::tree_of(&repo, &seed).await.unwrap()
17408            );
17409            assert_eq!(
17410                std::fs::read_to_string(candidate.worktree.join("referenced")).unwrap(),
17411                "required commit"
17412            );
17413        }
17414        assert!(runner.state.worktree_root().join("judge-1").exists());
17415        let heads: Vec<String> = candidate_heads(&runner.state.candidates).await;
17416        runner.prep().await.unwrap();
17417        assert_eq!(candidate_heads(&runner.state.candidates).await, heads);
17418
17419        runner.state.prep_complete = Some(false);
17420        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
17421            run: Some(format!(
17422                "test -f '{}'",
17423                tmp.path().join("dependency-ready").display()
17424            )),
17425            ..Default::default()
17426        }];
17427        assert!(runner.prep().await.is_err());
17428        assert!(runner.state.prep_failure.is_some());
17429        std::fs::write(tmp.path().join("dependency-ready"), "available").unwrap();
17430        runner.state = RunState::load(&runner.state.id).unwrap();
17431        assert!(
17432            runner.prep().await.is_err(),
17433            "correcting the cause alone must not auto-retry"
17434        );
17435        let failed_at = runner.state.events.last().unwrap().at;
17436        assert!(
17437            runner.retry_preparation(failed_at).is_err(),
17438            "old approvals cannot unlock the hold"
17439        );
17440        let mut task = crate::queue::Task::new(
17441            "retry".into(),
17442            "retry setup".into(),
17443            repo.clone(),
17444            crate::queue::Source::Human,
17445        );
17446        task.start(runner.state.id.clone());
17447        task.hold_machine(Some("setup failed".into()));
17448        task.release_operator("cli", None);
17449        runner
17450            .retry_preparation(task.resumption.as_ref().unwrap().at)
17451            .unwrap();
17452        runner.prep().await.unwrap();
17453        assert!(runner.state.prep_failure.is_none());
17454        assert_eq!(runner.state.prep_complete, Some(true));
17455        assert_eq!(runner.state.candidates.len(), 2);
17456        assert!(runner.state.worktree_root().join("judge-1").exists());
17457        for candidate in &runner.state.candidates {
17458            assert_eq!(
17459                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
17460                git::tree_of(&repo, &seed).await.unwrap()
17461            );
17462        }
17463    }
17464
17465    async fn candidate_heads(candidates: &[Candidate]) -> Vec<String> {
17466        let mut heads = Vec::new();
17467        for candidate in candidates {
17468            heads.push(git::rev_parse(&candidate.worktree, "HEAD").await.unwrap());
17469        }
17470        heads
17471    }
17472
17473    async fn preservation_resume_fixture() -> (tempfile::TempDir, Runner) {
17474        ask_test_home();
17475        let tmp = tempfile::tempdir().unwrap();
17476        let repo = tmp.path().join("repo");
17477        std::fs::create_dir(&repo).unwrap();
17478        init_repo(&repo);
17479        let mut runner = runner_at(RunStatus::Reviewing);
17480        runner.state.repo = repo.clone();
17481        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17482        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17483        for (index, label) in ['A', 'B'].into_iter().enumerate() {
17484            let branch = format!("candidate-{label}");
17485            let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
17486            git::worktree_add_branch(&repo, &worktree, &branch, "main")
17487                .await
17488                .unwrap();
17489            if label == 'B' {
17490                std::fs::write(worktree.join("change"), "winner").unwrap();
17491                git::rescue_commit(&worktree, "candidate change")
17492                    .await
17493                    .unwrap();
17494            }
17495            runner.state.candidates.push(Candidate {
17496                index,
17497                label,
17498                agent: "alpha".into(),
17499                branch,
17500                worktree,
17501                summary: "completed reply".into(),
17502                stat: String::new(),
17503                files: usize::from(label == 'B'),
17504                commits: usize::from(label == 'B'),
17505                empty: label == 'A',
17506                failed: None,
17507                verified_noop: None,
17508                duration_ms: 1,
17509                folded: false,
17510            });
17511        }
17512        runner.state.judge_skipped = true;
17513        runner.state.tally = Some(Tally {
17514            first_choice: BTreeMap::new(),
17515            borda: BTreeMap::new(),
17516            winner: 'B',
17517            rankings: 0,
17518            unanimous_initial: false,
17519            deliberated: false,
17520            changed_votes: 0,
17521            unanimous_final: false,
17522            tie_break: None,
17523            judges: 0,
17524            present: 0,
17525            quorum: 0,
17526            met_quorum: true,
17527            uncontested: Some("only B produced a change".into()),
17528        });
17529        runner.state.save().unwrap();
17530        (tmp, runner)
17531    }
17532
17533    #[tokio::test]
17534    async fn fold_losers_reclaims_isolated_outputs_without_a_pool_limit() {
17535        let (_tmp, mut runner) = preservation_resume_fixture().await;
17536        runner.state.config.verify.build_cache = crate::config::BuildCache::Isolated;
17537        runner.state.config.disk.cache_limit_bytes = 0;
17538        runner.state.config.graph.advise = true;
17539        runner.state.config.graph.advisors = 1;
17540        let advisor = runner.state.worktree_root().join("advisor-1");
17541        git::worktree_add_detached(&runner.state.repo, &advisor, "main")
17542            .await
17543            .unwrap();
17544        let home = crate::run::home();
17545        let loser =
17546            crate::build_target::resolve(&home, &runner.state.candidates[0].worktree).unwrap();
17547        let winner =
17548            crate::build_target::resolve(&home, &runner.state.candidates[1].worktree).unwrap();
17549        let advisor = crate::build_target::resolve(&home, &advisor).unwrap();
17550        for target in [&loser, &winner, &advisor] {
17551            std::fs::write(target.join("build-output"), "compiled").unwrap();
17552        }
17553
17554        runner.fold_losers().await.unwrap();
17555
17556        assert!(!loser.join("build-output").exists());
17557        assert!(!advisor.join("build-output").exists());
17558        assert!(winner.join("build-output").is_file());
17559    }
17560
17561    #[tokio::test]
17562    async fn fold_losers_persists_discard_before_later_teardown_failure() {
17563        let (_tmp, mut runner) = preservation_resume_fixture().await;
17564        runner.state.candidates[0].folded = true;
17565        runner.state.config.graph.advise = true;
17566        runner.state.config.graph.advisors = 2;
17567        let repo = runner.state.repo.clone();
17568        let root = runner.state.worktree_root();
17569        let discarded = root.join("advisor-1");
17570        git::worktree_add_detached(&repo, &discarded, "main")
17571            .await
17572            .unwrap();
17573        std::fs::write(discarded.join("design_proposal.json"), "{}").unwrap();
17574        let protected = root.join("advisor-2");
17575        git::worktree_add_branch(&repo, &protected, "attached-advisor", "main")
17576            .await
17577            .unwrap();
17578        std::fs::write(protected.join("keep"), "uncommitted").unwrap();
17579        runner.state.save().unwrap();
17580
17581        assert!(runner.fold_losers().await.is_err());
17582        assert!(!discarded.exists());
17583        assert!(protected.join("keep").exists());
17584        let saved = RunState::load(&runner.state.id).unwrap();
17585        assert!(saved.events.iter().any(|event| {
17586            event.message.contains("advisor-1") && event.message.contains("design_proposal.json")
17587        }));
17588    }
17589
17590    #[tokio::test]
17591    async fn read_seat_teardown_discards_only_owned_detached_seats() {
17592        let (tmp, mut runner) = preservation_resume_fixture().await;
17593        let repo = runner.state.repo.clone();
17594        let root = runner.state.worktree_root();
17595        for name in ["advisor-3", "judge-1", "review-2"] {
17596            let path = root.join(name);
17597            git::worktree_add_detached(&repo, &path, "main")
17598                .await
17599                .unwrap();
17600            std::fs::write(path.join("README.md"), "uncommitted edit").unwrap();
17601            std::fs::write(path.join("design_proposal.json"), "{}").unwrap();
17602            remove_read_seat_worktree(&mut runner.state, &path)
17603                .await
17604                .unwrap();
17605            assert!(!path.exists());
17606        }
17607        let outside = tmp.path().join("advisor-1");
17608        let unknown = root.join("unknown");
17609        let attached = root.join("advisor-4");
17610        git::worktree_add_detached(&repo, &outside, "main")
17611            .await
17612            .unwrap();
17613        git::worktree_add_detached(&repo, &unknown, "main")
17614            .await
17615            .unwrap();
17616        git::worktree_add_branch(&repo, &attached, "attached-advisor", "main")
17617            .await
17618            .unwrap();
17619        let foreign = tmp.path().join("foreign");
17620        std::fs::create_dir(&foreign).unwrap();
17621        init_repo(&foreign);
17622        let wrong_repo = root.join("judge-2");
17623        git::worktree_add_detached(&foreign, &wrong_repo, "main")
17624            .await
17625            .unwrap();
17626        let candidate = runner.state.candidates[0].worktree.clone();
17627        for path in [outside, unknown, attached, wrong_repo, candidate] {
17628            std::fs::write(path.join("uncommitted"), "keep").unwrap();
17629            assert!(
17630                remove_read_seat_worktree(&mut runner.state, &path)
17631                    .await
17632                    .is_err()
17633            );
17634            assert_eq!(
17635                std::fs::read_to_string(path.join("uncommitted")).unwrap(),
17636                "keep"
17637            );
17638        }
17639    }
17640
17641    #[tokio::test]
17642    #[cfg(unix)]
17643    async fn disk_interrupted_empty_implementation_retries_after_reload_and_failed_checkpoint() {
17644        for (solo, failed_checkpoint) in
17645            [(true, false), (false, false), (true, true), (false, true)]
17646        {
17647            let (_tmp, mut runner) = preservation_resume_fixture().await;
17648            if solo {
17649                runner.state.candidates.retain(|c| c.label == 'A');
17650            }
17651            runner.state.candidates[0].empty = false;
17652            runner.state.candidates[0].summary.clear();
17653            runner.state.tally = None;
17654            runner.state.judge_skipped = false;
17655            runner.state.status = RunStatus::Implementing;
17656            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
17657            let mut implementer = spec("alpha");
17658            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
17659            runner.roles.implementers = vec![implementer];
17660            let patch = runner.state.dir().join("artifacts/cand-A.patch");
17661            if failed_checkpoint {
17662                std::fs::create_dir_all(&patch).unwrap();
17663            }
17664            runner.state.save().unwrap();
17665            assert_eq!(runner.implement().await.is_err(), failed_checkpoint);
17666            drop(pressure);
17667            runner.state = RunState::load(&runner.state.id).unwrap();
17668            assert_eq!(runner.state.status, RunStatus::Blocked);
17669            assert!(runner.state.interrupted_implementations.contains(&'A'));
17670            assert_eq!(runner.state.candidates[0].commits, 0);
17671            assert!(!runner.state.candidates[0].empty);
17672            assert!(runner.state.candidates[0].failed.is_none());
17673            if failed_checkpoint {
17674                assert!(runner.state.candidate_preservation.contains_key(&'A'));
17675                std::fs::remove_dir(patch).unwrap();
17676            }
17677            runner.state.resource_block = None;
17678            runner.state.config.disk.min_free_bytes = 0;
17679            runner.roles.implementers[0].command = vec![
17680                "sh".into(),
17681                "-c".into(),
17682                "printf 'retried empty interrupted seat\\n' > retry-source; echo completed".into(),
17683            ];
17684            runner.implement().await.unwrap();
17685            assert!(runner.state.interrupted_implementations.is_empty());
17686            assert!(runner.state.candidate_preservation.is_empty());
17687            assert_eq!(runner.state.candidates[0].commits, 1);
17688            assert!(!runner.state.candidates[0].empty);
17689            assert!(
17690                std::fs::read_to_string(runner.state.candidates[0].worktree.join("retry-source"))
17691                    .unwrap()
17692                    .contains("retried empty interrupted seat")
17693            );
17694            if !solo {
17695                assert_eq!(runner.state.candidates[1].commits, 1);
17696            }
17697        }
17698    }
17699
17700    #[tokio::test]
17701    #[cfg(unix)]
17702    async fn disk_interrupted_implementation_preserves_edits_and_commits_before_resource_hold() {
17703        for (committed, block_rescue) in [(false, false), (false, true), (true, false)] {
17704            let (_tmp, mut runner) = preservation_resume_fixture().await;
17705            runner.state.candidates.retain(|c| c.label == 'A');
17706            runner.state.candidates[0].empty = false;
17707            runner.state.candidates[0].summary.clear();
17708            runner.state.tally = None;
17709            runner.state.judge_skipped = false;
17710            runner.state.status = RunStatus::Implementing;
17711            // Force only the real post-spawn watchdog, without failing the
17712            // separate admission check. Existing edits predate its measurement.
17713            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
17714            let wt = runner.state.candidates[0].worktree.clone();
17715            std::fs::write(
17716                wt.join("interrupted-source"),
17717                "retain implementation work\n",
17718            )
17719            .unwrap();
17720            if committed {
17721                git::rescue_commit(&wt, "implementation checkpoint")
17722                    .await
17723                    .unwrap();
17724            }
17725            let lock = git::git(
17726                &wt,
17727                &[
17728                    "rev-parse",
17729                    "--path-format=absolute",
17730                    "--git-path",
17731                    "index.lock",
17732                ],
17733            )
17734            .await
17735            .unwrap();
17736            if block_rescue {
17737                std::fs::write(&lock, "fixture-owned lock").unwrap();
17738            }
17739            let mut implementer = spec("alpha");
17740            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
17741            runner.roles.implementers = vec![implementer];
17742            runner.state.save().unwrap();
17743            let result = runner.implement().await;
17744            drop(pressure);
17745            assert_eq!(result.is_err(), block_rescue);
17746            assert_eq!(
17747                runner.state.resource_block.as_ref().unwrap().kind,
17748                "disk pressure"
17749            );
17750            assert!(
17751                runner
17752                    .state
17753                    .events
17754                    .iter()
17755                    .any(|e| e.message.contains("agent execution interrupted"))
17756            );
17757            assert!(
17758                runner
17759                    .state
17760                    .dir()
17761                    .join("artifacts/candidate-A-recovery/staged.patch")
17762                    .exists()
17763            );
17764            if block_rescue {
17765                let saved = RunState::load(&runner.state.id).unwrap();
17766                assert!(saved.candidate_preservation.contains_key(&'A'));
17767                assert!(!saved.candidates[0].empty);
17768                assert_eq!(
17769                    std::fs::read_to_string(wt.join("interrupted-source")).unwrap(),
17770                    "retain implementation work\n"
17771                );
17772                std::fs::remove_file(lock).unwrap();
17773                runner.state = saved;
17774            } else {
17775                assert_eq!(runner.state.status, RunStatus::Blocked);
17776                assert_eq!(runner.state.candidates[0].commits, 1);
17777            }
17778            // Recovery must save the candidate before deciding whether another
17779            // implementation is needed. No implementer is available on retry.
17780            runner.roles.implementers.clear();
17781            runner.state.config.disk.min_free_bytes = 0;
17782            runner.state.resource_block = None;
17783            runner.implement().await.unwrap();
17784            assert!(runner.state.candidate_preservation.is_empty());
17785            assert_eq!(runner.state.candidates[0].commits, 1);
17786            assert!(!runner.state.candidates[0].empty);
17787            assert!(git::is_clean(&wt).await.unwrap());
17788            assert!(
17789                crate::run::read_artifact(&runner.state, "cand-A.patch")
17790                    .unwrap()
17791                    .contains("retain implementation work")
17792            );
17793        }
17794    }
17795
17796    #[tokio::test]
17797    async fn candidate_preservation_does_not_reflag_confirmed_or_folded_empty_candidates() {
17798        let (_tmp, mut runner) = preservation_resume_fixture().await;
17799        // Schema 15 already confirmed the unfolded no-change result.
17800        runner.implement().await.unwrap();
17801        assert!(runner.state.candidate_preservation.is_empty());
17802        assert!(
17803            !runner
17804                .state
17805                .dir()
17806                .join("artifacts/candidate-A-recovery")
17807                .exists()
17808        );
17809        runner.fold_losers().await.unwrap();
17810        assert!(!runner.state.candidates[0].worktree.exists());
17811        for schema in [14, crate::run::SCHEMA] {
17812            runner.state.schema = schema;
17813            runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17814            runner.state.save().unwrap();
17815            runner.state = RunState::load(&runner.state.id).unwrap();
17816            runner.implement().await.unwrap();
17817            assert!(runner.state.candidate_preservation.is_empty());
17818            assert!(runner.state.candidates[0].folded);
17819            assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
17820        }
17821    }
17822
17823    #[tokio::test]
17824    async fn infrastructure_failure_report_retains_eligible_candidate_edits() {
17825        let (_tmp, mut runner) = preservation_resume_fixture().await;
17826        runner.state.candidates.retain(|c| c.label == 'A');
17827        runner.state.tally = None;
17828        runner.state.judge_skipped = false;
17829        let candidate = &mut runner.state.candidates[0];
17830        candidate.summary = "Reproduction bind denied with EPERM; source repair complete, deployed browser validation remains parent-owned.".into();
17831        candidate.failed = Some("deployment validation unavailable".into());
17832        std::fs::write(
17833            candidate.worktree.join("repair"),
17834            "future launcher policy\n",
17835        )
17836        .unwrap();
17837        runner
17838            .state
17839            .candidate_preservation
17840            .insert('A', "awaiting persistence".into());
17841        runner.persist_candidates().await.unwrap();
17842        let candidate = &runner.state.candidates[0];
17843        assert!(!candidate.empty);
17844        assert_eq!(candidate.commits, 1);
17845        assert_eq!(candidate.files, 1);
17846        assert!(candidate.failed.is_none());
17847        assert!(candidate.summary.contains("EPERM"));
17848        assert!(
17849            crate::run::read_artifact(&runner.state, "cand-A.patch")
17850                .unwrap()
17851                .contains("future launcher policy")
17852        );
17853        assert!(runner.state.candidate_preservation.is_empty());
17854    }
17855
17856    #[tokio::test]
17857    async fn candidate_preservation_legacy_recovery_blocks_stale_verdict_on_every_resume() {
17858        let (_tmp, mut runner) = preservation_resume_fixture().await;
17859        let wt = runner.state.candidates[0].worktree.clone();
17860        std::fs::write(wt.join("recovered"), "owned edits").unwrap();
17861        runner.state.schema = 14;
17862        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17863        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17864        let tally = serde_json::to_value(&runner.state.tally).unwrap();
17865        for _ in 0..2 {
17866            assert!(runner.implement().await.is_err());
17867            assert_eq!(runner.state.status, RunStatus::Blocked);
17868            assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
17869            assert!(
17870                runner.state.candidates[0].empty,
17871                "old verdict must remain unusable"
17872            );
17873            assert_eq!(serde_json::to_value(&runner.state.tally).unwrap(), tally);
17874            assert!(runner.state.judge_skipped);
17875            assert!(runner.state.judgements.is_empty() && runner.state.votes.is_empty());
17876            assert!(
17877                crate::run::read_artifact(&runner.state, "cand-A.patch")
17878                    .unwrap()
17879                    .contains("owned edits")
17880            );
17881            assert!(wt.exists());
17882            assert_eq!(
17883                git::commits_ahead(&wt, &runner.state.base_commit, "HEAD")
17884                    .await
17885                    .unwrap(),
17886                1
17887            );
17888            runner.state = RunState::load(&runner.state.id).unwrap();
17889        }
17890    }
17891
17892    #[tokio::test]
17893    async fn candidate_preservation_legacy_failed_seat_keeps_edits_before_judging() {
17894        let (_tmp, mut runner) = preservation_resume_fixture().await;
17895        let wt = runner.state.candidates[0].worktree.clone();
17896        runner.state.candidates[0].failed = Some("CLI failed before commit".into());
17897        std::fs::write(wt.join("recovered"), "failed seat edits").unwrap();
17898        let index_lock = PathBuf::from(
17899            git::git(
17900                &wt,
17901                &[
17902                    "rev-parse",
17903                    "--path-format=absolute",
17904                    "--git-path",
17905                    "index.lock",
17906                ],
17907            )
17908            .await
17909            .unwrap(),
17910        );
17911        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
17912        runner.state.schema = 14;
17913        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17914        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17915        assert!(runner.implement().await.is_err());
17916        assert!(runner.after_implement().is_err());
17917        assert!(runner.fold_losers().await.is_err());
17918        assert_eq!(
17919            std::fs::read_to_string(wt.join("recovered")).unwrap(),
17920            "failed seat edits"
17921        );
17922        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17923        runner.state = RunState::load(&runner.state.id).unwrap();
17924        std::fs::remove_file(index_lock).unwrap();
17925        // Recovery finds changes that the old uncontested result never judged.
17926        assert!(runner.implement().await.is_err());
17927        assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
17928        assert!(runner.state.candidates[0].empty);
17929        assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
17930        assert!(
17931            crate::run::read_artifact(&runner.state, "cand-A.patch")
17932                .unwrap()
17933                .contains("failed seat edits")
17934        );
17935        assert!(wt.exists());
17936    }
17937
17938    #[tokio::test]
17939    async fn candidate_preservation_loser_cleanup_resumes_after_branch_and_judge_failures() {
17940        let (_tmp, mut runner) = preservation_resume_fixture().await;
17941        let repo = runner.state.repo.clone();
17942        let common = git::git(
17943            &repo,
17944            &["rev-parse", "--path-format=absolute", "--git-common-dir"],
17945        )
17946        .await
17947        .unwrap();
17948        let branch_lock = PathBuf::from(common).join("refs/heads/candidate-A.lock");
17949        std::fs::write(&branch_lock, "fixture-owned lock").unwrap();
17950        assert!(runner.fold_losers().await.is_err());
17951        assert!(!runner.state.candidates[0].worktree.exists());
17952        assert!(!runner.state.candidates[0].folded);
17953        assert!(git::branch_exists(&repo, "candidate-A").await.unwrap());
17954        runner.state = RunState::load(&runner.state.id).unwrap();
17955        std::fs::remove_file(branch_lock).unwrap();
17956        let judge = runner.state.worktree_root().join("judge-1");
17957        git::worktree_add_detached(&repo, &judge, "main")
17958            .await
17959            .unwrap();
17960        std::fs::write(judge.join("uncommitted"), "retain").unwrap();
17961        git::git(&repo, &["worktree", "lock", &git::path_arg(&judge)])
17962            .await
17963            .unwrap();
17964        runner.roles.judges = vec![spec("judge")];
17965        assert!(runner.fold_losers().await.is_err());
17966        runner.state = RunState::load(&runner.state.id).unwrap();
17967        assert!(
17968            runner.state.candidates[0].folded,
17969            "candidate progress saved before judge failure"
17970        );
17971        assert!(!git::branch_exists(&repo, "candidate-A").await.unwrap());
17972        assert!(judge.join("uncommitted").exists());
17973        git::git(&repo, &["worktree", "unlock", &git::path_arg(&judge)])
17974            .await
17975            .unwrap();
17976        runner.fold_losers().await.unwrap();
17977        assert!(!judge.exists());
17978        runner.fold_losers().await.unwrap();
17979    }
17980
17981    #[tokio::test]
17982    async fn candidate_preservation_selected_implementer_resumes_through_execute_graph() {
17983        let (_tmp, mut runner) = preservation_resume_fixture().await;
17984        runner.state.candidates.retain(|c| c.label == 'B');
17985        runner.state.tally = None;
17986        runner.state.judge_skipped = false;
17987        runner.state.prep_complete = Some(true);
17988        runner.state.config.graph.advise = false;
17989        runner.state.config.graph.selected_implementer = Some("alpha".into());
17990        let wt = runner.state.candidates[0].worktree.clone();
17991        std::fs::write(wt.join("leftover"), "completed implementation").unwrap();
17992        runner
17993            .state
17994            .candidate_preservation
17995            .insert('B', "awaiting persistence".into());
17996        let index_lock = git::git(
17997            &wt,
17998            &[
17999                "rev-parse",
18000                "--path-format=absolute",
18001                "--git-path",
18002                "index.lock",
18003            ],
18004        )
18005        .await
18006        .unwrap();
18007        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
18008        runner.state.save().unwrap();
18009        assert!(runner.execute_graph().await.is_err());
18010        assert_eq!(runner.state.status, RunStatus::Blocked);
18011        assert!(runner.state.candidate_preservation.contains_key(&'B'));
18012        std::fs::remove_file(index_lock).unwrap();
18013        // Park at the next graph boundary: this tests the real selected-seat
18014        // hold guard without dispatching reviewers or publishing anything.
18015        for _ in 0..2 {
18016            runner.state = RunState::load(&runner.state.id).unwrap();
18017            runner.pause.park();
18018            runner.execute_graph().await.unwrap();
18019            assert_eq!(runner.state.status, RunStatus::Implementing);
18020            assert!(runner.state.candidate_preservation.is_empty());
18021            assert_eq!(runner.state.candidates[0].commits, 2);
18022            assert!(runner.state.tally.is_none());
18023        }
18024        runner.implement().await.unwrap();
18025        assert_eq!(runner.state.status, RunStatus::Judging);
18026        // A genuine selected-implementer hold must still require release.
18027        runner.state.status = RunStatus::Blocked;
18028        runner.state.candidates[0].failed = Some("implementation failed".into());
18029        runner.state.save().unwrap();
18030        let error = runner.execute_graph().await.unwrap_err();
18031        assert!(
18032            error
18033                .to_string()
18034                .contains("selected implementation is held")
18035        );
18036    }
18037
18038    #[tokio::test]
18039    async fn candidate_preservation_cleanup_unregisters_a_vanished_worktree() {
18040        let (_tmp, mut runner) = preservation_resume_fixture().await;
18041        let repo = runner.state.repo.clone();
18042        let candidate = runner.state.candidates[0].clone();
18043        // Remove only the disposable fixture directory, leaving Git's linked
18044        // worktree registration and branch intact, as in a vanished checkout.
18045        let registered = git::worktree_holding(&repo, &candidate.branch)
18046            .await
18047            .unwrap()
18048            .unwrap();
18049        assert_eq!(
18050            registered.canonicalize().unwrap(),
18051            candidate.worktree.canonicalize().unwrap()
18052        );
18053        std::fs::remove_dir_all(&candidate.worktree).unwrap();
18054        assert_eq!(
18055            git::worktree_holding(&repo, &candidate.branch)
18056                .await
18057                .unwrap(),
18058            Some(registered)
18059        );
18060        assert!(
18061            !git::branch_delete(&repo, &candidate.branch).await.unwrap(),
18062            "the stale registration initially keeps the branch checked out"
18063        );
18064        runner.fold_losers().await.unwrap();
18065        assert!(runner.state.candidates[0].folded);
18066        assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
18067        assert_eq!(
18068            git::worktree_holding(&repo, &candidate.branch)
18069                .await
18070                .unwrap(),
18071            None
18072        );
18073        runner.state = RunState::load(&runner.state.id).unwrap();
18074        runner.fold_losers().await.unwrap();
18075    }
18076
18077    #[tokio::test]
18078    async fn fold_run_unregisters_a_vanished_worktree_and_can_retry() {
18079        let (_tmp, mut runner) = preservation_resume_fixture().await;
18080        let repo = runner.state.repo.clone();
18081        let candidate = runner.state.candidates[0].clone();
18082        let winner = runner.state.candidates[1].clone();
18083        let registered = git::worktree_holding(&repo, &candidate.branch)
18084            .await
18085            .unwrap()
18086            .unwrap();
18087        assert_eq!(
18088            registered.canonicalize().unwrap(),
18089            candidate.worktree.canonicalize().unwrap()
18090        );
18091        std::fs::remove_dir_all(&candidate.worktree).unwrap();
18092        assert_eq!(
18093            git::worktree_holding(&repo, &candidate.branch)
18094                .await
18095                .unwrap(),
18096            Some(registered)
18097        );
18098        assert!(!git::branch_delete(&repo, &candidate.branch).await.unwrap());
18099
18100        for _ in 0..2 {
18101            fold_run(&mut runner.state, false, &crate::run::home())
18102                .await
18103                .unwrap();
18104            runner.state = RunState::load(&runner.state.id).unwrap();
18105            assert!(runner.state.candidates[0].folded);
18106            assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
18107            assert_eq!(
18108                git::worktree_holding(&repo, &candidate.branch)
18109                    .await
18110                    .unwrap(),
18111                None
18112            );
18113            assert!(!runner.state.candidates[1].folded);
18114            assert!(winner.worktree.exists());
18115            assert!(git::branch_exists(&repo, &winner.branch).await.unwrap());
18116        }
18117    }
18118
18119    /// The recovery-retention override, refused for the rule under test. The
18120    /// arrangement is saved in `home` before each call, so `record gone` or
18121    /// `unreadable` would be the fixture's mistake and fails here.
18122    async fn override_refusal(state: &mut RunState, home: &Path) -> anyhow::Error {
18123        let error = fold_run_overriding_recovery_retention(state, true, home)
18124            .await
18125            .expect_err("the override is refused");
18126        assert!(
18127            !matches!(
18128                error.downcast_ref::<FoldRefusal>(),
18129                Some(FoldRefusal::RecordGone | FoldRefusal::Unreadable(_))
18130            ),
18131            "refused for the wrong reason: {error:#}"
18132        );
18133        error
18134    }
18135
18136    #[tokio::test]
18137    async fn fold_recovery_override_archives_sources_and_keeps_safety_checks() {
18138        for sidecar in [false, true] {
18139            let tmp = tempfile::tempdir().unwrap();
18140            let home = tmp.path().join("home");
18141            let repo = tmp.path().join("repo");
18142            std::fs::create_dir(&repo).unwrap();
18143            init_repo(&repo);
18144            let mut state = runner_at(RunStatus::Superseded).state;
18145            state.repo = repo.clone();
18146            state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
18147            state.config.graph.worktree_root = Some(tmp.path().join("wt"));
18148            state.driver_exited = true;
18149            state.reserve_under(&home).unwrap();
18150            git::git(
18151                &repo,
18152                &["update-ref", "refs/remotes/origin/main", &state.base_commit],
18153            )
18154            .await
18155            .unwrap();
18156            let wt = state.worktree_root().join("cand-A");
18157            git::worktree_add_branch(&repo, &wt, "candidate", "main")
18158                .await
18159                .unwrap();
18160            std::fs::write(wt.join("independent"), "retained implementation\n").unwrap();
18161            git::commit_all(&wt, "fixture: independent source")
18162                .await
18163                .unwrap();
18164            let head = git::rev_parse(&wt, "HEAD").await.unwrap();
18165            state.candidates.push(Candidate {
18166                index: 0,
18167                label: 'A',
18168                agent: "fixture".into(),
18169                branch: "candidate".into(),
18170                worktree: wt.clone(),
18171                summary: String::new(),
18172                stat: String::new(),
18173                files: 0,
18174                commits: 0,
18175                empty: false,
18176                failed: None,
18177                verified_noop: None,
18178                duration_ms: 0,
18179                folded: false,
18180            });
18181            let mut task = crate::queue::Task::new(
18182                "task".into(),
18183                "task".into(),
18184                repo.clone(),
18185                crate::queue::Source::Human,
18186            );
18187            task.runs.push(state.id.clone());
18188            crate::queue::Queue::at(home.join("queue"))
18189                .put(&mut task)
18190                .unwrap();
18191            if sidecar {
18192                crate::pr_recovery::retain_sources(&task, &home).unwrap();
18193            }
18194            state.save_under(&home).unwrap();
18195            let reason = crate::pr_recovery::source_retention_reason(&home, &state).unwrap();
18196            let refusal = fold_run(&mut state, true, &home).await.unwrap_err();
18197            assert!(
18198                matches!(
18199                    refusal.downcast_ref::<FoldRefusal>(),
18200                    Some(FoldRefusal::Retained(retained)) if retained == &reason
18201                ),
18202                "{refusal:#}"
18203            );
18204            let mut disk = state.config.disk.clone();
18205            disk.fold_grace_secs = 0;
18206            assert_eq!(
18207                crate::clean::fold_due(
18208                    &home.join("runs"),
18209                    &home,
18210                    &state.worktree_root(),
18211                    &disk,
18212                    Timestamp::now() + std::time::Duration::from_secs(10),
18213                )
18214                .await
18215                .unwrap(),
18216                (0, 0)
18217            );
18218            assert!(wt.exists());
18219            state.status = RunStatus::Blocked;
18220            state.save_under(&home).unwrap();
18221            let error = override_refusal(&mut state, &home).await;
18222            assert!(
18223                error
18224                    .to_string()
18225                    .contains("requires a finished, non-resumable run"),
18226                "{error:#}"
18227            );
18228            state.status = RunStatus::Superseded;
18229            state.driver_exited = false;
18230            state.driver_claimed = None;
18231            state.save_under(&home).unwrap();
18232            let error = override_refusal(&mut state, &home).await;
18233            assert!(
18234                error
18235                    .to_string()
18236                    .contains("run is live or its ownership is unknown"),
18237                "{error:#}"
18238            );
18239            state.driver_pid = Some(std::process::id());
18240            state.driver_started_at = crate::proc::process_started_at(std::process::id());
18241            state.save_under(&home).unwrap();
18242            let error = override_refusal(&mut state, &home).await;
18243            assert!(
18244                error
18245                    .to_string()
18246                    .contains("run is live or its ownership is unknown"),
18247                "{error:#}"
18248            );
18249            state.driver_exited = true;
18250            state.driver_pid = None;
18251            state.driver_started_at = None;
18252            state.save_under(&home).unwrap();
18253            let lease = crate::driver::maintenance(&home, &state.id).unwrap();
18254            let error = override_refusal(&mut state, &home).await;
18255            assert!(
18256                matches!(
18257                    error.downcast_ref::<FoldRefusal>(),
18258                    Some(FoldRefusal::Live(_))
18259                ),
18260                "{error:#}"
18261            );
18262            drop(lease);
18263            #[cfg(unix)]
18264            {
18265                let output = crate::retention::OutputLease::take(&wt, false).unwrap();
18266                let error = override_refusal(&mut state, &home).await;
18267                assert!(
18268                    matches!(
18269                        error.downcast_ref::<FoldRefusal>(),
18270                        Some(FoldRefusal::Live(_))
18271                    ),
18272                    "{error:#}"
18273                );
18274                drop(output);
18275            }
18276            let owner = crate::pr_head::owner_lock(&home, &state.id).unwrap();
18277            let error = override_refusal(&mut state, &home).await;
18278            assert!(
18279                matches!(
18280                    error.downcast_ref::<FoldRefusal>(),
18281                    Some(FoldRefusal::Live(_))
18282                ),
18283                "{error:#}"
18284            );
18285            drop(owner);
18286            let checkpoint = git::git(
18287                &wt,
18288                &[
18289                    "rev-parse",
18290                    "--path-format=absolute",
18291                    "--git-path",
18292                    "CHERRY_PICK_HEAD",
18293                ],
18294            )
18295            .await
18296            .unwrap();
18297            std::fs::write(&checkpoint, &head).unwrap();
18298            let error = override_refusal(&mut state, &home).await;
18299            assert!(
18300                matches!(
18301                    error.downcast_ref::<FoldRefusal>(),
18302                    Some(FoldRefusal::ProofIncomplete(detail))
18303                        if detail.contains("Git recovery checkpoint retained")
18304                ),
18305                "{error:#}"
18306            );
18307            std::fs::remove_file(checkpoint).unwrap();
18308            std::fs::write(wt.join("dirty"), "keep").unwrap();
18309            let error = override_refusal(&mut state, &home).await;
18310            assert!(
18311                matches!(
18312                    error.downcast_ref::<FoldRefusal>(),
18313                    Some(FoldRefusal::ProofIncomplete(_))
18314                ),
18315                "{error:#}"
18316            );
18317            assert!(wt.join("dirty").exists());
18318            std::fs::remove_file(wt.join("dirty")).unwrap();
18319            let evidence = home
18320                .join("runs")
18321                .join(&state.id)
18322                .join("artifacts/fold-evidence");
18323            std::fs::create_dir_all(evidence.parent().unwrap()).unwrap();
18324            std::fs::write(&evidence, "blocked archive").unwrap();
18325            let error = override_refusal(&mut state, &home).await;
18326            assert!(
18327                matches!(
18328                    error.downcast_ref::<FoldRefusal>(),
18329                    Some(FoldRefusal::ProofIncomplete(_))
18330                ),
18331                "{error:#}"
18332            );
18333            assert!(wt.exists());
18334            assert!(
18335                !RunState::load_under(&state.id, &home)
18336                    .unwrap()
18337                    .events
18338                    .iter()
18339                    .any(|event| event.message.contains("--override-recovery-retention"))
18340            );
18341            std::fs::remove_file(&evidence).unwrap();
18342            fold_run_overriding_recovery_retention(&mut state, true, &home)
18343                .await
18344                .unwrap();
18345            assert!(!wt.exists());
18346            assert!(!git::branch_exists(&repo, "candidate").await.unwrap());
18347            assert!(
18348                git::worktree_holding(&repo, "candidate")
18349                    .await
18350                    .unwrap()
18351                    .is_none()
18352            );
18353            assert!(
18354                std::fs::read_to_string(evidence.join(format!("{head}.patch")))
18355                    .unwrap()
18356                    .contains("retained implementation")
18357            );
18358            assert!(evidence.join(format!("{head}.index")).is_file());
18359            let saved = RunState::load_under(&state.id, &home).unwrap();
18360            assert_eq!(saved.status, RunStatus::Superseded);
18361            assert!(saved.candidates[0].folded);
18362            assert!(saved.events.iter().any(|event| {
18363                event.message.contains("--override-recovery-retention")
18364                    && event.message.contains(&state.id)
18365                    && event.message.contains(&reason)
18366            }));
18367            assert_eq!(
18368                crate::pr_recovery::explicit_sources_retained(&home, &state.id),
18369                sidecar
18370            );
18371        }
18372    }
18373
18374    #[tokio::test]
18375    async fn candidate_preservation_retries_after_upgrade_without_rerunning_seats() {
18376        ask_test_home();
18377        let tmp = tempfile::tempdir().unwrap();
18378        let repo = tmp.path().join("repo");
18379        std::fs::create_dir(&repo).unwrap();
18380        init_repo(&repo);
18381        let mut runner = runner_at(RunStatus::Implementing);
18382        runner.state.repo = repo.clone();
18383        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
18384        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
18385        for (index, label) in ['A', 'B'].into_iter().enumerate() {
18386            let branch = format!("candidate-{label}");
18387            let wt = runner.state.worktree_root().join(format!("cand-{label}"));
18388            git::worktree_add_branch(&repo, &wt, &branch, "main")
18389                .await
18390                .unwrap();
18391            std::fs::write(wt.join("README.md"), "tracked edits\n").unwrap();
18392            git::git(&wt, &["add", "README.md"]).await.unwrap();
18393            std::fs::write(wt.join("README.md"), "later tracked edits\n").unwrap();
18394            std::fs::write(wt.join("new-file"), "untracked edits\n").unwrap();
18395            runner.state.candidates.push(Candidate {
18396                index,
18397                label,
18398                agent: "alpha".to_owned(),
18399                branch,
18400                worktree: wt,
18401                summary: "completed implementation".to_owned(),
18402                stat: String::new(),
18403                files: 0,
18404                commits: 0,
18405                empty: false,
18406                failed: None,
18407                verified_noop: None,
18408                duration_ms: 42,
18409                folded: false,
18410            });
18411            runner
18412                .state
18413                .candidate_preservation
18414                .insert(label, "awaiting persistence".to_owned());
18415        }
18416        let wt = runner.state.candidates[0].worktree.clone();
18417        let index_lock = git::git(
18418            &wt,
18419            &[
18420                "rev-parse",
18421                "--path-format=absolute",
18422                "--git-path",
18423                "index.lock",
18424            ],
18425        )
18426        .await
18427        .unwrap();
18428        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
18429        runner.state.save().unwrap();
18430        assert!(runner.persist_candidates().await.is_err());
18431        assert!(runner.state.candidate_preservation.contains_key(&'A'));
18432        assert!(!runner.state.candidate_preservation.contains_key(&'B'));
18433        assert_eq!(
18434            runner.state.candidates[1].commits, 1,
18435            "other results are still collected"
18436        );
18437        assert!(
18438            !runner.state.candidates[0].empty,
18439            "failed rescue is not no change"
18440        );
18441        assert_eq!(
18442            runner.state.candidates[0].summary,
18443            "completed implementation"
18444        );
18445        assert!(runner.after_implement().is_err());
18446        // The record the fold locks is the one on disk, so the arrangement is
18447        // saved first; the refusal asserted is the preservation rule's own,
18448        // never `record gone`.
18449        runner.state.save().unwrap();
18450        let refusal = fold_run(&mut runner.state, true, &crate::run::home())
18451            .await
18452            .unwrap_err();
18453        assert!(
18454            matches!(
18455                refusal.downcast_ref::<FoldRefusal>(),
18456                Some(FoldRefusal::ProofIncomplete(detail))
18457                    if detail.contains("candidate preservation incomplete")
18458            ),
18459            "{refusal:#}"
18460        );
18461        assert!(wt.join("new-file").exists());
18462        let recovery = runner.state.dir().join("artifacts/candidate-A-recovery");
18463        assert!(recovery.join("staged.patch").exists());
18464        assert!(recovery.join("unstaged.patch").exists());
18465        assert_eq!(
18466            std::fs::read_to_string(recovery.join("untracked/new-file")).unwrap(),
18467            "untracked edits\n"
18468        );
18469        runner.state.begin_pass();
18470        runner.state.end_pass_parked(ParkCause::Upgrade {
18471            from: "1.0".into(),
18472            to: Some("1.1".into()),
18473        });
18474        runner.state.save().unwrap();
18475        runner.state = RunState::load(&runner.state.id).unwrap();
18476        assert!(matches!(
18477            runner.state.passes.last().unwrap().end,
18478            Some(crate::run::PassEnd::Parked {
18479                cause: ParkCause::Upgrade { .. }
18480            })
18481        ));
18482        std::fs::remove_file(index_lock).unwrap();
18483        // No implementer is configured: a persistence retry cannot dispatch a seat.
18484        runner.implement().await.unwrap();
18485        assert!(runner.state.candidate_preservation.is_empty());
18486        assert!(
18487            runner
18488                .state
18489                .candidates
18490                .iter()
18491                .all(|c| c.commits == 1 && !c.empty)
18492        );
18493        assert!(git::is_clean(&wt).await.unwrap());
18494        assert!(
18495            crate::run::read_artifact(&runner.state, "cand-A.patch")
18496                .unwrap()
18497                .contains("later tracked edits")
18498        );
18499    }
18500
18501    #[tokio::test]
18502    async fn candidate_preservation_git_read_and_cleanup_fail_closed() {
18503        ask_test_home();
18504        let tmp = tempfile::tempdir().unwrap();
18505        let repo = tmp.path().join("repo");
18506        std::fs::create_dir(&repo).unwrap();
18507        init_repo(&repo);
18508        let wt = tmp.path().join("candidate");
18509        git::worktree_add_branch(&repo, &wt, "candidate", "main")
18510            .await
18511            .unwrap();
18512        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
18513        assert!(remove_preserved_worktree(&repo, &wt).await.is_err());
18514        assert!(wt.join("uncommitted").exists());
18515        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
18516        std::fs::remove_file(wt.join("uncommitted")).unwrap();
18517        let mut runner = runner_at(RunStatus::Implementing);
18518        runner.state.repo = repo.clone();
18519        runner.state.base_commit = "missing-base".to_owned();
18520        runner.state.candidates.push(Candidate {
18521            index: 0,
18522            label: 'A',
18523            agent: "alpha".into(),
18524            branch: "candidate".into(),
18525            worktree: wt.clone(),
18526            summary: "completed".into(),
18527            stat: String::new(),
18528            files: 0,
18529            commits: 0,
18530            empty: false,
18531            failed: None,
18532            verified_noop: None,
18533            duration_ms: 1,
18534            folded: false,
18535        });
18536        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
18537        // Saved in the home the fold uses: without a record the fold would
18538        // refuse as `record gone` and say nothing about the dirty tree.
18539        let home = tmp.path().join("home");
18540        runner.state.save_under(&home).unwrap();
18541        let refusal = fold_run(&mut runner.state, true, &home).await.unwrap_err();
18542        assert!(
18543            refusal
18544                .to_string()
18545                .contains("worktree has uncommitted work; refusing removal"),
18546            "{refusal:#}"
18547        );
18548        assert!(refusal.downcast_ref::<FoldRefusal>().is_none());
18549        assert!(!runner.state.candidates[0].folded);
18550        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
18551        std::fs::remove_file(wt.join("uncommitted")).unwrap();
18552        runner
18553            .state
18554            .candidate_preservation
18555            .insert('A', "pending".into());
18556        assert!(runner.persist_candidates().await.is_err());
18557        assert!(!runner.state.candidates[0].empty);
18558        assert!(!runner.state.candidates[0].folded);
18559        assert!(wt.exists());
18560        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
18561        let patch_path = runner.state.dir().join("artifacts/cand-A.patch");
18562        std::fs::create_dir_all(&patch_path).unwrap();
18563        assert!(
18564            runner.persist_candidates().await.is_err(),
18565            "artifact failure stays pending"
18566        );
18567        assert!(runner.state.candidate_preservation.contains_key(&'A'));
18568        assert!(!runner.state.candidates[0].empty);
18569        std::fs::remove_dir(patch_path).unwrap();
18570        runner.persist_candidates().await.unwrap();
18571        assert!(
18572            runner.state.candidates[0].empty,
18573            "only successful inspection confirms no change"
18574        );
18575    }
18576
18577    fn init_repo(dir: &Path) {
18578        let run = |args: &[&str]| {
18579            let out = std::process::Command::new("git")
18580                .args(args)
18581                .current_dir(dir)
18582                .quiet()
18583                .output()
18584                .expect("spawn git");
18585            assert!(
18586                out.status.success(),
18587                "git {args:?} failed: {}",
18588                String::from_utf8_lossy(&out.stderr)
18589            );
18590        };
18591        run(&["init", "-b", "main"]);
18592        run(&["config", "user.name", "magi test"]);
18593        run(&["config", "user.email", "magi@example.com"]);
18594        std::fs::write(dir.join("README.md"), "# fixture\n").unwrap();
18595        run(&["add", "-A"]);
18596        run(&["commit", "-m", "init"]);
18597    }
18598
18599    // `settle_questions` is what closes the ghost the phone showed: a run's
18600    // seat asked something, the run then ended, and nothing was left to
18601    // abandon the question it left `open`. `HOME` is a process-wide
18602    // `OnceLock` (see `run::set_home`'s doc), so this only wins the race the
18603    // first time it runs in the binary — every test below still reaches the
18604    // same directory whichever call won, and each gets its own run id from
18605    // `RunState::new`, so they never collide there.
18606    fn ask_test_home() {
18607        crate::run::pin_test_home();
18608    }
18609
18610    #[test]
18611    fn startup_terminal_save_failure_preserves_original_error_and_reservation() {
18612        ask_test_home();
18613        let mut runner = runner_at(RunStatus::Prep);
18614        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
18615        // A blocked temporary output path makes the terminal save fail while
18616        // preserving the already published reservation.
18617        std::fs::create_dir(runner.state.dir().join("run.json.tmp")).unwrap();
18618        let error = guard
18619            .finish(
18620                &mut runner.state,
18621                Err(
18622                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "original refusal")
18623                        .into(),
18624                ),
18625            )
18626            .unwrap_err();
18627        assert_eq!(
18628            error.downcast_ref::<std::io::Error>().unwrap().kind(),
18629            std::io::ErrorKind::PermissionDenied
18630        );
18631        assert!(error.downcast_ref::<crate::run::StartupFailure>().is_some());
18632        let message = format!("{error:#}");
18633        assert!(message.contains("original refusal"));
18634        assert!(!message.contains("could not save terminal"));
18635        assert_eq!(
18636            error.chain().count(),
18637            2,
18638            "only startup attribution wraps the original error"
18639        );
18640        let saved = RunState::load(&runner.state.id).unwrap();
18641        assert_eq!(saved.status, RunStatus::Blocked);
18642        assert!(!saved.startup.unwrap().complete);
18643    }
18644
18645    #[test]
18646    fn reserved_startup_interruption_is_blocked_and_not_resumable() {
18647        ask_test_home();
18648        let mut runner = runner_at(RunStatus::Prep);
18649        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
18650        let id = runner.state.id.clone();
18651        drop(guard);
18652        let saved = RunState::load(&id).unwrap();
18653        assert_eq!(saved.status, RunStatus::Blocked);
18654        assert!(!saved.startup.as_ref().unwrap().complete);
18655        assert!(
18656            saved
18657                .startup
18658                .unwrap()
18659                .failure
18660                .unwrap()
18661                .contains("interrupted")
18662        );
18663        assert!(Runner::resume(&id).is_err());
18664    }
18665
18666    #[test]
18667    fn startup_failure_keeps_typed_cause_and_separate_task_history() {
18668        ask_test_home();
18669        let mut runner = runner_at(RunStatus::Prep);
18670        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
18671        let error = guard
18672            .finish(
18673                &mut runner.state,
18674                Err(
18675                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "refused startup")
18676                        .into(),
18677                ),
18678            )
18679            .unwrap_err();
18680        assert_eq!(
18681            error.downcast_ref::<std::io::Error>().unwrap().kind(),
18682            std::io::ErrorKind::PermissionDenied
18683        );
18684        let failure = error.downcast_ref::<crate::run::StartupFailure>().unwrap();
18685        let mut task = crate::queue::Task::new(
18686            "review".into(),
18687            "criteria".into(),
18688            runner.state.repo.clone(),
18689            crate::queue::Source::Human,
18690        );
18691        task.record_startup_failure(failure.clone());
18692        task.record_startup_failure(failure.clone());
18693        assert_eq!(task.startup_failures.len(), 1);
18694        assert!(task.runs.is_empty());
18695        assert_eq!(task.attempts, 0);
18696    }
18697
18698    async fn exhausted_base_fixture() -> (tempfile::TempDir, Runner, String, String) {
18699        ask_test_home();
18700        let tmp = tempfile::tempdir().unwrap();
18701        let repo = tmp.path().join("repo");
18702        std::fs::create_dir(&repo).unwrap();
18703        init_repo(&repo);
18704        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
18705        let origin = tmp.path().join("origin.git");
18706        git::git(&repo, &["init", "--bare", origin.to_str().unwrap()])
18707            .await
18708            .unwrap();
18709        git::git(
18710            &repo,
18711            &["remote", "add", "origin", origin.to_str().unwrap()],
18712        )
18713        .await
18714        .unwrap();
18715        git::git(&repo, &["checkout", "-b", "fix/retained"])
18716            .await
18717            .unwrap();
18718        std::fs::write(repo.join("retained"), "retained change").unwrap();
18719        git::git(&repo, &["add", "."]).await.unwrap();
18720        git::git(&repo, &["commit", "-m", "retained implementation"])
18721            .await
18722            .unwrap();
18723        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
18724        git::git(&repo, &["checkout", "main"]).await.unwrap();
18725        std::fs::write(repo.join("base-change"), "new base").unwrap();
18726        git::git(&repo, &["add", "."]).await.unwrap();
18727        git::git(&repo, &["commit", "-m", "base moved"])
18728            .await
18729            .unwrap();
18730        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
18731        git::git(&repo, &["checkout", "fix/retained"])
18732            .await
18733            .unwrap();
18734        let mut runner = runner_at(RunStatus::Voting);
18735        runner.state.repo = repo.clone();
18736        runner.state.base_commit = base;
18737        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
18738        runner.state.config.disk.min_free_bytes = 0;
18739        runner.state.config.graph.review_rounds = 1;
18740        runner.state.config.verify.e2e = vec!["true".into()];
18741        runner.state.config.verify.gate = vec!["true".into()];
18742        runner.state.candidates = vec![Candidate {
18743            index: 0,
18744            label: 'A',
18745            agent: "fixture".into(),
18746            branch: "fix/retained".into(),
18747            worktree: repo.clone(),
18748            summary: String::new(),
18749            stat: String::new(),
18750            files: 1,
18751            commits: 1,
18752            empty: false,
18753            failed: None,
18754            verified_noop: None,
18755            duration_ms: 0,
18756            folded: false,
18757        }];
18758        runner.state.tally = Some(Tally {
18759            first_choice: BTreeMap::new(),
18760            borda: BTreeMap::new(),
18761            winner: 'A',
18762            rankings: 0,
18763            unanimous_initial: true,
18764            deliberated: false,
18765            changed_votes: 0,
18766            unanimous_final: true,
18767            tie_break: None,
18768            judges: 0,
18769            present: 0,
18770            quorum: 0,
18771            met_quorum: true,
18772            uncontested: Some("review-only".into()),
18773        });
18774        let mut task = crate::queue::Task::new(
18775            "fixture".into(),
18776            "fixture".into(),
18777            repo,
18778            crate::queue::Source::Human,
18779        );
18780        task.link_run(&runner.state.id);
18781        crate::queue::Queue::open().put(&mut task).unwrap();
18782        runner.state.origin = Some(crate::run::Origin::queue(&task.id));
18783        runner.state.base_sync = Some(BaseSync {
18784            tip: String::new(),
18785            behind: 1,
18786            attempts: BASE_SYNC_ROUNDS,
18787            conflict: None,
18788            already_in: None,
18789        });
18790        runner.sync_to_base().await.unwrap();
18791        assert_eq!(runner.state.status, RunStatus::Blocked);
18792        (tmp, runner, head, task.id)
18793    }
18794
18795    #[tokio::test]
18796    async fn rebase_preparation_failure_preserves_base_sync_budget_and_resumes() {
18797        let (_tmp, mut runner, head, _task) = exhausted_base_fixture().await;
18798        runner.state.status = RunStatus::Voting;
18799        runner.state.base_sync = None;
18800        runner.state.base_sync_recovery = Default::default();
18801        let scratch = runner.state.dir().join("base-sync");
18802        std::fs::create_dir_all(&scratch).unwrap();
18803        std::fs::write(scratch.join("obstruction"), "keep").unwrap();
18804        runner.sync_to_base().await.unwrap();
18805        assert!(runner.state.resource_block.is_some());
18806        assert!(!runner.state.base_sync_blocked());
18807        assert!(runner.state.base_sync.is_none());
18808        assert_eq!(
18809            std::fs::read_to_string(scratch.join("obstruction")).unwrap(),
18810            "keep"
18811        );
18812        assert_eq!(runner.state.base_episode_used(), 0);
18813        assert!(runner.state.base_sync_recovery.operations.is_empty());
18814        assert!(runner.state.rebase_fixes.is_empty());
18815        assert_eq!(
18816            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18817            head
18818        );
18819        std::fs::remove_dir_all(&scratch).unwrap();
18820        runner.state.resource_block = None;
18821        runner.sync_to_base().await.unwrap();
18822        assert!(!runner.state.base_sync_blocked());
18823        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18824        assert_eq!(runner.state.base_episode_used(), 1);
18825        assert!(runner.state.base_sync_recovery.operations[0].finished);
18826        assert!(runner.state.rebase_fixes.is_empty());
18827        assert!(git::is_ancestor(&runner.state.repo, "origin/main", "HEAD").await);
18828        assert!(git::is_clean(&runner.state.repo).await.unwrap());
18829    }
18830
18831    #[tokio::test]
18832    async fn rebase_legacy_sequencer_stop_reuses_the_original_reservation() {
18833        let (tmp, mut runner, head, owner) = exhausted_base_fixture().await;
18834        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18835        runner.state.base_sync_recovery = Default::default();
18836        runner.state.task_instruction = Some("fixture".into());
18837        runner.state.config.agents = vec![spec("fixture")];
18838        runner.state.config.graph.review_rounds = 0;
18839        runner.state.config.merge.mode = MergeMode::None;
18840        runner.state.driver_exited = true;
18841        let sync = runner.state.base_sync.as_mut().unwrap();
18842        sync.conflict = None;
18843        sync.attempts = 0;
18844        runner.state.reserve_base_operation(&head, &tip);
18845        runner.state.finish_base_operation(None);
18846        let detail = format!(
18847            "fix/retained conflicts with origin/main and did not rebase: \
18848             conflict not resolved after 28 of 3 fixer round(s) (not on the new base); \
18849             remaining conflicted path(s): none recorded; git said: \
18850             warning: execution failed: {}",
18851            git::REBASE_EXEC
18852        );
18853        runner.state.base_sync.as_mut().unwrap().conflict = Some(detail.clone());
18854        runner.state.record_base_sync_stop(&head);
18855        runner.state.rebase_fixes.push(crate::run::RebaseFixRecord {
18856            unstarted: false,
18857            agent: "fixture".into(),
18858            paths: Vec::new(),
18859            from: Some(head.clone()),
18860            finished: true,
18861            error: None,
18862            stop: None,
18863            onto: None,
18864            index_outside: None,
18865            launcher: None,
18866            infra: None,
18867            outage: None,
18868        });
18869        runner.state.save().unwrap();
18870        assert_eq!(
18871            crate::resume::validate(&crate::run::home(), &runner.state.id)
18872                .unwrap()
18873                .id,
18874            runner.state.id
18875        );
18876
18877        let dirty = runner.state.repo.join("owner-work");
18878        std::fs::write(&dirty, "keep").unwrap();
18879        runner.sync_to_base().await.unwrap();
18880        assert_eq!(std::fs::read_to_string(&dirty).unwrap(), "keep");
18881        assert!(runner.state.base_sync_recovery.operations[0].finished);
18882        assert!(runner.state.base_sync_blocked());
18883        std::fs::remove_file(dirty).unwrap();
18884
18885        let queue = crate::queue::Queue::open();
18886        let id = runner.state.id.clone();
18887        assert!(crate::resume::pin_queued(&queue, &id, None, None).unwrap());
18888        let _claim = queue.claim(&owner).unwrap();
18889        let mut task = queue.get(&owner).unwrap();
18890        let config = tmp.path().join("test-config.toml");
18891        std::fs::write(&config, "[disk]\nmin_free_bytes = 0\n").unwrap();
18892        let opts = crate::daemon::Opts {
18893            repo: task.repo.clone(),
18894            config: Some(config),
18895            ..Default::default()
18896        };
18897        crate::daemon::run_claimed(&opts, &queue, &mut task).await;
18898        let task = queue.get(&owner).unwrap();
18899        assert_eq!(
18900            task.runs.as_slice(),
18901            std::slice::from_ref(&id),
18902            "{:?}",
18903            task.hold_reason
18904        );
18905        runner.state = RunState::load(&id).unwrap();
18906        assert!(!runner.state.base_sync_blocked());
18907        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18908        assert_eq!(runner.state.base_sync_recovery.operations.len(), 1);
18909        assert!(runner.state.base_sync_recovery.operations[0].finished);
18910        assert_eq!(
18911            runner.state.base_sync_recovery.stops.last().unwrap().detail,
18912            detail
18913        );
18914        assert_eq!(runner.state.rebase_fixes.len(), 1);
18915        assert!(git::is_ancestor(&runner.state.repo, &tip, "HEAD").await);
18916    }
18917
18918    #[cfg(unix)]
18919    #[tokio::test]
18920    async fn base_recovery_control_rechecks_owner_decision_and_routing_at_consumption() {
18921        for routed in [false, true] {
18922            let (_tmp, mut runner, head, owner) = exhausted_base_fixture().await;
18923            let home = crate::run::home();
18924            let queue = crate::queue::Queue::open();
18925            let task = queue.get(&owner).unwrap();
18926            runner.state.task_instruction = Some(task.instruction.clone());
18927            runner.state.driver_exited = true;
18928            runner.state.save().unwrap();
18929            let questions = crate::ask::Questions::at(home.join("questions"));
18930            let mut q = crate::ask::Question::new(
18931                runner.state.id.clone(),
18932                "base-recovery".into(),
18933                "owner".into(),
18934                "Recover bounded base movement?".into(),
18935                String::new(),
18936                vec!["recover".into()],
18937            );
18938            q.actions.insert(
18939                "recover".into(),
18940                crate::ask::ChoiceAction::RecoverBase {
18941                    run: runner.state.id.clone(),
18942                    stop: runner.state.base_sync_recovery.stop.clone().unwrap(),
18943                    episode: runner.state.base_sync_recovery.episodes.last().unwrap().id,
18944                },
18945            );
18946            q.routed_task = Some(owner.clone());
18947            q.answer(crate::ask::Answer::Choice("recover".into()))
18948                .unwrap();
18949            questions.put(&mut q).unwrap();
18950            crate::base_recovery_control::recover(
18951                &queue,
18952                &home,
18953                crate::base_recovery_control::Request {
18954                    run: runner.state.id.clone(),
18955                    head: head.clone(),
18956                    actor: "decisions".into(),
18957                    request: q.id.clone(),
18958                    decision: Some((owner.clone(), q.answered_at.unwrap())),
18959                    expected_stop: Some((
18960                        runner.state.base_sync_recovery.stop.clone().unwrap(),
18961                        runner.state.base_sync_recovery.episodes.last().unwrap().id,
18962                    )),
18963                    evidence_digest: None,
18964                },
18965            )
18966            .await
18967            .unwrap();
18968            if routed {
18969                questions
18970                    .update(&q.id, |q| {
18971                        q.routed_task = Some("another-owner".into());
18972                        Ok(())
18973                    })
18974                    .unwrap();
18975            } else {
18976                let mut task = queue.get(&owner).unwrap();
18977                task.hold_manual(Some("new owner decision".into()));
18978                // Keep the generation to exercise the separate owner-decision binding.
18979                task.status = crate::queue::TaskStatus::Queued;
18980                queue.put(&mut task).unwrap();
18981            }
18982            runner.state = RunState::load(&runner.state.id).unwrap();
18983            runner.sync_to_base().await.unwrap();
18984            let approval = runner
18985                .state
18986                .base_sync_recovery
18987                .authorizations
18988                .last()
18989                .unwrap();
18990            assert!(approval.consumed);
18991            assert!(approval.invalidated.as_ref().unwrap().contains(if routed {
18992                "routing"
18993            } else {
18994                "owner decision"
18995            }));
18996            assert_eq!(
18997                runner.state.base_sync.as_ref().unwrap().attempts,
18998                BASE_SYNC_ROUNDS
18999            );
19000            assert_eq!(
19001                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19002                head
19003            );
19004        }
19005    }
19006
19007    #[cfg(unix)]
19008    #[tokio::test]
19009    async fn base_recovery_authorizes_its_worker_but_rejects_other_workers() {
19010        const CHILD: &str = "MAGI_BASE_RECOVERY_WORKER_TEST";
19011        if std::env::var_os(CHILD).is_none() {
19012            let home = tempfile::tempdir().unwrap();
19013            let output = std::process::Command::new(std::env::current_exe().unwrap())
19014                .args([
19015                    "--exact",
19016                    "graph::tests::base_recovery_authorizes_its_worker_but_rejects_other_workers",
19017                    "--nocapture",
19018                ])
19019                .env(CHILD, "1")
19020                .env("MAGI_HOME", home.path())
19021                .env("MAGI_WORKER_HOME", home.path())
19022                .env("MAGI_WORKER_ID", "abcdef")
19023                .output()
19024                .unwrap();
19025            assert!(
19026                output.status.success()
19027                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
19028                "{}\n{}",
19029                String::from_utf8_lossy(&output.stdout),
19030                String::from_utf8_lossy(&output.stderr)
19031            );
19032            return;
19033        }
19034        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
19035        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
19036        let home = crate::run::home();
19037        let queue = crate::queue::Queue::open();
19038        let mut owner = queue.get(&task).unwrap();
19039        owner.release_operator("test-release", None);
19040        owner.start(runner.state.id.clone());
19041        queue.put(&mut owner).unwrap();
19042        runner.state.driver_exited = true;
19043        runner.state.task_instruction = Some(owner.instruction.clone());
19044        runner.state.save().unwrap();
19045        let _claim = queue.claim(&task).unwrap();
19046        let reserve = |id: &str| {
19047            let directory = home.join("workers/jobs").join(id);
19048            std::fs::create_dir_all(&directory).unwrap();
19049            let job = crate::worker::Job {
19050                id: id.into(),
19051                sequence: 1,
19052                kind: "task".into(),
19053                key: format!("task:{task}"),
19054                payload: serde_json::json!({"opts": crate::daemon::Opts::default(), "queue": queue.root(), "task": task}),
19055                generation: "fixture-generation".into(),
19056                version: None,
19057                status: crate::worker::Status::Running,
19058                result: None,
19059                pid: Some(std::process::id()),
19060                created_at: 0,
19061                finished_at: None,
19062            };
19063            std::fs::write(
19064                directory.join("job.json"),
19065                serde_json::to_vec(&job).unwrap(),
19066            )
19067            .unwrap();
19068            crate::worker::execution_lease_for_test(&directory.join("live.lock"))
19069        };
19070        let _own = reserve("abcdef");
19071        let other = reserve("fedcba");
19072        assert!(
19073            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19074                .await
19075                .is_err()
19076        );
19077        assert!(
19078            RunState::load(&runner.state.id)
19079                .unwrap()
19080                .base_sync_recovery
19081                .authorizations
19082                .is_empty()
19083        );
19084        drop(other);
19085        assert!(crate::daemon::is_working_on(
19086            &home,
19087            &runner.state.id,
19088            Timestamp::now()
19089        ));
19090        assert!(
19091            !crate::daemon::is_working_on_other(&home, &runner.state.id, Timestamp::now()).unwrap()
19092        );
19093        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19094            .await
19095            .unwrap();
19096        assert!(
19097            RunState::load(&runner.state.id)
19098                .unwrap()
19099                .base_recovery_pending()
19100        );
19101    }
19102
19103    #[cfg(unix)]
19104    #[tokio::test]
19105    async fn base_recovery_authorizes_a_crashed_driver_with_a_free_matching_lease() {
19106        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
19107        let home = crate::run::home();
19108        runner.state.driver_pid = Some(std::process::id());
19109        runner.state.driver_started_at = crate::proc::process_started_at(std::process::id());
19110        runner.state.driver_exited = false;
19111        runner.state.begin_pass();
19112        runner.state.save().unwrap();
19113        let mut driver = crate::driver::DriverGuard::acquire(&home, &runner.state).unwrap();
19114        driver.record(&runner.state).unwrap();
19115        let saved = std::fs::read(runner.state.dir().join("run.json")).unwrap();
19116        // Preserve the durable claim as if the process died before Drop saved.
19117        drop(driver);
19118        std::fs::write(runner.state.dir().join("run.json"), saved).unwrap();
19119        assert_eq!(
19120            runner.state.liveness_under(&home, false),
19121            crate::run::Liveness::Dead
19122        );
19123        let queue = crate::queue::Queue::open();
19124        let _claim = queue.claim(&task).unwrap();
19125        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19126            .await
19127            .unwrap();
19128        let disk = RunState::load(&runner.state.id).unwrap();
19129        assert!(!disk.driver_exited);
19130        assert!(disk.base_recovery_pending());
19131    }
19132
19133    #[cfg(unix)]
19134    #[tokio::test]
19135    async fn base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase() {
19136        const CHILD: &str = "MAGI_BASE_RECOVERY_CLOSURE_TEST";
19137        if std::env::var_os(CHILD).is_none() {
19138            use std::os::unix::fs::PermissionsExt;
19139            let tmp = tempfile::tempdir().unwrap();
19140            let gh = tmp.path().join("gh");
19141            std::fs::write(&gh, r#"#!/bin/sh
19142case "$1 $2" in
19143  'pr view') printf '{"headRefName":"fix/retained","headRefOid":"%s","baseRefName":"main","state":"OPEN","isCrossRepository":false}' "$(git rev-parse fix/retained)" ;;
19144  'pr close') if [ ! -f "$MAGI_BASE_CLOSURE_MARKER" ]; then touch "$MAGI_BASE_CLOSURE_MARKER"; echo 'transient closure failure' >&2; exit 1; fi ;;
19145  *) exit 2 ;;
19146esac
19147"#).unwrap();
19148            std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
19149            let mut paths = vec![tmp.path().to_path_buf()];
19150            paths.extend(std::env::split_paths(&std::env::var_os("PATH").unwrap()));
19151            let output = std::process::Command::new(std::env::current_exe().unwrap())
19152                .args(["--exact", "graph::tests::base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase", "--nocapture"])
19153                .env(CHILD, "1")
19154                .env("MAGI_BASE_CLOSURE_MARKER", tmp.path().join("closure-attempted"))
19155                .env("PATH", std::env::join_paths(paths).unwrap())
19156                .env_remove("MAGI_WORKER_HOME").env_remove("MAGI_WORKER_ID")
19157                .output().unwrap();
19158            assert!(
19159                output.status.success()
19160                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
19161                "{}\n{}",
19162                String::from_utf8_lossy(&output.stdout),
19163                String::from_utf8_lossy(&output.stderr)
19164            );
19165            return;
19166        }
19167        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19168        let repo = runner.state.repo.clone();
19169        git::git(&repo, &["checkout", "main"]).await.unwrap();
19170        git::git(&repo, &["cherry-pick", &head]).await.unwrap();
19171        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
19172        git::git(&repo, &["checkout", "fix/retained"])
19173            .await
19174            .unwrap();
19175        runner.state.pr = Some(crate::run::PrRecord {
19176            url: "https://example.test/project/pull/1".into(),
19177            number: 1,
19178            state: "open".into(),
19179            checks: "unknown".into(),
19180            round: 0,
19181            rounds: 1,
19182            red_at_merge: Vec::new(),
19183        });
19184        runner.sync_to_base().await.unwrap();
19185        assert_eq!(runner.state.status, RunStatus::Blocked);
19186        assert_eq!(
19187            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
19188            crate::base_sync_recovery::StopKind::ClosingIntegratedPr
19189        );
19190        assert!(runner.state.base_sync_closure_pending());
19191        assert!(crate::handover::can_resume(&runner.state));
19192        let queue = crate::queue::Queue::open();
19193        assert!(!crate::base_sync_recovery::held_task(
19194            &queue,
19195            &queue.get(&task).unwrap()
19196        ));
19197        assert!(runner.state.authorize_base_sync(&task).is_err());
19198        // Legacy closure stops have no typed stop but must retain the checkpoint.
19199        runner.state.base_sync_recovery.stop = None;
19200        runner.state.status = RunStatus::Voting;
19201        runner.state.gate_ran = true;
19202        runner.state.config.graph.review_rounds = 0;
19203        runner.state.save().unwrap();
19204        assert!(crate::handover::can_resume(&runner.state));
19205        runner.state = RunState::load(&runner.state.id).unwrap();
19206        runner.execute_graph().await.unwrap();
19207        assert_eq!(runner.state.status, RunStatus::AlreadyInBase);
19208        assert_eq!(runner.state.pr.as_ref().unwrap().state, "closed");
19209        assert_eq!(
19210            runner.state.base_sync.as_ref().unwrap().attempts,
19211            BASE_SYNC_ROUNDS
19212        );
19213        assert!(runner.state.base_sync_recovery.authorizations.is_empty());
19214        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), head);
19215        assert!(runner.state.reviews.is_empty());
19216        assert!(runner.state.gate.is_empty());
19217    }
19218
19219    #[cfg(unix)]
19220    #[tokio::test]
19221    async fn base_recovery_authorization_requires_current_owner_free_lease_and_clean_tree() {
19222        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
19223        runner.state.driver_exited = true;
19224        runner.state.save().unwrap();
19225        let home = crate::run::home();
19226        let queue = crate::queue::Queue::open();
19227        let _claim = queue.claim(&task).unwrap();
19228        let lease = crate::driver::maintenance(&home, &runner.state.id).unwrap();
19229        assert!(
19230            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19231                .await
19232                .is_err()
19233        );
19234        drop(lease);
19235        std::fs::write(runner.state.repo.join("dirty"), "retained uncommitted work").unwrap();
19236        assert!(
19237            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19238                .await
19239                .is_err()
19240        );
19241        std::fs::remove_file(runner.state.repo.join("dirty")).unwrap();
19242        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19243            .await
19244            .unwrap();
19245        let disk = RunState::load(&runner.state.id).unwrap();
19246        assert!(disk.base_recovery_pending());
19247        assert_eq!(disk.base_sync_recovery.authorizations.len(), 1);
19248        assert!(
19249            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19250                .await
19251                .is_err()
19252        );
19253        assert_eq!(
19254            RunState::load(&runner.state.id)
19255                .unwrap()
19256                .base_sync_recovery
19257                .authorizations
19258                .len(),
19259            1
19260        );
19261        let mut owner = queue.get(&task).unwrap();
19262        owner.runs.push("20260101-000000-ffff".into());
19263        queue.put(&mut owner).unwrap();
19264        let error = Runner::authorize_base_recovery(&home, &runner.state.id, &task)
19265            .await
19266            .unwrap_err();
19267        assert!(error.to_string().contains("run task ownership changed"));
19268    }
19269
19270    #[cfg(unix)]
19271    #[tokio::test]
19272    async fn base_recovery_legacy_voting_and_repeated_resume_stay_blocked() {
19273        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
19274        let mut legacy = serde_json::to_value(&runner.state).unwrap();
19275        legacy.as_object_mut().unwrap().remove("base_sync_recovery");
19276        legacy["status"] = serde_json::json!("voting");
19277        runner.state = serde_json::from_value(legacy).unwrap();
19278        runner.state.save().unwrap();
19279        for _ in 0..3 {
19280            runner.execute_graph().await.unwrap();
19281            assert_eq!(runner.state.status, RunStatus::Blocked);
19282            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19283            assert!(!crate::handover::can_resume(&runner.state));
19284            assert_eq!(
19285                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19286                head
19287            );
19288            assert!(runner.state.reviews.is_empty());
19289            assert!(!runner.state.gate_ran);
19290        }
19291        let notice = crate::notices::run_ended(&runner.state).unwrap();
19292        let stop = runner.state.base_sync_recovery.stop.clone().unwrap();
19293        runner.state.begin_pass();
19294        runner.state.status = RunStatus::Voting;
19295        runner.deliberate().await.unwrap();
19296        runner.vote().await.unwrap();
19297        runner.finish_after_tally().await.unwrap();
19298        assert_eq!(runner.state.status, RunStatus::Blocked);
19299        assert_eq!(runner.state.base_sync_recovery.stop.as_ref(), Some(&stop));
19300        assert_eq!(
19301            crate::notices::run_ended(&runner.state).unwrap().since,
19302            notice.since
19303        );
19304    }
19305
19306    #[cfg(unix)]
19307    #[tokio::test]
19308    async fn base_recovery_never_authorizes_conflicts_publication_or_unknown_stops() {
19309        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19310        for detail in [
19311            "fix/retained conflicts with origin/main and did not rebase: conflict",
19312            "rebased fix/retained locally but origin refused the push",
19313            "unknown failure",
19314        ] {
19315            runner.state.base_sync.as_mut().unwrap().conflict = Some(detail.into());
19316            runner.state.record_base_sync_stop(&head);
19317            assert!(runner.state.authorize_base_sync(&task).is_err());
19318            runner.state.status = RunStatus::Voting;
19319            runner.execute_graph().await.unwrap();
19320            assert_eq!(runner.state.status, RunStatus::Blocked);
19321            assert!(!crate::handover::can_resume(&runner.state));
19322            assert_eq!(
19323                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19324                head
19325            );
19326        }
19327    }
19328
19329    #[tokio::test]
19330    async fn base_recovery_preparation_stop_keeps_remaining_budget() {
19331        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19332        let state = &mut runner.state;
19333        let tip = state.base_sync.as_ref().unwrap().tip.clone();
19334        let branch = state.winner().unwrap().branch.clone();
19335        state.base_sync_recovery = Default::default();
19336        state.base_sync.as_mut().unwrap().attempts = 0;
19337        state.reserve_base_operation(&head, &tip);
19338        state.finish_base_operation(None);
19339        let detail = format!(
19340            "could not rebase {branch} onto origin/main: spawn git rev-parse --git-path magi-rebase-heads: Invalid directory (os error 267)"
19341        );
19342        state.base_sync.as_mut().unwrap().conflict = Some(detail.clone());
19343        state.event("land", detail);
19344        state.record_base_sync_stop_as(&head, Some(crate::base_sync_recovery::StopKind::Unknown));
19345        assert!(state.unknown_preparation_stop(&head));
19346        let digest = state.preparation_digest(&head).unwrap();
19347        state
19348            .base_sync_recovery
19349            .operations
19350            .last_mut()
19351            .unwrap()
19352            .validated_head = Some(head.clone());
19353        assert!(!state.unknown_preparation_stop(&head));
19354        state
19355            .base_sync_recovery
19356            .operations
19357            .last_mut()
19358            .unwrap()
19359            .validated_head = None;
19360        state.task_instruction = Some(crate::queue::Queue::open().get(&task).unwrap().instruction);
19361        state.driver_exited = true;
19362        state.save().unwrap();
19363        let home = crate::run::home();
19364        let queue = crate::queue::Queue::open();
19365        let inspection = crate::repair_budget::legacy::inspect(&queue, &home, &task, &state.id)
19366            .await
19367            .unwrap();
19368        assert_eq!(inspection["classification"], "recoverable-unknown-stop");
19369        assert_eq!(inspection["evidence_digest"], digest);
19370        let request = crate::base_recovery_control::Request {
19371            run: state.id.clone(),
19372            head: head.clone(),
19373            actor: "test".into(),
19374            request: "preparation".into(),
19375            decision: None,
19376            expected_stop: None,
19377            evidence_digest: Some(digest),
19378        };
19379        let mut stale = request.clone();
19380        stale.evidence_digest = Some("stale".into());
19381        assert!(
19382            crate::base_recovery_control::recover(&queue, &home, stale)
19383                .await
19384                .is_err()
19385        );
19386        let scratch = state.dir().join("base-sync");
19387        std::fs::create_dir(&scratch).unwrap();
19388        assert!(
19389            crate::base_recovery_control::recover(&queue, &home, request.clone())
19390                .await
19391                .is_err()
19392        );
19393        std::fs::remove_dir(&scratch).unwrap();
19394        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
19395        git::git(
19396            &state.repo,
19397            &[
19398                "commit",
19399                "--allow-empty",
19400                "-m",
19401                "base advanced after inspection",
19402            ],
19403        )
19404        .await
19405        .unwrap();
19406        git::git(&state.repo, &["push", "origin", "main"])
19407            .await
19408            .unwrap();
19409        git::git(&state.repo, &["checkout", "fix/retained"])
19410            .await
19411            .unwrap();
19412        let outcome = crate::base_recovery_control::recover(&queue, &home, request.clone())
19413            .await
19414            .unwrap();
19415        assert!(!outcome.repeated);
19416        assert!(
19417            crate::base_recovery_control::recover(&queue, &home, request)
19418                .await
19419                .unwrap()
19420                .repeated
19421        );
19422        runner.state = RunState::load(&runner.state.id).unwrap();
19423        assert!(runner.state.base_recovery_pending());
19424        runner.sync_to_base().await.unwrap();
19425        assert!(!runner.state.base_sync_blocked());
19426        assert!(!runner.state.consume_base_recovery(&head));
19427        assert_eq!(runner.state.base_episode_used(), 2);
19428        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
19429        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 1);
19430        assert_eq!(runner.state.base_sync_recovery.stops.len(), 1);
19431    }
19432
19433    #[cfg(unix)]
19434    #[tokio::test]
19435    async fn base_recovery_consumption_survives_crash_without_another_attempt() {
19436        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19437        runner.state.authorize_base_sync(&task).unwrap();
19438        assert!(runner.state.consume_base_recovery(&head));
19439        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19440        runner.state.reserve_base_operation(&head, &tip);
19441        runner.state.save().unwrap();
19442        runner.state = RunState::load(&runner.state.id).unwrap();
19443        assert!(!runner.state.consume_base_recovery(&head));
19444        runner.sync_to_base().await.unwrap();
19445        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19446        assert_eq!(runner.state.base_episode_used(), 1);
19447        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
19448        assert!(
19449            runner
19450                .state
19451                .base_sync_recovery
19452                .operations
19453                .last()
19454                .unwrap()
19455                .finished
19456        );
19457        assert!(!runner.state.base_sync_blocked());
19458        runner.sync_to_base().await.unwrap();
19459        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19460    }
19461
19462    #[cfg(unix)]
19463    #[tokio::test]
19464    async fn base_recovery_legacy_authorization_and_unrecorded_wait_grant_no_interval() {
19465        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19466        // Both historical diagnostic spellings retain an exhaustion identity.
19467        let original = runner
19468            .state
19469            .base_sync
19470            .as_ref()
19471            .unwrap()
19472            .conflict
19473            .clone()
19474            .unwrap();
19475        runner.state.base_sync.as_mut().unwrap().conflict = Some(
19476            original
19477                .replace("synchronization(s)", "rebase(s)")
19478                .replace("synchronizing", "rebasing"),
19479        );
19480        runner.state.base_sync_recovery = Default::default();
19481        runner.state.record_base_sync_stop(&head);
19482        assert_eq!(
19483            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
19484            crate::base_sync_recovery::StopKind::Exhausted
19485        );
19486        runner.state.authorize_base_sync(&task).unwrap();
19487        let mut legacy = serde_json::to_value(&runner.state).unwrap();
19488        let auth = legacy["base_sync_recovery"]["authorizations"][0]
19489            .as_object_mut()
19490            .unwrap();
19491        auth.remove("interval");
19492        auth.remove("scope");
19493        runner.state = serde_json::from_value(legacy).unwrap();
19494        assert!(runner.state.consume_base_recovery(&head));
19495        assert_eq!(runner.state.base_episode_used(), 3);
19496        runner.sync_to_base().await.unwrap();
19497        assert_eq!(runner.state.base_episode_used(), 4);
19498        runner.state.resource_block = Some(crate::run::ResourceBlock {
19499            node: "gate".into(),
19500            kind: "cache".into(),
19501            detail: "legacy wait".into(),
19502            at: Timestamp::now(),
19503            cause: crate::run::ResourceBlockCause::Unrecorded,
19504        });
19505        runner.state.save().unwrap();
19506        assert!(
19507            runner
19508                .state
19509                .base_sync_recovery
19510                .episodes
19511                .last()
19512                .unwrap()
19513                .boundary
19514                .is_none()
19515        );
19516        runner.state.resource_block = None;
19517        advance_base_fixture(&runner).await;
19518        runner.sync_to_base().await.unwrap();
19519        assert!(runner.state.base_sync_blocked());
19520        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19521    }
19522
19523    #[cfg(unix)]
19524    async fn advance_base_fixture(runner: &Runner) {
19525        let repo = &runner.state.repo;
19526        for args in [
19527            vec!["checkout", "main"],
19528            vec!["commit", "--allow-empty", "-m", "base advanced"],
19529            vec!["push", "origin", "main"],
19530            vec!["checkout", "fix/retained"],
19531        ] {
19532            git::git(repo, &args).await.unwrap();
19533        }
19534    }
19535
19536    #[cfg(unix)]
19537    fn fresh_base_interval_fixture(runner: &mut Runner) {
19538        runner.state.base_sync.as_mut().unwrap().attempts = 0;
19539        runner.state.base_sync.as_mut().unwrap().conflict = None;
19540        runner.state.base_sync_recovery = Default::default();
19541        runner.state.status = RunStatus::Voting;
19542    }
19543
19544    #[cfg(unix)]
19545    #[tokio::test]
19546    async fn base_recovery_resource_boundary_requires_new_owner_and_is_single_use() {
19547        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
19548        fresh_base_interval_fixture(&mut runner);
19549        runner.state.begin_pass();
19550        runner.sync_to_base().await.unwrap();
19551        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19552        runner.state.resource_block = Some(crate::run::ResourceBlock {
19553            node: "gate".into(),
19554            kind: "build cache".into(),
19555            detail: "busy".into(),
19556            at: Timestamp::now(),
19557            cause: crate::run::ResourceBlockCause::Timeout {
19558                waited_secs: 1,
19559                limit_secs: 1,
19560            },
19561        });
19562        runner.state.save().unwrap();
19563        let queue = crate::queue::Queue::open();
19564        let mut owner = queue.get(&task).unwrap();
19565        runner.state.task_instruction = Some(owner.instruction.clone());
19566        owner.release_operator("fixture-owner", None);
19567        queue.put(&mut owner).unwrap();
19568        let approval = owner.resumption.clone().unwrap();
19569        runner.state.resource_block = None;
19570        runner.state.save().unwrap();
19571        runner.state = RunState::load(&runner.state.id).unwrap();
19572        advance_base_fixture(&runner).await;
19573        runner.sync_to_base().await.unwrap();
19574        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
19575        assert_eq!(runner.state.base_episode_used(), 1);
19576        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
19577        assert!(
19578            runner.state.base_sync_recovery.episodes[0]
19579                .boundary
19580                .as_ref()
19581                .unwrap()
19582                .consumed
19583        );
19584        assert!(
19585            !runner
19586                .state
19587                .renew_base_episode(&task, &approval, &head, "base")
19588        );
19589        for _ in 0..3 {
19590            owner.release_operator("fixture-owner", None);
19591            queue.put(&mut owner).unwrap();
19592            runner.state = RunState::load(&runner.state.id).unwrap();
19593            runner.state.begin_pass();
19594            runner.sync_to_base().await.unwrap();
19595            assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
19596            assert_eq!(runner.state.base_episode_used(), 1);
19597        }
19598        runner.state.resource_block = Some(crate::run::ResourceBlock {
19599            node: "gate".into(),
19600            kind: "disk pressure".into(),
19601            detail: "free space required".into(),
19602            at: Timestamp::now(),
19603            cause: crate::run::ResourceBlockCause::Other,
19604        });
19605        runner.state.end_pass_parked(ParkCause::Interrupt {
19606            reason: "disk pressure".into(),
19607        });
19608        runner.state.save().unwrap();
19609        owner.release_operator("fixture-owner-after-disk", None);
19610        queue.put(&mut owner).unwrap();
19611        runner.state.resource_block = None;
19612        advance_base_fixture(&runner).await;
19613        runner.sync_to_base().await.unwrap();
19614        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 3);
19615        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 3);
19616        assert_eq!(runner.state.base_episode_used(), 1);
19617        assert_eq!(runner.state.base_sync_recovery.renewals.len(), 2);
19618    }
19619
19620    #[cfg(unix)]
19621    #[tokio::test]
19622    async fn base_recovery_continuous_advancement_stops_at_four() {
19623        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
19624        fresh_base_interval_fixture(&mut runner);
19625        for spent in 1..=BASE_SYNC_ROUNDS {
19626            runner.sync_to_base().await.unwrap();
19627            assert!(!runner.state.base_sync_blocked());
19628            assert_eq!(runner.state.base_episode_used(), spent);
19629            advance_base_fixture(&runner).await;
19630        }
19631        runner.sync_to_base().await.unwrap();
19632        assert_eq!(
19633            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
19634            crate::base_sync_recovery::StopKind::Exhausted
19635        );
19636        let stop = runner.state.base_sync_recovery.stop.as_ref().unwrap();
19637        assert!(stop.unverified_sync);
19638        let action = runner.state.base_sync_next_action();
19639        assert!(action.contains("never reached its gate"));
19640        assert!(action.contains("4/4 in episode 0, 4 lifetime"));
19641        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19642        runner.state = RunState::load(&runner.state.id).unwrap();
19643        runner.sync_to_base().await.unwrap();
19644        assert_eq!(runner.state.base_episode_used(), 4);
19645        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 1);
19646    }
19647
19648    #[cfg(unix)]
19649    #[tokio::test]
19650    async fn base_recovery_stop_diagnostic_requires_synced_head_without_current_gate() {
19651        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
19652        runner.state.ensure_base_episode();
19653        // Verification progress alone is not evidence of a successful sync.
19654        runner.state.record_base_progress(&head);
19655        runner.state.base_sync_recovery.stop = None;
19656        runner.state.record_base_sync_stop(&head);
19657        assert!(
19658            !runner
19659                .state
19660                .base_sync_recovery
19661                .stop
19662                .as_ref()
19663                .unwrap()
19664                .unverified_sync
19665        );
19666
19667        runner.state.finish_base_operation(Some(&head));
19668        // A gate for another head cannot verify this synchronization.
19669        runner.state.gate_ran = true;
19670        runner.state.gate_head = Some("older-head".into());
19671        runner.state.base_sync_recovery.stop = None;
19672        runner.state.record_base_sync_stop(&head);
19673        runner.state.save().unwrap();
19674        runner.state = RunState::load(&runner.state.id).unwrap();
19675        assert!(
19676            runner
19677                .state
19678                .base_sync_recovery
19679                .stop
19680                .as_ref()
19681                .unwrap()
19682                .unverified_sync
19683        );
19684
19685        runner.state.gate_head = Some(head.clone());
19686        runner.state.base_sync_recovery.stop = None;
19687        runner.state.record_base_sync_stop(&head);
19688        assert!(
19689            !runner
19690                .state
19691                .base_sync_recovery
19692                .stop
19693                .as_ref()
19694                .unwrap()
19695                .unverified_sync
19696        );
19697        assert!(
19698            !runner
19699                .state
19700                .base_sync_next_action()
19701                .contains("never reached its gate")
19702        );
19703
19704        // Historical records cannot establish the missing synchronization evidence.
19705        let mut legacy = serde_json::to_value(&runner.state).unwrap();
19706        legacy["base_sync_recovery"]["stop"]
19707            .as_object_mut()
19708            .unwrap()
19709            .remove("unverified_sync");
19710        legacy["base_sync_recovery"]["episodes"][0]
19711            .as_object_mut()
19712            .unwrap()
19713            .remove("last_sync_head");
19714        runner.state = serde_json::from_value(legacy).unwrap();
19715        assert!(
19716            !runner
19717                .state
19718                .base_sync_recovery
19719                .stop
19720                .as_ref()
19721                .unwrap()
19722                .unverified_sync
19723        );
19724        assert!(
19725            runner.state.base_sync_recovery.episodes[0]
19726                .last_sync_head
19727                .is_none()
19728        );
19729    }
19730
19731    #[cfg(unix)]
19732    #[tokio::test]
19733    async fn base_recovery_next_action_reports_new_episode_and_pending_approval() {
19734        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19735        runner.state.authorize_base_sync(&task).unwrap();
19736        assert!(
19737            runner
19738                .state
19739                .base_sync_next_action()
19740                .contains("Approval recorded")
19741        );
19742        assert!(
19743            runner
19744                .state
19745                .base_sync_next_action()
19746                .contains("4/4 in episode 0, 4 lifetime")
19747        );
19748        assert!(runner.state.consume_base_recovery(&head));
19749        assert!(
19750            runner
19751                .state
19752                .base_sync_next_action()
19753                .contains("0/4 in episode 1, 4 lifetime")
19754        );
19755    }
19756
19757    #[cfg(unix)]
19758    #[tokio::test]
19759    async fn base_recovery_changed_head_invalidates_without_spending() {
19760        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
19761        runner.state.authorize_base_sync(&task).unwrap();
19762        git::git(
19763            &runner.state.repo,
19764            &["commit", "--allow-empty", "-m", "external head change"],
19765        )
19766        .await
19767        .unwrap();
19768        runner.sync_to_base().await.unwrap();
19769        let a = runner
19770            .state
19771            .base_sync_recovery
19772            .authorizations
19773            .last()
19774            .unwrap();
19775        assert!(a.consumed);
19776        assert!(a.invalidated.as_deref().unwrap().contains("HEAD changed"));
19777        runner.state = RunState::load(&runner.state.id).unwrap();
19778        assert!(
19779            runner
19780                .state
19781                .base_sync_next_action()
19782                .contains("Approval invalidated")
19783        );
19784        assert!(!runner.state.base_recovery_pending());
19785        assert!(runner.state.base_sync_blocked());
19786        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19787    }
19788
19789    #[cfg(unix)]
19790    #[tokio::test]
19791    async fn base_recovery_stale_fetched_base_invalidates_approval() {
19792        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19793        runner.state.driver_exited = true;
19794        runner.state.save().unwrap();
19795        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
19796            .await
19797            .unwrap();
19798        runner.state = RunState::load(&runner.state.id).unwrap();
19799        advance_base_fixture(&runner).await;
19800        runner.sync_to_base().await.unwrap();
19801        let a = runner
19802            .state
19803            .base_sync_recovery
19804            .authorizations
19805            .last()
19806            .unwrap();
19807        assert!(
19808            a.consumed
19809                && a.invalidated
19810                    .as_deref()
19811                    .unwrap()
19812                    .contains("fetched base changed")
19813        );
19814        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19815        assert_eq!(
19816            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19817            head
19818        );
19819        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
19820            .await
19821            .unwrap();
19822        runner.state = RunState::load(&runner.state.id).unwrap();
19823        runner.sync_to_base().await.unwrap();
19824        assert!(!runner.state.base_sync_blocked());
19825        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19826    }
19827
19828    #[cfg(unix)]
19829    #[tokio::test]
19830    async fn base_recovery_crash_after_git_finishes_reserved_operation_once() {
19831        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19832        runner.state.authorize_base_sync(&task).unwrap();
19833        assert!(runner.state.consume_base_recovery(&head));
19834        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19835        runner.state.reserve_base_operation(&head, &tip);
19836        runner.state.save().unwrap();
19837        let scratch = runner.state.dir().join("base-sync");
19838        assert_eq!(
19839            crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
19840                .await
19841                .unwrap(),
19842            crate::rebase::Rebased::Applied
19843        );
19844        runner.state = RunState::load(&runner.state.id).unwrap();
19845        runner.sync_to_base().await.unwrap();
19846        assert!(
19847            runner
19848                .state
19849                .base_sync_recovery
19850                .operations
19851                .last()
19852                .unwrap()
19853                .finished
19854        );
19855        assert_eq!(runner.state.base_episode_used(), 1);
19856        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19857        assert!(!runner.state.base_sync_blocked());
19858    }
19859
19860    #[cfg(unix)]
19861    #[tokio::test]
19862    async fn base_recovery_crash_preserves_untracked_files() {
19863        for ignored in [false, true] {
19864            let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19865            runner.state.authorize_base_sync(&task).unwrap();
19866            assert!(runner.state.consume_base_recovery(&head));
19867            let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19868            runner.state.reserve_base_operation(&head, &tip);
19869            runner.state.save().unwrap();
19870            let scratch = runner.state.dir().join("base-sync");
19871            assert_eq!(
19872                crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
19873                    .await
19874                    .unwrap(),
19875                crate::rebase::Rebased::Applied
19876            );
19877            let repo = &runner.state.repo;
19878            let result = git::rev_parse(repo, "HEAD").await.unwrap();
19879            assert_ne!(result, head);
19880            if ignored {
19881                let exclude = git::git(repo, &["rev-parse", "--git-path", "info/exclude"])
19882                    .await
19883                    .unwrap();
19884                std::fs::write(repo.join(exclude), "local-notes\n").unwrap();
19885            }
19886            std::fs::write(repo.join("local-notes"), "retained work\n").unwrap();
19887            assert!(
19888                git::git_raw(repo, &["diff", "--quiet", &head])
19889                    .await
19890                    .unwrap()
19891                    .ok()
19892            );
19893            // Resume after the branch moved, before its checkout was reset.
19894            runner.state = RunState::load(&runner.state.id).unwrap();
19895            runner.sync_to_base().await.unwrap();
19896            assert!(runner.state.base_sync_blocked());
19897            assert!(!runner.state.base_sync_recovery.operations[0].finished);
19898            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19899            assert_eq!(
19900                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19901                result
19902            );
19903            assert_eq!(
19904                std::fs::read_to_string(runner.state.repo.join("local-notes")).unwrap(),
19905                "retained work\n"
19906            );
19907            assert!(
19908                git::git_raw(&runner.state.repo, &["diff", "--quiet", &head])
19909                    .await
19910                    .unwrap()
19911                    .ok()
19912            );
19913        }
19914    }
19915
19916    #[cfg(unix)]
19917    #[tokio::test]
19918    async fn base_recovery_crash_does_not_adopt_foreign_commits() {
19919        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19920        runner.state.authorize_base_sync(&task).unwrap();
19921        assert!(runner.state.consume_base_recovery(&head));
19922        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19923        runner.state.reserve_base_operation(&head, &tip);
19924        runner.state.save().unwrap();
19925        let scratch = runner.state.dir().join("base-sync");
19926        crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
19927            .await
19928            .unwrap();
19929        git::sync_to_head(&runner.state.repo).await.unwrap();
19930        std::fs::write(runner.state.repo.join("foreign"), "foreign work").unwrap();
19931        git::git(&runner.state.repo, &["add", "foreign"])
19932            .await
19933            .unwrap();
19934        git::git(&runner.state.repo, &["commit", "-m", "foreign work"])
19935            .await
19936            .unwrap();
19937        let foreign_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19938        runner.state = RunState::load(&runner.state.id).unwrap();
19939        runner.sync_to_base().await.unwrap();
19940        assert!(runner.state.base_sync_blocked());
19941        assert!(
19942            !runner
19943                .state
19944                .base_sync_recovery
19945                .operations
19946                .last()
19947                .unwrap()
19948                .finished
19949        );
19950        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19951        assert_eq!(
19952            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19953            foreign_head
19954        );
19955    }
19956
19957    #[cfg(unix)]
19958    async fn paused_base_conflict_fixture() -> (tempfile::TempDir, Runner, String, String, PathBuf)
19959    {
19960        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
19961        fresh_base_interval_fixture(&mut runner);
19962        let repo = &runner.state.repo;
19963        git::git(repo, &["checkout", "main"]).await.unwrap();
19964        std::fs::write(repo.join("retained"), "upstream change\n").unwrap();
19965        git::git(repo, &["add", "retained"]).await.unwrap();
19966        git::git(repo, &["commit", "-m", "upstream retained change"])
19967            .await
19968            .unwrap();
19969        git::git(repo, &["push", "origin", "main"]).await.unwrap();
19970        let tip = git::rev_parse(repo, "HEAD").await.unwrap();
19971        git::git(repo, &["checkout", "fix/retained"]).await.unwrap();
19972        let scratch = runner.state.dir().join("base-sync");
19973        assert!(matches!(
19974            git::rebase_start(repo, &scratch, "fix/retained", &tip)
19975                .await
19976                .unwrap(),
19977            git::RebaseStart::Conflicted(_)
19978        ));
19979        runner.state.rebase_fixes.push(crate::run::RebaseFixRecord {
19980            unstarted: false,
19981            agent: "fixture".into(),
19982            paths: vec!["retained".into()],
19983            from: Some(head.clone()),
19984            onto: None,
19985            stop: Some(git::rev_parse(&scratch, "REBASE_HEAD").await.unwrap()),
19986            index_outside: None,
19987            finished: false,
19988            error: None,
19989            launcher: None,
19990            infra: None,
19991            outage: None,
19992        });
19993        (tmp, runner, head, tip, scratch)
19994    }
19995
19996    #[cfg(unix)]
19997    #[tokio::test]
19998    async fn base_recovery_imports_legacy_rebase_before_following_new_main() {
19999        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
20000        // A resource stop from before reservations existed, with resolved
20001        // contents left for the launcher's ordinary staging continuation.
20002        std::fs::write(
20003            scratch.join("retained"),
20004            "upstream and retained resolution\n",
20005        )
20006        .unwrap();
20007        runner.state.resource_block = Some(crate::run::ResourceBlock {
20008            node: "rebase".into(),
20009            kind: "repository coordination".into(),
20010            detail: "busy".into(),
20011            at: Timestamp::now(),
20012            cause: crate::run::ResourceBlockCause::Other,
20013        });
20014        runner.state.save().unwrap();
20015        // Advance the remote without moving either checkout participating
20016        // in the standing rebase.
20017        let newer = git::git(
20018            &runner.state.repo,
20019            &[
20020                "commit-tree",
20021                "main^{tree}",
20022                "-p",
20023                "main",
20024                "-m",
20025                "base advanced during wait",
20026            ],
20027        )
20028        .await
20029        .unwrap();
20030        git::git(
20031            &runner.state.repo,
20032            &[
20033                "push",
20034                "origin",
20035                &format!("{}:refs/heads/main", newer.trim()),
20036            ],
20037        )
20038        .await
20039        .unwrap();
20040        runner.state = RunState::load(&runner.state.id).unwrap();
20041        runner.state.resource_block = None;
20042        runner.sync_to_base().await.unwrap();
20043        assert!(!runner.state.base_sync_blocked());
20044        let op = &runner.state.base_sync_recovery.operations[0];
20045        assert_eq!(op.head, head);
20046        assert_eq!(op.tip, tip);
20047        assert!(op.finished);
20048        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
20049        assert_eq!(runner.state.rebase_fixes.len(), 1);
20050        let latest = git::rev_parse(&runner.state.repo, "origin/main")
20051            .await
20052            .unwrap();
20053        assert_ne!(latest, tip);
20054        runner.state = RunState::load(&runner.state.id).unwrap();
20055        runner.sync_to_base().await.unwrap();
20056        assert!(!runner.state.base_sync_blocked());
20057        assert_eq!(runner.state.base_sync_recovery.operations.len(), 2);
20058        assert_eq!(runner.state.base_sync_recovery.operations[1].tip, latest);
20059        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
20060    }
20061
20062    #[cfg(unix)]
20063    #[tokio::test]
20064    async fn base_recovery_resumes_exact_validated_conflict_result_after_crash() {
20065        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
20066        runner.state.reserve_base_operation(&head, &tip);
20067        runner.state.save().unwrap();
20068        std::fs::write(
20069            scratch.join("retained"),
20070            "upstream and retained resolution\n",
20071        )
20072        .unwrap();
20073        git::git(&scratch, &["add", "retained"]).await.unwrap();
20074        git::git(
20075            &scratch,
20076            &["-c", "core.editor=true", "rebase", "--continue"],
20077        )
20078        .await
20079        .unwrap();
20080        let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
20081        assert!(
20082            !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
20083                .await
20084                .unwrap()
20085                .is_empty()
20086        );
20087        assert_eq!(
20088            crate::rebase::finish(
20089                &mut runner.state,
20090                &scratch,
20091                "fix/retained",
20092                &head,
20093                &tip,
20094                &["retained".into()],
20095                ""
20096            )
20097            .await
20098            .unwrap(),
20099            crate::rebase::Rebased::Applied
20100        );
20101        assert!(!scratch.exists());
20102        // Simulate losing the caller before finish_base_operation/save.
20103        runner.state = RunState::load(&runner.state.id).unwrap();
20104        let op = &runner.state.base_sync_recovery.operations[0];
20105        assert!(!op.finished);
20106        assert_eq!(op.validated_head.as_deref(), Some(result.as_str()));
20107        runner.sync_to_base().await.unwrap();
20108        assert!(!runner.state.base_sync_blocked());
20109        assert!(runner.state.base_sync_recovery.operations[0].finished);
20110        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
20111        assert_eq!(runner.state.rebase_fixes.len(), 1);
20112        let winner = runner.state.winner().unwrap().clone();
20113        let wait = runner.repository_wait();
20114        assert!(
20115            verify_current_head(&mut runner.state, &winner, &wait)
20116                .await
20117                .unwrap()
20118        );
20119        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
20120    }
20121
20122    #[cfg(unix)]
20123    #[tokio::test]
20124    async fn base_recovery_revalidates_completed_scratch_before_validation_save() {
20125        for damage in [None, Some("record"), Some("foreign"), Some("dirty")] {
20126            let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
20127            runner.state.reserve_base_operation(&head, &tip);
20128            runner.state.save().unwrap();
20129            std::fs::write(
20130                scratch.join("retained"),
20131                "upstream and retained resolution\n",
20132            )
20133            .unwrap();
20134            git::git(&scratch, &["add", "retained"]).await.unwrap();
20135            git::git(
20136                &scratch,
20137                &["-c", "core.editor=true", "rebase", "--continue"],
20138            )
20139            .await
20140            .unwrap();
20141            let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
20142            assert!(!git::rebase_in_progress(&scratch).await);
20143            assert!(
20144                !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
20145                    .await
20146                    .unwrap()
20147                    .is_empty()
20148            );
20149            match damage {
20150                Some("record") => {
20151                    let path =
20152                        git::git(&scratch, &["rev-parse", "--git-path", "magi-rebase-heads"])
20153                            .await
20154                            .unwrap();
20155                    std::fs::write(scratch.join(path), "").unwrap();
20156                }
20157                Some("foreign") => {
20158                    std::fs::write(scratch.join("foreign"), "foreign work").unwrap();
20159                    git::git(&scratch, &["add", "foreign"]).await.unwrap();
20160                    git::git(&scratch, &["commit", "-m", "foreign work"])
20161                        .await
20162                        .unwrap();
20163                }
20164                Some("dirty") => {
20165                    std::fs::write(scratch.join("retained"), "uncommitted work").unwrap();
20166                }
20167                _ => {}
20168            }
20169            let retained_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20170            // Crash immediately after Git continuation, before finish runs.
20171            runner.state = RunState::load(&runner.state.id).unwrap();
20172            assert!(
20173                runner.state.base_sync_recovery.operations[0]
20174                    .validated_head
20175                    .is_none()
20176            );
20177            runner.sync_to_base().await.unwrap();
20178            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
20179            assert_eq!(runner.state.base_episode_used(), 1);
20180            assert_eq!(runner.state.rebase_fixes.len(), 1);
20181            assert_eq!(
20182                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
20183                retained_head
20184            );
20185            if damage.is_some() {
20186                assert!(runner.state.base_sync_blocked());
20187                assert!(scratch.exists());
20188                assert!(!runner.state.base_sync_recovery.operations[0].finished);
20189                assert!(
20190                    runner.state.base_sync_recovery.operations[0]
20191                        .validated_head
20192                        .is_none()
20193                );
20194            } else {
20195                assert!(!runner.state.base_sync_blocked());
20196                assert!(!scratch.exists());
20197                assert!(runner.state.base_sync_recovery.operations[0].finished);
20198                assert_eq!(
20199                    runner.state.base_sync_recovery.operations[0]
20200                        .validated_head
20201                        .as_deref(),
20202                    Some(result.as_str())
20203                );
20204                let winner = runner.state.winner().unwrap().clone();
20205                let wait = runner.repository_wait();
20206                assert!(
20207                    verify_current_head(&mut runner.state, &winner, &wait)
20208                        .await
20209                        .unwrap()
20210                );
20211                assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
20212                runner.state = RunState::load(&runner.state.id).unwrap();
20213                runner.sync_to_base().await.unwrap();
20214                assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
20215            }
20216        }
20217    }
20218
20219    #[cfg(unix)]
20220    async fn resumed_gate_fixture() -> (tempfile::TempDir, Runner, String) {
20221        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
20222        // This is an ordinary gate stop, not an authorized base-budget recovery.
20223        runner.state.prep_complete = Some(true);
20224        runner.state.base_sync = None;
20225        runner.state.base_sync_recovery = Default::default();
20226        runner.state.config.graph.gate_fix_rounds = 1;
20227        let mut review = review_round(true, 0, 1, 1, false, true);
20228        review.head = head.clone();
20229        review.verified_head = Some(head.clone());
20230        runner.state.reviews = vec![review];
20231        runner.state.gate = vec![CommandOutcome {
20232            command: "old gate".into(),
20233            code: Some(1),
20234            output_tail: "old failure".into(),
20235            duration_ms: 0,
20236            resource_blocked: false,
20237            ..Default::default()
20238        }];
20239        runner.state.gate_head = Some(head.clone());
20240        runner.state.gate_ran = true;
20241        runner.state.gate_fixes = vec![crate::run::GateFixRecord {
20242            agent: "fixture".into(),
20243            failed: runner.state.gate.clone(),
20244            notes: "spent".into(),
20245            committed: false,
20246            error: None,
20247        }];
20248        runner.state.land_approval = Some(crate::run::LandApproval {
20249            question: "old approval".into(),
20250            head: head.clone(),
20251        });
20252        runner.state.status = RunStatus::Blocked;
20253        (tmp, runner, head)
20254    }
20255
20256    #[cfg(unix)]
20257    #[tokio::test]
20258    async fn current_head_e2e_keeps_synchronized_base_when_tracking_ref_moves() {
20259        let (_tmp, mut runner, _) = resumed_gate_fixture().await;
20260        runner.sync_to_base().await.unwrap();
20261        let winner = runner.state.winner().unwrap().clone();
20262        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
20263        let base = runner.state.base_sync.as_ref().unwrap().tip.clone();
20264        assert_ne!(head, base);
20265        runner.state.config.verify.e2e = vec![format!(
20266            "git update-ref refs/remotes/origin/main {head} && false"
20267        )];
20268        let wait = repository_wait(&runner.state, None);
20269        assert!(
20270            !verify_current_head(&mut runner.state, &winner, &wait)
20271                .await
20272                .unwrap()
20273        );
20274        assert_eq!(
20275            git::rev_parse(&runner.state.repo, "refs/remotes/origin/main")
20276                .await
20277                .unwrap(),
20278            head
20279        );
20280        assert_eq!(
20281            runner
20282                .state
20283                .head_e2e
20284                .as_ref()
20285                .unwrap()
20286                .base_commit
20287                .as_deref(),
20288            Some(base.as_str())
20289        );
20290    }
20291
20292    #[cfg(unix)]
20293    #[tokio::test]
20294    async fn resumed_gate_rebase_verifies_new_head_without_refilling_repairs() {
20295        for (e2e_ok, gate_ok) in [(true, true), (true, false), (false, true)] {
20296            let (tmp, mut runner, old) = resumed_gate_fixture().await;
20297            let phases = tmp.path().join("phases");
20298            runner.state.config.verify.e2e = vec![format!(
20299                "echo e2e >> '{}'; {}",
20300                phases.display(),
20301                if e2e_ok {
20302                    "true"
20303                } else {
20304                    "echo new-e2e-failure; false"
20305                }
20306            )];
20307            runner.state.config.verify.gate = vec![format!(
20308                "echo gate >> '{}'; {}",
20309                phases.display(),
20310                if gate_ok {
20311                    "true"
20312                } else {
20313                    "echo new-gate-failure; false"
20314                }
20315            )];
20316            runner.state.save().unwrap();
20317            runner.state = RunState::load(&runner.state.id).unwrap();
20318            runner.sync_to_base().await.unwrap();
20319            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20320            assert_ne!(head, old);
20321            // Reentry after Git updated but before verification was invalidated.
20322            runner.state = RunState::load(&runner.state.id).unwrap();
20323            runner.execute_graph().await.unwrap();
20324            assert_eq!(runner.state.gate_fixes.len(), 1);
20325            assert_eq!(runner.state.reviews.len(), 1);
20326            assert_eq!(runner.state.reviews[0].head, old);
20327            assert_eq!(runner.state.land_approval.as_ref().unwrap().head, old);
20328            assert_eq!(runner.state.verification_history.len(), 1);
20329            let history = &runner.state.verification_history[0];
20330            assert_eq!(history.gate_head.as_deref(), Some(old.as_str()));
20331            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
20332            assert!(history.archived_at.is_some());
20333            assert_eq!(history.fixes_spent, Some(1));
20334            assert_eq!(history.gate[0].output_tail, "old failure");
20335            let archive_events: Vec<_> = runner
20336                .state
20337                .events
20338                .iter()
20339                .filter(|e| e.node == "gate" && e.message.starts_with("archived gate on "))
20340                .collect();
20341            assert_eq!(archive_events.len(), 1);
20342            assert!(archive_events[0].message.contains(&short(&old)));
20343            assert!(archive_events[0].message.contains(&short(&head)));
20344            assert!(
20345                archive_events[0]
20346                    .message
20347                    .contains("1 gate-fix round(s) already spent stay spent")
20348            );
20349            assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, head);
20350            assert_eq!(runner.state.head_e2e.as_ref().unwrap().passed, e2e_ok);
20351            if e2e_ok {
20352                assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
20353                assert_eq!(runner.state.gate_allows_progress(), gate_ok);
20354            } else {
20355                assert!(!runner.state.gate_ran);
20356            }
20357            assert_eq!(
20358                runner.state.status,
20359                if e2e_ok && gate_ok {
20360                    RunStatus::Ready
20361                } else {
20362                    RunStatus::Blocked
20363                }
20364            );
20365            if !e2e_ok || !gate_ok {
20366                let cause = runner.state.verification_blocking_cause().unwrap();
20367                assert!(cause.contains(&head));
20368                assert!(cause.contains(if e2e_ok { "gate failed" } else { "e2e failed" }));
20369                // A later successful progress event must not become the cause.
20370                runner.state.event("land", "rebased successfully");
20371                let notice = crate::notices::run_ended(&runner.state).unwrap();
20372                assert!(!format!("{notice:?}").contains("rebased successfully"));
20373                assert!(runner.state.merge.is_none());
20374            }
20375            let before = std::fs::read_to_string(&phases).unwrap();
20376            runner.state.save().unwrap();
20377            runner.state = RunState::load(&runner.state.id).unwrap();
20378            runner.review_loop().await.unwrap();
20379            runner.gate().await.unwrap();
20380            assert_eq!(std::fs::read_to_string(&phases).unwrap(), before);
20381            assert_eq!(runner.state.verification_history.len(), 1);
20382            let history = &runner.state.verification_history[0];
20383            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
20384            assert!(history.archived_at.is_some());
20385            assert_eq!(history.fixes_spent, Some(1));
20386        }
20387    }
20388
20389    #[cfg(unix)]
20390    #[tokio::test]
20391    async fn resumed_gate_unchanged_head_keeps_failure_and_unknown_head_rechecks() {
20392        let (tmp, mut runner, head) = resumed_gate_fixture().await;
20393        let marker = tmp.path().join("gate-ran");
20394        runner.state.config.verify.gate = vec![format!("touch '{}'", marker.display())];
20395        runner.review_loop().await.unwrap();
20396        runner.gate().await.unwrap();
20397        assert_eq!(runner.state.status, RunStatus::Blocked);
20398        assert!(!marker.exists());
20399        assert!(runner.state.verification_history.is_empty());
20400        runner.state.gate_head = None;
20401        runner.gate().await.unwrap();
20402        assert!(marker.exists());
20403        assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
20404        assert_eq!(runner.state.verification_history.len(), 1);
20405        assert_eq!(runner.state.gate_fixes.len(), 1);
20406    }
20407
20408    #[cfg(unix)]
20409    #[tokio::test]
20410    async fn resumed_gate_pending_e2e_retries_without_spending_or_landing() {
20411        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
20412        runner.sync_to_base().await.unwrap();
20413        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20414        runner.state.reconcile_verification_head(&head);
20415        // Both crash-before-command and resource wait are unresolved evidence.
20416        for outcomes in [
20417            Vec::new(),
20418            vec![CommandOutcome {
20419                command: "true".into(),
20420                code: None,
20421                output_tail: "cache unavailable".into(),
20422                duration_ms: 0,
20423                resource_blocked: true,
20424                ..Default::default()
20425            }],
20426        ] {
20427            runner.state.head_e2e = Some(crate::run::GateRepairE2e::new(
20428                head.clone(),
20429                false,
20430                outcomes,
20431            ));
20432            runner.state.gate_ran = false;
20433            runner.state.gate.clear();
20434            runner.state.save().unwrap();
20435            runner.state = RunState::load(&runner.state.id).unwrap();
20436            runner.merge().await.unwrap();
20437            assert!(runner.state.merge.is_none());
20438            runner.review_loop().await.unwrap();
20439            runner.gate().await.unwrap();
20440            assert!(runner.state.head_e2e.as_ref().unwrap().passed);
20441            assert!(runner.state.gate_allows_progress());
20442            assert_eq!(runner.state.gate_fixes.len(), 1);
20443            assert!(runner.state.merge.is_none());
20444        }
20445        // Moving the winner after a successful gate cannot publish an unchecked SHA.
20446        git::git(
20447            &runner.state.repo,
20448            &["commit", "--allow-empty", "-m", "external update"],
20449        )
20450        .await
20451        .unwrap();
20452        runner.merge().await.unwrap();
20453        assert!(runner.state.merge.is_none());
20454        assert_eq!(runner.state.status, RunStatus::Blocked);
20455    }
20456
20457    #[cfg(unix)]
20458    #[tokio::test]
20459    async fn resumed_gate_resource_waits_preserve_budget_and_retry_on_reentry() {
20460        for waiting_on_gate in [false, true] {
20461            let (tmp, mut runner, _old) = resumed_gate_fixture().await;
20462            runner.sync_to_base().await.unwrap();
20463            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20464            runner.state.reconcile_verification_head(&head);
20465            if waiting_on_gate {
20466                runner.state.head_e2e = Some(crate::run::GateRepairE2e::new(
20467                    head.clone(),
20468                    true,
20469                    Vec::new(),
20470                ));
20471            }
20472            let cache = tmp.path().join("cache");
20473            runner.state.config.verify.e2e =
20474                vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
20475            runner.state.config.verify.gate = vec!["true".into()];
20476            runner.state.config.graph.timeout_resource_wait = 1;
20477            let owner =
20478                crate::cache::Owner::here("other", "e2e", "e2e", &runner.state.repo, "other-head");
20479            let guard =
20480                match crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap() {
20481                    crate::cache::AcquireOutcome::Acquired(g) => g,
20482                    crate::cache::AcquireOutcome::Busy(b) => panic!("unexpected busy cache: {b:?}"),
20483                };
20484            runner.review_loop().await.unwrap();
20485            runner.gate().await.unwrap();
20486            assert!(!runner.state.gate_ran);
20487            assert_eq!(runner.state.gate_fixes.len(), 1);
20488            assert!(runner.state.resource_block.is_some());
20489            runner.merge().await.unwrap();
20490            assert!(runner.state.merge.is_none());
20491            drop(guard);
20492            runner.state = RunState::load(&runner.state.id).unwrap();
20493            // The driver clears the previous pass's resource stop on resume.
20494            runner.state.resource_block = None;
20495            runner.review_loop().await.unwrap();
20496            runner.gate().await.unwrap();
20497            assert!(runner.state.gate_allows_progress());
20498            assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
20499            assert_eq!(runner.state.gate_fixes.len(), 1);
20500        }
20501    }
20502
20503    #[cfg(unix)]
20504    #[tokio::test]
20505    async fn resumed_gate_pre_gate_head_change_and_review_holds() {
20506        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
20507        runner.sync_to_base().await.unwrap();
20508        let before = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20509        runner.state.config.verify.pre_gate = vec!["echo mechanical > mechanical".into()];
20510        // Verification passes before pre_gate and fails on the mechanically changed head.
20511        runner.state.config.verify.e2e = vec!["test ! -f mechanical".into()];
20512        runner.review_loop().await.unwrap();
20513        runner.gate().await.unwrap();
20514        let after = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20515        assert_ne!(before, after);
20516        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, after);
20517        assert!(!runner.state.head_e2e.as_ref().unwrap().passed);
20518        assert!(!runner.state.gate_allows_progress());
20519        runner.merge().await.unwrap();
20520        assert!(runner.state.merge.is_none());
20521        assert!(
20522            runner
20523                .state
20524                .verification_history
20525                .iter()
20526                .any(|h| h.e2e.as_ref().is_some_and(|e| e.head == before && e.passed))
20527        );
20528
20529        // An incomplete review is still an independent hold on a changed head.
20530        runner.state.reviews[0].clean = false;
20531        runner.state.reviews[0].answered = 0;
20532        runner.state.config.verify.e2e = vec!["true".into()];
20533        runner.review_loop().await.unwrap();
20534        runner.gate().await.unwrap();
20535        runner.merge().await.unwrap();
20536        assert_eq!(runner.state.status, RunStatus::Blocked);
20537        assert!(runner.state.merge.is_none());
20538        assert!(
20539            runner
20540                .state
20541                .verification_blocking_cause()
20542                .unwrap()
20543                .contains("review blocked")
20544        );
20545    }
20546
20547    #[cfg(unix)]
20548    #[tokio::test]
20549    async fn resumed_gate_cannot_certify_a_head_changed_by_its_command() {
20550        let (_tmp, mut runner, old) = resumed_gate_fixture().await;
20551        runner.state.gate_head = None;
20552        runner.state.config.verify.gate =
20553            vec!["git -c commit.gpgsign=false commit --allow-empty -m 'gate changed head'".into()];
20554        runner.review_loop().await.unwrap();
20555        runner.gate().await.unwrap();
20556        assert_ne!(
20557            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
20558            old
20559        );
20560        assert_eq!(runner.state.gate_head.as_deref(), Some(old.as_str()));
20561        assert!(!runner.state.gate_allows_progress());
20562        assert_eq!(runner.state.status, RunStatus::Blocked);
20563        runner.merge().await.unwrap();
20564        assert!(runner.state.merge.is_none());
20565    }
20566
20567    #[cfg(unix)]
20568    #[tokio::test]
20569    async fn base_recovery_success_requires_new_review_e2e_and_gate() {
20570        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
20571        let mut old_review = review_round(true, 0, 1, 1, false, true);
20572        old_review.head = head.clone();
20573        old_review.verified_head = Some(head.clone());
20574        runner.state.reviews = vec![old_review];
20575        runner.state.gate = vec![CommandOutcome {
20576            command: "old gate".into(),
20577            code: None,
20578            output_tail: "timed out after 2400s".into(),
20579            duration_ms: 2_400_000,
20580            resource_blocked: false,
20581            ..Default::default()
20582        }];
20583        runner.state.gate_ran = true;
20584        runner.state.gate_head = Some(head.clone());
20585        runner.state.land_approval = Some(crate::run::LandApproval {
20586            question: "old-head-approval".into(),
20587            head: head.clone(),
20588        });
20589        runner.state.authorize_base_sync(&task).unwrap();
20590        runner.sync_to_base().await.unwrap();
20591        assert!(!runner.state.base_sync_blocked());
20592        let fresh = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20593        assert_ne!(head, fresh);
20594        assert_eq!(runner.state.reviews.len(), 1);
20595        assert!(!runner.state.gate_ran);
20596        let saved = &runner.state.base_sync_recovery.authorizations[0];
20597        assert_eq!(saved.reviews[0].head, head);
20598        assert_eq!(saved.gate_head.as_deref(), Some(head.as_str()));
20599        assert!(saved.gate_ran);
20600        assert!(!saved.gate[0].ok());
20601        runner.review_loop().await.unwrap();
20602        runner.gate().await.unwrap();
20603        assert_eq!(runner.state.reviews[0].head, head);
20604        assert_eq!(
20605            runner.state.reviews[0].verified_head.as_deref(),
20606            Some(head.as_str())
20607        );
20608        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, fresh);
20609        assert!(runner.state.head_e2e.as_ref().unwrap().passed);
20610        assert_eq!(runner.state.gate_head.as_deref(), Some(fresh.as_str()));
20611        assert!(runner.state.gate_ran);
20612        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
20613        assert_eq!(runner.state.land_approval.as_ref().unwrap().head, head);
20614        assert_ne!(runner.state.land_approval.as_ref().unwrap().head, fresh);
20615        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
20616        assert_eq!(
20617            std::fs::read_to_string(runner.state.repo.join("retained")).unwrap(),
20618            "retained change"
20619        );
20620    }
20621
20622    #[cfg(unix)]
20623    #[tokio::test]
20624    async fn base_recovery_moving_base_uses_bounded_authorized_interval() {
20625        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
20626        let queue = crate::queue::Queue::open();
20627        let mut owner = queue.get(&task).unwrap();
20628        owner.release_operator("test-resume", None);
20629        queue.put(&mut owner).unwrap();
20630        let generation = owner.resumption.as_ref().unwrap().generation;
20631        runner.state.task_instruction = Some(owner.instruction.clone());
20632        runner.state.driver_exited = true;
20633        runner.state.save().unwrap();
20634        let home = crate::run::home();
20635        let _claim = queue.claim(&task).unwrap();
20636        owner.resumption.as_mut().unwrap().at =
20637            runner.state.base_sync_recovery.stop.as_ref().unwrap().at;
20638        queue.put(&mut owner).unwrap();
20639        assert!(
20640            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20641                .await
20642                .is_err(),
20643            "an approval from before the stop grants nothing"
20644        );
20645        owner.resumption.as_mut().unwrap().at = Timestamp::now();
20646        queue.put(&mut owner).unwrap();
20647        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20648            .await
20649            .unwrap();
20650        assert!(
20651            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20652                .await
20653                .is_err()
20654        );
20655        runner.state = RunState::load(&runner.state.id).unwrap();
20656        assert_eq!(
20657            runner.state.base_sync_recovery.authorizations[0].generation,
20658            Some(generation)
20659        );
20660        runner.sync_to_base().await.unwrap();
20661        let repo = runner.state.repo.clone();
20662        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
20663        git::git(&repo, &["checkout", "main"]).await.unwrap();
20664        std::fs::write(repo.join("base-change"), "base moved again").unwrap();
20665        git::git(&repo, &["add", "."]).await.unwrap();
20666        git::git(&repo, &["commit", "-m", "move base again"])
20667            .await
20668            .unwrap();
20669        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
20670        git::git(&repo, &["checkout", "fix/retained"])
20671            .await
20672            .unwrap();
20673        runner.sync_to_base().await.unwrap();
20674        assert!(!runner.state.base_sync_blocked());
20675        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
20676        assert_eq!(runner.state.base_episode_used(), 2);
20677        let fresh = git::rev_parse(&repo, "HEAD").await.unwrap();
20678        assert_ne!(fresh, head);
20679        assert!(!runner.state.base_recovery_pending());
20680        // Even replaying the generation with a later timestamp grants nothing.
20681        owner.resumption.as_mut().unwrap().at = Timestamp::now();
20682        queue.put(&mut owner).unwrap();
20683        assert!(
20684            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20685                .await
20686                .is_err()
20687        );
20688        runner.state = RunState::load(&runner.state.id).unwrap();
20689        runner.sync_to_base().await.unwrap();
20690        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
20691        assert_eq!(runner.state.base_sync_recovery.authorizations.len(), 1);
20692        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), fresh);
20693    }
20694
20695    #[cfg(unix)]
20696    #[tokio::test]
20697    async fn base_recovery_tally_skips_deliberation_and_voting_without_a_sync_stop() {
20698        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
20699        runner.state.base_sync = None;
20700        runner.state.status = RunStatus::Blocked;
20701        let mut second = runner.state.candidates[0].clone();
20702        second.label = 'B';
20703        runner.state.candidates.push(second);
20704        assert!(runner.state.votes.is_empty());
20705        assert!(runner.state.deliberation.is_empty());
20706        runner.deliberate().await.unwrap();
20707        runner.vote().await.unwrap();
20708        assert_eq!(runner.state.status, RunStatus::Blocked);
20709        assert!(runner.state.votes.is_empty());
20710        assert!(runner.state.deliberation.is_empty());
20711    }
20712
20713    /// A minimal, git-free `Runner` at a given status — `settle_questions`
20714    /// reads nothing else off it.
20715    fn runner_at(status: RunStatus) -> Runner {
20716        let mut state = RunState::new(
20717            PathBuf::from("/nonexistent/repo"),
20718            "main".to_owned(),
20719            "deadbeef".to_owned(),
20720            "task".to_owned(),
20721            Config::default(),
20722        );
20723        // These fixtures test execution flow, independent of host disk capacity.
20724        state.config.disk.min_free_bytes = 0;
20725        // These fixtures share one home and save concurrently. Short clock
20726        // IDs can collide, making an ownership test read another test's run.
20727        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
20728        state.id = format!(
20729            "20000101-000000-{:04x}",
20730            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
20731        );
20732        state.status = status;
20733        Runner {
20734            state,
20735            roles: ResolvedRoles {
20736                implementers: Vec::new(),
20737                judges: Vec::new(),
20738                reviewers: Vec::new(),
20739                fixer: None,
20740                conductor: conductor(),
20741                implementer_roster: Vec::new(),
20742                judge_roster: Vec::new(),
20743                reviewer_roster: Vec::new(),
20744            },
20745            sem: Arc::new(Semaphore::new(1)),
20746            pause: Pause::new(),
20747            interrupt: Pause::new(),
20748        }
20749    }
20750
20751    #[tokio::test]
20752    async fn targeted_fix_refuses_independent_ownership_conflicts() {
20753        crate::run::pin_test_home();
20754        let home = crate::run::home();
20755        let mut runner = runner_at(RunStatus::Ready);
20756        runner.state.driver_exited = true;
20757        runner.state.save().unwrap();
20758        let id = runner.state.id.clone();
20759        let path = runner.state.dir().join("run.json");
20760        let ids = ["R1-1-1".into()];
20761        let lease = crate::driver::maintenance(&home, &id).unwrap();
20762        for (guard, expected) in [
20763            (Some(lease), "currently being worked on"),
20764            (None, "ownership is being updated"),
20765        ] {
20766            let owner = if guard.is_none() {
20767                Some(crate::pr_head::owner_lock(&home, &id).unwrap())
20768            } else {
20769                None
20770            };
20771            let before = std::fs::read(&path).unwrap();
20772            let err = runner
20773                .fix_selected(&ids, "ownership conflict", false)
20774                .await
20775                .unwrap_err();
20776            assert!(format!("{err:#}").contains(expected), "{err:#}");
20777            assert_eq!(std::fs::read(&path).unwrap(), before);
20778            assert!(!runner.state.dir().join("fix.lock").exists());
20779            drop(owner);
20780            drop(guard);
20781        }
20782        let mut disk = RunState::load(&id).unwrap();
20783        disk.driver_exited = false;
20784        disk.driver_pid = Some(std::process::id());
20785        disk.driver_started_at = Some(crate::proc::process_started_at(std::process::id()).unwrap());
20786        disk.save().unwrap();
20787        assert_eq!(
20788            disk.liveness_under(&home, false),
20789            crate::run::Liveness::Live
20790        );
20791        let before = std::fs::read(&path).unwrap();
20792        let err = runner
20793            .fix_selected(&ids, "live driver", false)
20794            .await
20795            .unwrap_err();
20796        assert!(
20797            err.to_string().contains("currently being worked on"),
20798            "{err:#}"
20799        );
20800        assert_eq!(std::fs::read(&path).unwrap(), before);
20801        assert!(!runner.state.dir().join("fix.lock").exists());
20802        disk.driver_exited = true;
20803        disk.driver_pid = None;
20804        disk.driver_started_at = None;
20805        disk.status = RunStatus::Reviewing;
20806        disk.save().unwrap();
20807        let before = std::fs::read(&path).unwrap();
20808        let err = runner
20809            .fix_selected(&ids, "stale state", false)
20810            .await
20811            .unwrap_err();
20812        assert!(
20813            err.to_string().contains("run changed since it was loaded"),
20814            "{err:#}"
20815        );
20816        assert_eq!(std::fs::read(&path).unwrap(), before);
20817        assert!(!runner.state.dir().join("fix.lock").exists());
20818        assert!(runner.state.operator_fixes.is_empty());
20819    }
20820
20821    #[tokio::test]
20822    async fn targeted_fix_preflight_releases_owner_and_cancellation_releases_claims() {
20823        use std::future::Future;
20824        use std::task::Poll;
20825
20826        crate::run::pin_test_home();
20827        let home = crate::run::home();
20828        let repo = tempfile::tempdir().unwrap();
20829        let mut runner = runner_at(RunStatus::Ready);
20830        runner.state.repo = repo.path().to_path_buf();
20831        runner.state.driver_exited = true;
20832        runner.state.candidates.push(Candidate {
20833            index: 0,
20834            label: 'A',
20835            agent: "mock".into(),
20836            branch: "magi/test/A".into(),
20837            worktree: repo.path().join("wt"),
20838            summary: String::new(),
20839            stat: String::new(),
20840            files: 0,
20841            commits: 0,
20842            empty: false,
20843            failed: None,
20844            verified_noop: None,
20845            duration_ms: 0,
20846            folded: false,
20847        });
20848        runner.state.tally = Some(Tally {
20849            first_choice: BTreeMap::from([('A', 1)]),
20850            borda: BTreeMap::new(),
20851            winner: 'A',
20852            rankings: 1,
20853            unanimous_initial: true,
20854            deliberated: false,
20855            changed_votes: 0,
20856            unanimous_final: true,
20857            tie_break: None,
20858            judges: 1,
20859            present: 1,
20860            quorum: 1,
20861            met_quorum: true,
20862            uncontested: None,
20863        });
20864        runner.state.save().unwrap();
20865        let id = runner.state.id.clone();
20866        let dir = runner.state.dir();
20867        let before = std::fs::read(dir.join("run.json")).unwrap();
20868        let ids = ["R1-1-1".into()];
20869        let mut fix = Box::pin(runner.fix_selected(&ids, "preflight lock check", false));
20870        std::future::poll_fn(|cx| match fix.as_mut().poll(cx) {
20871            Poll::Pending => Poll::Ready(()),
20872            Poll::Ready(result) => panic!("preflight completed without yielding: {result:?}"),
20873        })
20874        .await;
20875        assert!(FixClaim::acquire(&dir).is_err());
20876        assert!(crate::driver::maintenance(&home, &id).is_err());
20877        drop(crate::pr_head::owner_lock(&home, &id).unwrap());
20878        drop(fix);
20879        assert!(FixClaim::acquire(&dir).is_ok());
20880        assert!(crate::driver::maintenance(&home, &id).is_ok());
20881        assert_eq!(std::fs::read(dir.join("run.json")).unwrap(), before);
20882    }
20883
20884    #[tokio::test]
20885    async fn source_eviction_resume_restores_before_graph_shortcuts_and_setup() {
20886        crate::run::pin_test_home();
20887        let temp = tempfile::tempdir().unwrap();
20888        let root = temp.path().canonicalize().unwrap();
20889        let repo = root.join("repo");
20890        std::fs::create_dir(&repo).unwrap();
20891        init_repo(&repo);
20892        git::git(&repo, &["config", "core.autocrlf", "false"])
20893            .await
20894            .unwrap();
20895        let mut runner = runner_at(RunStatus::Blocked);
20896        runner.state.repo = repo.clone();
20897        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
20898        runner.state.config.agents = vec![conductor()];
20899        runner.state.config.graph.selected_implementer = Some("conductor".into());
20900        runner.state.config.graph.worktree_root = Some(root.join("worktrees"));
20901        let (shell, command, setup_output) = if cfg!(windows) {
20902            (
20903                vec!["cmd".into(), "/C".into()],
20904                "echo ready>seat-ready",
20905                "ready\r\n",
20906            )
20907        } else {
20908            (
20909                vec!["sh".into(), "-c".into()],
20910                "printf ready > seat-ready",
20911                "ready",
20912            )
20913        };
20914        runner.state.config.verify.shell = Some(shell);
20915        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
20916            run: Some(command.into()),
20917            ..Default::default()
20918        }];
20919        runner.state.save().unwrap();
20920        let path = runner.state.worktree_root().join("judge-1");
20921        git::worktree_add_detached(&repo, &path, &runner.state.base_commit)
20922            .await
20923            .unwrap();
20924        std::fs::write(path.join("checkpoint"), "unrelated seat").unwrap();
20925        git::git(&path, &["add", "."]).await.unwrap();
20926        let tree = git::git(&path, &["write-tree"]).await.unwrap();
20927        let head = git::git(&path, &["commit-tree", &tree, "-m", "seat checkpoint"])
20928            .await
20929            .unwrap();
20930        git::git(&path, &["checkout", "--detach", &head])
20931            .await
20932            .unwrap();
20933        let evidence = crate::fold_evidence::snapshot(
20934            &runner.state,
20935            &crate::run::home().canonicalize().unwrap(),
20936            &head,
20937            64 * 1024 * 1024,
20938        )
20939        .await
20940        .unwrap();
20941        let mut contents = BTreeMap::new();
20942        contents.insert(
20943            repo.join("logs/HEAD"),
20944            format!("{head} {head} fixture\n").into_bytes(),
20945        );
20946        let record = serde_json::json!({
20947            "version":1, "run":runner.state.id, "source":path, "head":head,
20948            "evidence":evidence, "admin":{}, "admin_contents":contents,
20949            "history":{head.clone():evidence}, "phase":"evicted"
20950        });
20951        std::fs::write(
20952            runner.state.dir().join("artifacts/eviction-judge-1.json"),
20953            serde_json::to_vec(&record).unwrap(),
20954        )
20955        .unwrap();
20956        assert!(git::worktree_remove_clean(&repo, &path).await.unwrap());
20957        git::git(&repo, &["reflog", "expire", "--expire=now", "--all"])
20958            .await
20959            .unwrap();
20960        git::git(&repo, &["gc", "--prune=now"]).await.unwrap();
20961        assert!(
20962            !git::git_raw(&repo, &["cat-file", "-e", &head])
20963                .await
20964                .unwrap()
20965                .ok()
20966        );
20967        let mut resumed = Runner::resume(&runner.state.id).unwrap();
20968        let error = resumed.execute().await.unwrap_err();
20969        assert!(
20970            error
20971                .to_string()
20972                .contains("selected implementation is held"),
20973            "{error:#}"
20974        );
20975        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
20976        assert_eq!(
20977            std::fs::read_to_string(path.join("seat-ready")).unwrap(),
20978            setup_output
20979        );
20980        assert_eq!(
20981            std::fs::read_to_string(path.join("checkpoint")).unwrap(),
20982            "unrelated seat"
20983        );
20984        let error = resumed.execute().await.unwrap_err();
20985        assert!(
20986            error
20987                .to_string()
20988                .contains("selected implementation is held"),
20989            "{error:#}"
20990        );
20991        std::fs::write(path.join("checkpoint"), "next recorded review").unwrap();
20992        git::git(&path, &["add", "."]).await.unwrap();
20993        let next_tree = git::git(&path, &["write-tree"]).await.unwrap();
20994        let next = git::git(
20995            &path,
20996            &[
20997                "commit-tree",
20998                &next_tree,
20999                "-p",
21000                &head,
21001                "-m",
21002                "next review checkpoint",
21003            ],
21004        )
21005        .await
21006        .unwrap();
21007        git::git(&path, &["checkout", "--detach", &next])
21008            .await
21009            .unwrap();
21010        resumed.state.reviews.push(
21011            serde_json::from_value(serde_json::json!({
21012                "round":1, "head":next, "reviews":[]
21013            }))
21014            .unwrap(),
21015        );
21016        resumed.state.save().unwrap();
21017        let error = resumed.execute().await.unwrap_err();
21018        assert!(
21019            error
21020                .to_string()
21021                .contains("selected implementation is held"),
21022            "{error:#}"
21023        );
21024        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), next);
21025    }
21026
21027    #[tokio::test]
21028    async fn driver_claim_waits_for_maintenance_before_starting_a_pass() {
21029        crate::run::pin_test_home();
21030        let mut runner = runner_at(RunStatus::Gating);
21031        runner.state.save().unwrap();
21032        let id = runner.state.id.clone();
21033        let passes = runner.state.passes.len();
21034        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
21035        let mut claiming = Box::pin(runner.claim_driver(None));
21036        std::future::poll_fn(|cx| {
21037            assert!(std::future::Future::poll(claiming.as_mut(), cx).is_pending());
21038            std::task::Poll::Ready(())
21039        })
21040        .await;
21041        assert_eq!(RunState::load(&id).unwrap().passes.len(), passes);
21042        drop(owner);
21043        let execution = tokio::time::timeout(Duration::from_secs(2), claiming)
21044            .await
21045            .unwrap()
21046            .unwrap();
21047        assert_eq!(execution.runner.state.passes.len(), passes + 1);
21048        assert!(execution.runner.state.resource_block.is_none());
21049        assert_eq!(
21050            execution.runner.state.liveness(false),
21051            crate::run::Liveness::Live
21052        );
21053        drop(execution);
21054        assert!(RunState::load(&id).unwrap().driver_exited);
21055    }
21056
21057    #[tokio::test]
21058    async fn a_failed_driver_lease_record_releases_the_claim_and_retained_state() {
21059        crate::run::pin_test_home();
21060        let mut runner = runner_at(RunStatus::Gating);
21061        runner.state.save().unwrap();
21062        // run.json can commit, but the subsequent lease metadata write fails.
21063        // Cleanup must run after releasing the short ownership lock.
21064        std::fs::create_dir(runner.state.dir().join("driver.json.tmp")).unwrap();
21065        assert!(runner.claim_driver(None).await.is_err());
21066        assert!(runner.state.driver_exited);
21067        assert_eq!(runner.state.driver_pid, None);
21068        let disk = RunState::load(&runner.state.id).unwrap();
21069        assert!(disk.driver_exited);
21070        assert_eq!(disk.driver_pid, None);
21071        assert_eq!(disk.status, RunStatus::Gating);
21072    }
21073
21074    #[tokio::test]
21075    async fn an_early_graph_error_releases_its_driver() {
21076        crate::run::pin_test_home();
21077        let mut runner = runner_at(RunStatus::Blocked);
21078        runner.state.config.graph.selected_implementer = Some("selected".into());
21079        runner.state.save().unwrap();
21080        assert!(runner.execute().await.is_err());
21081        let disk = RunState::load(&runner.state.id).unwrap();
21082        assert!(disk.driver_exited);
21083        assert_eq!(disk.driver_pid, None);
21084        assert_eq!(disk.status, RunStatus::Blocked);
21085    }
21086
21087    fn merge_repair_request(phase: crate::run::MergeRepairPhase) -> crate::run::MergeRepair {
21088        crate::run::MergeRepair {
21089            question: "repair-question".into(),
21090            head: "old-head".into(),
21091            pr: "https://github.com/o/r/pull/42".into(),
21092            reviews: vec![review_round(false, 1, 1, 1, false, true)],
21093            gate: vec![outcome(Some(0), false)],
21094            gate_head: Some("old-head".into()),
21095            gate_fixes: Vec::new(),
21096            pre_gate: Vec::new(),
21097            phase,
21098            failure: None,
21099        }
21100    }
21101
21102    #[tokio::test]
21103    async fn merge_repair_claim_refuses_concurrent_and_obsolete_drivers() {
21104        crate::run::pin_test_home();
21105        let mut runner = runner_at(RunStatus::Landing);
21106        runner.state.merge_repairs.push(merge_repair_request(
21107            crate::run::MergeRepairPhase::Requested,
21108        ));
21109        runner.state.save().unwrap();
21110        let claim = FixClaim::acquire(&runner.state.dir()).unwrap();
21111        assert!(
21112            runner
21113                .execute()
21114                .await
21115                .unwrap_err()
21116                .to_string()
21117                .contains("already running")
21118        );
21119        assert_eq!(
21120            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
21121            crate::run::MergeRepairPhase::Requested
21122        );
21123        drop(claim);
21124        let mut disk = runner.state.clone();
21125        disk.merge_repairs[0].phase = crate::run::MergeRepairPhase::Complete;
21126        disk.save().unwrap();
21127        assert!(
21128            runner
21129                .execute()
21130                .await
21131                .unwrap_err()
21132                .to_string()
21133                .contains("decision changed")
21134        );
21135        assert_eq!(
21136            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
21137            crate::run::MergeRepairPhase::Complete
21138        );
21139    }
21140
21141    #[test]
21142    fn merge_repair_starts_a_real_new_budget_and_preserves_old_evidence() {
21143        crate::run::pin_test_home();
21144        let mut runner = runner_at(RunStatus::Landing);
21145        let request = merge_repair_request(crate::run::MergeRepairPhase::Fixing);
21146        runner.state.reviews = request.reviews.clone();
21147        runner.state.gate = request.gate.clone();
21148        runner.state.gate_ran = true;
21149        runner.state.land_approval = Some(crate::run::LandApproval {
21150            question: "old".into(),
21151            head: "old-head".into(),
21152        });
21153        runner.state.merge_repairs.push(request);
21154        runner.begin_merge_repair_review(0).unwrap();
21155        assert_eq!(review_conclusion(&runner.state.reviews, 2), None);
21156        assert!(!runner.state.gate_status().ok());
21157        assert!(runner.state.land_approval.is_none());
21158        let disk = RunState::load(&runner.state.id).unwrap();
21159        assert_eq!(disk.merge_repairs[0].reviews[0].blocking, 1);
21160        assert!(disk.merge_repairs[0].gate[0].ok());
21161        assert_eq!(
21162            disk.merge_repairs[0].phase,
21163            crate::run::MergeRepairPhase::Reviewing
21164        );
21165        assert_eq!(disk.merge_repairs[0].pr, "https://github.com/o/r/pull/42");
21166        assert!(disk.reviews.is_empty());
21167    }
21168
21169    #[tokio::test]
21170    async fn merge_repair_interrupted_fixer_and_exhausted_generation_hold_without_repeating_work() {
21171        crate::run::pin_test_home();
21172        for phase in [
21173            crate::run::MergeRepairPhase::Fixing,
21174            crate::run::MergeRepairPhase::Requested,
21175        ] {
21176            let mut runner = runner_at(RunStatus::Landing);
21177            runner.state.config.graph.land_rounds = 0;
21178            runner.state.merge_repairs.push(merge_repair_request(phase));
21179            runner.state.save().unwrap();
21180            assert!(!runner.repair_merge_review().await.unwrap());
21181            assert_eq!(runner.state.status, RunStatus::Blocked);
21182            assert_eq!(
21183                runner.state.merge_repairs[0].phase,
21184                crate::run::MergeRepairPhase::Failed
21185            );
21186            let reason = runner.state.merge_repairs[0].failure.as_ref().unwrap();
21187            assert!(
21188                reason.contains(if phase == crate::run::MergeRepairPhase::Fixing {
21189                    "interrupted"
21190                } else {
21191                    "budget exhausted"
21192                })
21193            );
21194            assert!(runner.state.merge.is_none());
21195        }
21196    }
21197
21198    /// `park_here` folding in the reason `Pause::park_because` recorded -
21199    /// this is what lets an operator reading a run's events tell an
21200    /// interrupt-driven park from an ordinary shutdown park.
21201    #[test]
21202    fn park_here_folds_the_interrupt_reason_into_the_park_event() {
21203        crate::run::pin_test_home();
21204        let mut runner = runner_at(RunStatus::Implementing);
21205        let interrupt = Pause::new();
21206        runner.watch_interrupt(interrupt.clone());
21207
21208        interrupt.park_because("task a1b2 asked to run first");
21209
21210        assert!(runner.park_here().expect("park_here"));
21211        assert!(runner.state.parked);
21212        let last = runner.state.events.last().expect("a park event");
21213        assert_eq!(last.node, "park");
21214        assert!(
21215            last.message.contains("task a1b2 asked to run first"),
21216            "expected the interrupt reason in {:?}",
21217            last.message
21218        );
21219    }
21220
21221    /// The cause is stored on the pass when it parks, and the first cause a
21222    /// shared pause was given is the one that stays.
21223    #[test]
21224    fn park_here_records_the_structured_cause_and_the_first_one_wins() {
21225        crate::run::pin_test_home();
21226        let mut runner = runner_at(RunStatus::Implementing);
21227        runner.state.begin_pass();
21228        let shutdown = Pause::new();
21229        runner.on_pause(shutdown.clone());
21230        let upgrade = ParkCause::Upgrade {
21231            from: "0.121.0".to_owned(),
21232            to: Some("0.121.1".to_owned()),
21233        };
21234        shutdown.park_for(upgrade.clone());
21235        shutdown.park_for(ParkCause::Operator);
21236
21237        assert!(runner.park_here().expect("park_here"));
21238        assert_eq!(
21239            runner.state.passes[0].end,
21240            Some(crate::run::PassEnd::Parked { cause: upgrade })
21241        );
21242        let last = runner.state.events.last().expect("a park event");
21243        assert!(last.message.contains("0.121.0"), "{}", last.message);
21244    }
21245
21246    #[tokio::test]
21247    async fn driver_admission_accepts_a_freshly_minted_record_under_its_lease() {
21248        crate::run::pin_test_home();
21249        let mut runner = runner_at(RunStatus::Reviewing);
21250        runner.state.save().unwrap();
21251        let mut execution = runner.claim_driver(None).await.expect("first execution");
21252        assert_eq!(execution.runner.state.passes.len(), 1);
21253        execution
21254            .driver
21255            .finish(&mut execution.runner.state)
21256            .await
21257            .unwrap();
21258    }
21259
21260    #[tokio::test]
21261    async fn driver_admission_resumes_a_record_saved_before_its_first_claim() {
21262        crate::run::pin_test_home();
21263        let mut runner = runner_at(RunStatus::Reviewing);
21264        runner.state.config.agents = vec![conductor()];
21265        runner.state.config.graph.timeout_resource_wait = 0;
21266        runner.state.save().unwrap();
21267        let id = runner.state.id.clone();
21268        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
21269        assert!(runner.claim_driver(None).await.is_err());
21270        drop(owner);
21271        drop(runner);
21272        let mut resumed = Runner::resume(&id).unwrap();
21273        assert_eq!(resumed.state.driver_claimed, Some(false));
21274        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Dead);
21275        assert_eq!(resumed.state.liveness(true), crate::run::Liveness::Live);
21276        let mut execution = resumed
21277            .claim_driver(None)
21278            .await
21279            .expect("retry initial claim after reload");
21280        assert_eq!(execution.runner.state.driver_claimed, Some(true));
21281        assert_eq!(execution.runner.state.passes.len(), 1);
21282        execution
21283            .driver
21284            .finish(&mut execution.runner.state)
21285            .await
21286            .unwrap();
21287    }
21288
21289    #[tokio::test]
21290    async fn driver_admission_preclaim_marker_does_not_bypass_an_execution_lease() {
21291        crate::run::pin_test_home();
21292        let mut runner = runner_at(RunStatus::Reviewing);
21293        runner.state.config.agents = vec![conductor()];
21294        runner.state.save().unwrap();
21295        let id = runner.state.id.clone();
21296        let lease = crate::driver::maintenance(&crate::run::home(), &id).unwrap();
21297        let mut resumed = Runner::resume(&id).unwrap();
21298        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Live);
21299        assert!(resumed.claim_driver(None).await.is_err());
21300        assert!(RunState::load(&id).unwrap().passes.is_empty());
21301        drop(lease);
21302        let mut execution = resumed.claim_driver(None).await.unwrap();
21303        execution
21304            .driver
21305            .finish(&mut execution.runner.state)
21306            .await
21307            .unwrap();
21308    }
21309
21310    #[tokio::test]
21311    async fn driver_admission_accepts_legacy_unknown_process_with_a_proven_free_pass_lease() {
21312        crate::run::pin_test_home();
21313        let mut runner = runner_at(RunStatus::Reviewing);
21314        let state = &mut runner.state;
21315        state.config.agents = vec![conductor()];
21316        state.driver_claimed = None;
21317        state.driver_pid = Some(std::process::id());
21318        state.driver_started_at = None;
21319        state.begin_pass();
21320        state.save().unwrap();
21321        let lease = crate::driver::maintenance(&crate::run::home(), &state.id).unwrap();
21322        std::fs::write(
21323            state.dir().join("driver.json"),
21324            serde_json::to_vec(&serde_json::json!({
21325                "pid": state.driver_pid, "started_at": null,
21326                "pass": state.passes[0].started_at, "pass_index": state.passes[0].index,
21327            }))
21328            .unwrap(),
21329        )
21330        .unwrap();
21331        assert_eq!(state.liveness(false), crate::run::Liveness::Live);
21332        drop(lease);
21333        assert_eq!(state.liveness(false), crate::run::Liveness::Dead);
21334        let mut resumed = Runner::resume(&state.id).unwrap();
21335        assert!(!resumed.state.driver_exited);
21336        let mut execution = resumed
21337            .claim_driver(None)
21338            .await
21339            .expect("lease proves previous execution ended");
21340        assert_eq!(execution.runner.state.passes.len(), 2);
21341        execution
21342            .driver
21343            .finish(&mut execution.runner.state)
21344            .await
21345            .unwrap();
21346    }
21347
21348    #[tokio::test]
21349    async fn driver_admission_admits_a_legacy_record_without_a_claim_marker() {
21350        crate::run::pin_test_home();
21351        let mut runner = runner_at(RunStatus::Reviewing);
21352        let mut json = serde_json::to_value(&runner.state).unwrap();
21353        json.as_object_mut().unwrap().remove("driver_claimed");
21354        runner.state = serde_json::from_value(json).unwrap();
21355        assert_eq!(runner.state.driver_claimed, None);
21356        runner.state.save().unwrap();
21357        let mut execution = runner
21358            .claim_driver(None)
21359            .await
21360            .expect("the execution lease, not a missing marker, excludes a second driver");
21361        assert_eq!(execution.runner.state.passes.len(), 1);
21362        execution
21363            .driver
21364            .finish(&mut execution.runner.state)
21365            .await
21366            .unwrap();
21367    }
21368
21369    #[tokio::test]
21370    async fn driver_admission_refuses_a_proven_live_driver() {
21371        crate::run::pin_test_home();
21372        let mut runner = runner_at(RunStatus::Reviewing);
21373        let pid = std::process::id();
21374        runner.state.driver_pid = Some(pid);
21375        runner.state.driver_started_at = crate::proc::process_started_at(pid);
21376        assert!(runner.state.driver_started_at.is_some());
21377        runner.state.save().unwrap();
21378        let error = runner
21379            .claim_driver(None)
21380            .await
21381            .err()
21382            .expect("a live driver must refuse");
21383        let message = error.to_string();
21384        assert!(
21385            message.starts_with("run already has a live driver: "),
21386            "{message}"
21387        );
21388        assert!(message.contains(&format!("pid={pid}")), "{message}");
21389        assert!(
21390            message.contains(runner.state.driver_started_at.as_deref().unwrap()),
21391            "{message}"
21392        );
21393        let saved = RunState::load(&runner.state.id).unwrap();
21394        assert_eq!(saved.driver_pid, Some(pid));
21395        assert_eq!(saved.status, RunStatus::Reviewing);
21396        assert!(saved.passes.is_empty());
21397    }
21398
21399    #[tokio::test]
21400    async fn driver_admission_refuses_another_worker_claim_with_shared_format() {
21401        crate::run::pin_test_home();
21402        let home = crate::run::home();
21403        let mut runner = runner_at(RunStatus::Reviewing);
21404        runner.state.driver_exited = true;
21405        runner.state.driver_pid = None;
21406        runner.state.driver_started_at = None;
21407        runner.state.save().unwrap();
21408
21409        let queue = crate::queue::Queue::at(home.join("queue"));
21410        let mut task = crate::queue::Task::new(
21411            "task".into(),
21412            "task".into(),
21413            runner.state.repo.clone(),
21414            crate::queue::Source::Human,
21415        );
21416        task.runs.push(runner.state.id.clone());
21417        queue.put(&mut task).unwrap();
21418        let payload = serde_json::json!({
21419            "queue": home.join("queue"),
21420            "task": task.id,
21421            "opts": crate::daemon::Opts::default(),
21422            "standalone": false,
21423        });
21424        let (job, lease) =
21425            crate::worker::running_fixture(&home, &format!("task:{}", task.id), payload).unwrap();
21426
21427        let error = runner
21428            .claim_driver(None)
21429            .await
21430            .err()
21431            .expect("another active worker claim must refuse");
21432        let message = error.to_string();
21433        assert!(
21434            message.starts_with("run already has a live driver: worker claim"),
21435            "{message}"
21436        );
21437        assert!(message.contains(&job.id), "{message}");
21438        assert!(message.contains("status=running"), "{message}");
21439        assert!(message.contains("live.lock held"), "{message}");
21440
21441        drop(lease);
21442        let _ = std::fs::remove_dir_all(home.join("workers").join("jobs").join(&job.id));
21443    }
21444
21445    #[test]
21446    fn parking_resource_halt_persists_the_pass_once() {
21447        crate::run::pin_test_home();
21448        let mut runner = runner_at(RunStatus::Reviewing);
21449        runner.state.begin_pass();
21450        runner.state.resource_block = Some(crate::run::ResourceBlock {
21451            node: "fix".into(),
21452            kind: "shared build cache".into(),
21453            detail: "cancelled".into(),
21454            at: Timestamp::now(),
21455            cause: crate::run::ResourceBlockCause::Cancelled { park: None },
21456        });
21457        let cause = ParkCause::Upgrade {
21458            from: "old".into(),
21459            to: Some("new".into()),
21460        };
21461        runner.pause.park_for(cause.clone());
21462        // Both direct fixer exits and graph resource boundaries must complete
21463        // parking, rather than returning a stale Reviewing record.
21464        runner.stop_for_resource().unwrap();
21465        assert!(runner.resource_halt().unwrap());
21466        assert!(runner.park_here().unwrap());
21467        let saved = RunState::load(&runner.state.id).unwrap();
21468        assert!(saved.parked);
21469        assert_eq!(saved.status, RunStatus::Reviewing);
21470        assert!(saved.passes[0].ended_at.is_some());
21471        assert_eq!(
21472            saved.passes[0].end,
21473            Some(crate::run::PassEnd::Parked {
21474                cause: cause.clone()
21475            })
21476        );
21477        assert_eq!(
21478            saved.resource_block.unwrap().cause,
21479            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
21480        );
21481        assert_eq!(
21482            saved
21483                .events
21484                .iter()
21485                .filter(|event| event.node == "park")
21486                .count(),
21487            1
21488        );
21489    }
21490
21491    /// `watch_interrupt` and `on_pause` are genuinely independent: an ordinary
21492    /// shutdown `Pause` (what `Stop::park` hands every run, shared and never
21493    /// cleared) must not make a *different* run - one only watching its own,
21494    /// unshared interrupt `Pause` - see itself as parked. If a future change
21495    /// ever collapsed these back into one handle, the interrupt scheduler
21496    /// would park every run for the rest of the daemon's life, not just the
21497    /// one it meant to interrupt.
21498    #[test]
21499    fn the_stop_level_pause_and_a_runs_interrupt_pause_do_not_leak_into_each_other() {
21500        crate::run::pin_test_home();
21501        let mut runner = runner_at(RunStatus::Implementing);
21502        let shutdown = Pause::new();
21503        runner.on_pause(shutdown.clone());
21504        let interrupt = Pause::new();
21505        runner.watch_interrupt(interrupt.clone());
21506
21507        // Nobody has asked for anything yet.
21508        assert!(!runner.park_here().expect("park_here"));
21509        assert!(!runner.state.parked);
21510
21511        // Only the interrupt handle fires; the shutdown handle stays clear.
21512        interrupt.park_because("test");
21513        assert!(!shutdown.parked());
21514        assert!(runner.park_here().expect("park_here"));
21515    }
21516
21517    /// The property every prior attempt at this feature failed to pin down:
21518    /// asking a run to park while one of its nodes has a real, in-flight
21519    /// async operation running (an agent call, in production) must not cut
21520    /// that operation short. `park_here` is only ever consulted *between*
21521    /// `execute`'s node calls - see its own doc - so nothing inside a node
21522    /// can observe a park request until the node itself returns. This proves
21523    /// that structurally, with real `tokio` concurrency and a channel
21524    /// handshake (never a sleep, which would only prove "usually", not
21525    /// "cannot"): the "node" below reports that it has genuinely started,
21526    /// and only then is the park requested; the node still has to be told to
21527    /// finish before `park_here` is ever called, exactly mirroring every
21528    /// `self.some_node().await; if self.park_here()? { return Ok(()); }` pair
21529    /// in `execute`.
21530    #[tokio::test]
21531    async fn a_park_request_made_mid_node_only_takes_effect_at_the_next_boundary() {
21532        crate::run::pin_test_home();
21533        let mut runner = runner_at(RunStatus::Implementing);
21534        let interrupt = Pause::new();
21535        runner.watch_interrupt(interrupt.clone());
21536
21537        let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>();
21538        let (finish_tx, finish_rx) = tokio::sync::oneshot::channel::<()>();
21539
21540        // Stands in for one node's in-flight agent call: it proves it has
21541        // genuinely started, then blocks - exactly as a spawned CLI process
21542        // does - until told to finish.
21543        let node = async move {
21544            started_tx.send(()).expect("send started");
21545            finish_rx.await.expect("recv finish");
21546            "node finished"
21547        };
21548
21549        let interrupter = async move {
21550            started_rx.await.expect("recv started");
21551            // The call is now genuinely in flight. Ask it to park.
21552            interrupt.park_because("higher-priority task waiting");
21553            // Nothing the node does can observe this yet - there is no
21554            // check inside it, by construction - so let the executor run
21555            // anything pending and then let the node finish on its own.
21556            tokio::task::yield_now().await;
21557            finish_tx.send(()).expect("send finish");
21558        };
21559
21560        let (node_result, ()) = tokio::join!(node, interrupter);
21561        assert_eq!(
21562            node_result, "node finished",
21563            "the in-flight call ran to completion"
21564        );
21565
21566        // Only now, at the boundary the real `execute` would check right
21567        // after this node, does the park take effect.
21568        assert!(runner.park_here().expect("park_here"));
21569        assert!(runner.state.parked);
21570    }
21571
21572    /// A run parked mid-competition carries every field it had accumulated
21573    /// through the exact same disk round-trip an ordinary resume uses -
21574    /// `RunState::save`/`RunState::load`, which is all `Runner::resume` is.
21575    /// Nothing about parking for an interrupt is a special case of that path;
21576    /// this is what proves it rather than assuming it.
21577    #[test]
21578    fn a_run_parked_for_an_interrupt_resumes_with_nothing_lost() {
21579        crate::run::pin_test_home();
21580        let mut runner = runner_at(RunStatus::Judging);
21581        // `Runner::resume` re-resolves roles from the saved config, which
21582        // refuses an empty roster - give it the same minimal one `conductor`
21583        // itself uses.
21584        runner.state.config.agents = vec![conductor()];
21585        runner.state.candidates = vec![Candidate {
21586            index: 0,
21587            label: 'A',
21588            agent: "alpha".to_owned(),
21589            branch: "magi/x/A".to_owned(),
21590            worktree: PathBuf::from("/nonexistent/worktree"),
21591            summary: "did the thing".to_owned(),
21592            stat: "1 file changed".to_owned(),
21593            files: 1,
21594            commits: 1,
21595            empty: false,
21596            failed: None,
21597            verified_noop: None,
21598            duration_ms: 1234,
21599            folded: false,
21600        }];
21601        let run_id = runner.state.id.clone();
21602
21603        let interrupt = Pause::new();
21604        runner.watch_interrupt(interrupt.clone());
21605        interrupt.park_because("task c3d4 asked to run first");
21606        assert!(runner.park_here().expect("park_here"));
21607
21608        let resumed = Runner::resume(&run_id).expect("resume");
21609        assert_eq!(resumed.state.candidates.len(), 1);
21610        assert_eq!(resumed.state.candidates[0].summary, "did the thing");
21611        assert_eq!(resumed.state.candidates[0].branch, "magi/x/A");
21612        assert_eq!(resumed.state.status, runner.state.status);
21613        assert!(
21614            resumed.state.parked,
21615            "still parked until `execute` actually walks the graph again"
21616        );
21617        assert!(resumed.state.events.iter().any(|e| e.node == "park"));
21618    }
21619
21620    /// A fresh open question on `run`, stored and handed back for assertions.
21621    fn ask_open_question(store: &ask::Questions, run: &str) -> ask::Question {
21622        let mut q = ask::Question::new(
21623            run.to_owned(),
21624            "implement".to_owned(),
21625            "impl-A".to_owned(),
21626            "Which storage backend should the cache use?".to_owned(),
21627            String::new(),
21628            vec!["SQLite".to_owned(), "Redis".to_owned()],
21629        );
21630        store.put(&mut q).unwrap();
21631        q
21632    }
21633
21634    #[test]
21635    fn a_failed_runs_open_question_is_abandoned() {
21636        ask_test_home();
21637        let store = ask::Questions::open();
21638        let mut runner = runner_at(RunStatus::Failed);
21639        let run = runner.state.id.clone();
21640        let q = ask_open_question(&store, &run);
21641
21642        runner.settle_questions();
21643
21644        let back = store.get(&q.id).unwrap();
21645        assert!(
21646            !back.status.open(),
21647            "the seat that asked died with the run; nobody is left to read an answer"
21648        );
21649        assert!(
21650            back.detail.contains(&run) && back.detail.contains("failed"),
21651            "the reason names what the run became, not just that it is gone: {}",
21652            back.detail
21653        );
21654    }
21655
21656    #[test]
21657    fn a_merged_runs_open_question_is_abandoned_too() {
21658        ask_test_home();
21659        let store = ask::Questions::open();
21660        // A run that finishes cleanly still leaves nobody to read an answer -
21661        // this is not only a failure-path cleanup.
21662        for status in [RunStatus::Merged, RunStatus::Ready] {
21663            let mut runner = runner_at(status);
21664            let run = runner.state.id.clone();
21665            let q = ask_open_question(&store, &run);
21666
21667            runner.settle_questions();
21668
21669            let back = store.get(&q.id).unwrap();
21670            assert!(
21671                !back.status.open(),
21672                "{status:?} run's question must not outlive the run"
21673            );
21674        }
21675    }
21676
21677    #[test]
21678    fn a_still_resumable_runs_open_question_is_left_alone() {
21679        ask_test_home();
21680        let store = ask::Questions::open();
21681        // `Blocked` and `Stalled` can still be resumed — the candidates, the
21682        // review round and the seat sessions are all still on disk — so a
21683        // question asked mid-round may yet get a real answer from a real
21684        // resume. Sweeping it here would be exactly the failure mode this
21685        // whole feature exists to avoid on the other side.
21686        for status in [RunStatus::Blocked, RunStatus::Stalled] {
21687            let mut runner = runner_at(status);
21688            let run = runner.state.id.clone();
21689            let q = ask_open_question(&store, &run);
21690
21691            runner.settle_questions();
21692
21693            let back = store.get(&q.id).unwrap();
21694            assert!(
21695                back.status.open(),
21696                "{status:?} is still alive; the question must still be waiting"
21697            );
21698        }
21699    }
21700
21701    #[test]
21702    fn settle_questions_never_touches_an_already_answered_question() {
21703        ask_test_home();
21704        let store = ask::Questions::open();
21705        let mut runner = runner_at(RunStatus::Failed);
21706        let run = runner.state.id.clone();
21707        let mut q = ask_open_question(&store, &run);
21708        q.answer(crate::ask::Answer::Choice("SQLite".to_owned()))
21709            .unwrap();
21710        store.put(&mut q).unwrap();
21711
21712        // Called twice, the way a crash-recovered daemon reclaim and the
21713        // graph's own cleanup both can for the same run — `abandon_for_run`
21714        // only ever touches what is still open, so this must be inert both
21715        // times, not merely the second.
21716        runner.settle_questions();
21717        runner.settle_questions();
21718
21719        let back = store.get(&q.id).unwrap();
21720        assert_eq!(
21721            back.status,
21722            ask::QuestionStatus::Answered,
21723            "a real answer is a decision on record, never overwritten by a sweep"
21724        );
21725    }
21726
21727    #[tokio::test]
21728    async fn fold_reclaims_only_proven_idle_isolated_outputs() {
21729        let tmp = tempfile::tempdir().unwrap();
21730        let home = tmp.path().join("home");
21731        let repo = tmp.path().join("repo");
21732        std::fs::create_dir(&home).unwrap();
21733        std::fs::create_dir(&repo).unwrap();
21734        init_repo(&repo);
21735
21736        let mut config = Config::default();
21737        config.graph.worktree_root = Some(tmp.path().join("wt"));
21738        config.verify.build_cache = crate::config::BuildCache::Isolated;
21739        let mut state = RunState::new(
21740            repo.clone(),
21741            "main".into(),
21742            "base".into(),
21743            "fold fixture".into(),
21744            config,
21745        );
21746        let root = state.worktree_root();
21747        let mut outputs = Vec::new();
21748        for name in ["idle", "busy"] {
21749            let checkout = root.join(name);
21750            git::worktree_add_detached(&repo, &checkout, "main")
21751                .await
21752                .unwrap();
21753            let target = crate::build_target::resolve(&home, &checkout).unwrap();
21754            let output = target.join("generated");
21755            std::fs::write(&output, name).unwrap();
21756            outputs.push((target, output));
21757        }
21758        let unknown = crate::build_target::root(&home)
21759            .join("00000000-0000-0000-0000-000000000000")
21760            .join("target");
21761        std::fs::create_dir_all(&unknown).unwrap();
21762        let unowned = unknown.join("generated");
21763        std::fs::write(&unowned, "keep").unwrap();
21764        let owner = crate::cache::Owner::here("fixture", "build", "busy", &root.join("busy"), "");
21765        let crate::cache::AcquireOutcome::Acquired(_lease) =
21766            crate::cache::try_acquire(&home, &outputs[1].0, &owner).unwrap()
21767        else {
21768            panic!("fixture target must be free");
21769        };
21770
21771        state.save_under(&home).unwrap();
21772        fold_run(&mut state, true, &home).await.unwrap();
21773        assert!(!root.exists());
21774        assert!(!outputs[0].1.exists());
21775        assert!(outputs[1].1.is_file());
21776        assert!(unowned.is_file());
21777    }
21778
21779    /// `fold_run(&mut state, drop_winner = false)` is exactly the call
21780    /// `clean::fold_due` makes for a `Ready`/`Failed` run - one that finished
21781    /// without merging, whose winner is still the operator's answer to read.
21782    /// Nothing previously called `fold_run` itself with a real `tally`, so
21783    /// this is the first test to pin down the one distinction the whole
21784    /// automatic-fold feature depends on: the winner's worktree and branch
21785    /// must survive, everything else sharing the run's worktree bay - a
21786    /// loser, standing in for a judge/review worktree too, since `fold_run`'s
21787    /// second sweep treats every non-winner directory under the bay alike -
21788    /// must not.
21789    #[tokio::test]
21790    async fn fold_run_keeps_only_the_winner_when_the_winner_is_not_dropped() {
21791        crate::run::pin_test_home();
21792        let tmp = tempfile::tempdir().expect("tempdir");
21793        let repo = tmp.path().join("repo");
21794        std::fs::create_dir_all(&repo).unwrap();
21795        init_repo(&repo);
21796
21797        let mut config = Config::default();
21798        config.graph.worktree_root = Some(tmp.path().join("wt"));
21799
21800        let mut state = RunState::new(
21801            repo.clone(),
21802            "main".to_owned(),
21803            "deadbeef".to_owned(),
21804            "task".to_owned(),
21805            config,
21806        );
21807        let root = state.worktree_root();
21808        let wt_a = root.join("cand-A");
21809        let wt_b = root.join("cand-B");
21810        git::worktree_add_branch(&repo, &wt_a, "magi/x/A", "main")
21811            .await
21812            .expect("worktree A");
21813        git::worktree_add_branch(&repo, &wt_b, "magi/x/B", "main")
21814            .await
21815            .expect("worktree B");
21816
21817        state.candidates = vec![
21818            Candidate {
21819                index: 0,
21820                label: 'A',
21821                agent: "alpha".to_owned(),
21822                branch: "magi/x/A".to_owned(),
21823                worktree: wt_a.clone(),
21824                summary: String::new(),
21825                stat: String::new(),
21826                files: 0,
21827                commits: 0,
21828                empty: false,
21829                failed: None,
21830                verified_noop: None,
21831                duration_ms: 0,
21832                folded: false,
21833            },
21834            Candidate {
21835                index: 1,
21836                label: 'B',
21837                agent: "beta".to_owned(),
21838                branch: "magi/x/B".to_owned(),
21839                worktree: wt_b.clone(),
21840                summary: String::new(),
21841                stat: String::new(),
21842                files: 0,
21843                commits: 0,
21844                empty: false,
21845                failed: None,
21846                verified_noop: None,
21847                duration_ms: 0,
21848                folded: false,
21849            },
21850        ];
21851        state.tally = Some(Tally {
21852            first_choice: BTreeMap::from([('A', 1)]),
21853            borda: BTreeMap::new(),
21854            winner: 'A',
21855            rankings: 1,
21856            unanimous_initial: true,
21857            deliberated: false,
21858            changed_votes: 0,
21859            unanimous_final: true,
21860            tie_break: None,
21861            judges: 1,
21862            present: 1,
21863            quorum: 1,
21864            met_quorum: true,
21865            uncontested: None,
21866        });
21867        state.status = RunStatus::Ready;
21868
21869        state.save_under(&crate::run::home()).unwrap();
21870        fold_run(&mut state, false, &crate::run::home())
21871            .await
21872            .expect("fold_run");
21873
21874        assert!(wt_a.exists(), "the unmerged winner's worktree survives");
21875        assert!(
21876            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
21877            "the unmerged winner's branch survives"
21878        );
21879        assert!(
21880            !state.candidates[0].folded,
21881            "the winner is not marked folded"
21882        );
21883
21884        assert!(!wt_b.exists(), "the loser's worktree is removed");
21885        assert!(
21886            !git::branch_exists(&repo, "magi/x/B").await.unwrap(),
21887            "the loser's branch is removed"
21888        );
21889        assert!(state.candidates[1].folded, "the loser is marked folded");
21890    }
21891
21892    #[tokio::test]
21893    #[cfg(unix)]
21894    async fn fold_run_waits_for_shared_lock_before_removing_worktrees_branches_or_config() {
21895        use std::os::fd::AsRawFd as _;
21896        use std::time::Duration;
21897
21898        let tmp = tempfile::tempdir().unwrap();
21899        let repo = tmp.path().join("repo");
21900        std::fs::create_dir_all(&repo).unwrap();
21901        init_repo(&repo);
21902        let common = repo.join(".git");
21903        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
21904        let home = tmp.path().join("home");
21905        let mut config = Config::default();
21906        config.coordination = crate::config::test_coordination();
21907        config.graph.worktree_root = Some(tmp.path().join("wt"));
21908        config.graph.timeout_resource_wait = 1;
21909        let mut state = RunState::new(
21910            repo.clone(),
21911            "main".into(),
21912            "deadbeef".into(),
21913            "task".into(),
21914            config,
21915        );
21916        let root = state.worktree_root();
21917        let candidate = root.join("cand-A");
21918        let reviewer = root.join("review-1");
21919        let branch = state.branch_for('A');
21920        git::worktree_add_branch(&repo, &candidate, &branch, "main")
21921            .await
21922            .unwrap();
21923        git::worktree_add_detached(&repo, &reviewer, "main")
21924            .await
21925            .unwrap();
21926        git::acquire_worktree_config(&repo).await.unwrap();
21927        state.enabled_worktree_config = true;
21928        state.status = RunStatus::Ready;
21929        state.candidates.push(Candidate {
21930            index: 0,
21931            label: 'A',
21932            agent: "implement".into(),
21933            branch: branch.clone(),
21934            worktree: candidate.clone(),
21935            summary: String::new(),
21936            stat: String::new(),
21937            files: 0,
21938            commits: 0,
21939            empty: false,
21940            failed: None,
21941            verified_noop: None,
21942            duration_ms: 0,
21943            folded: false,
21944        });
21945        state.save_under(&home).unwrap();
21946        let config_before = std::fs::read(common.join("config")).unwrap();
21947        let worktrees_before = git::git(&repo, &["worktree", "list", "--porcelain"])
21948            .await
21949            .unwrap();
21950        // A separate OS handle bypasses the launcher's local gate, exactly as
21951        // an external updater does, and must still prevent all folding work.
21952        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
21953        assert_eq!(
21954            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
21955            0
21956        );
21957        let mut fold = Box::pin(fold_run(&mut state, true, &home));
21958        assert!(
21959            tokio::time::timeout(Duration::from_millis(200), &mut fold)
21960                .await
21961                .is_err()
21962        );
21963        assert!(candidate.exists());
21964        assert!(reviewer.exists());
21965        assert!(git::branch_exists(&repo, &branch).await.unwrap());
21966        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
21967        assert_eq!(
21968            git::git(&repo, &["worktree", "list", "--porcelain"])
21969                .await
21970                .unwrap(),
21971            worktrees_before
21972        );
21973        let error = tokio::time::timeout(Duration::from_secs(3), &mut fold)
21974            .await
21975            .unwrap()
21976            .unwrap_err();
21977        assert!(error.is::<crate::repo_lock::ResourceBlocked>());
21978        drop(fold);
21979        assert!(candidate.exists() && reviewer.exists());
21980        assert!(!state.candidates[0].folded && state.enabled_worktree_config);
21981        assert_eq!(
21982            state.resource_block.as_ref().unwrap().kind,
21983            "repository coordination"
21984        );
21985        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
21986        drop(external);
21987        let mut fold = Box::pin(fold_run(&mut state, true, &home));
21988        let removed = tokio::time::timeout(Duration::from_secs(10), &mut fold)
21989            .await
21990            .unwrap()
21991            .unwrap();
21992        drop(fold);
21993        assert!(removed.contains(&branch));
21994        assert!(!root.exists());
21995        assert!(!git::branch_exists(&repo, &branch).await.unwrap());
21996        assert!(state.candidates[0].folded);
21997        assert!(!state.enabled_worktree_config);
21998        assert_ne!(std::fs::read(common.join("config")).unwrap(), config_before);
21999        let enabled = git::git_raw(
22000            &repo,
22001            &["config", "--local", "--get", "extensions.worktreeConfig"],
22002        )
22003        .await
22004        .unwrap();
22005        assert!(!enabled.ok(), "the last config reference was released");
22006    }
22007
22008    /// A handover holds repository coordination and then asks for the
22009    /// predecessor's owner lock; an automatic fold already holds that lock. The
22010    /// fold asks for coordination once and gives way, so the handover's short
22011    /// retry succeeds - waiting for it would leave both waiting for each other.
22012    /// Nothing is changed or saved on the way out and the refusal is `live`;
22013    /// the explicit entry points (`magi fold`) still wait, bounded as before.
22014    #[tokio::test]
22015    #[cfg(unix)]
22016    async fn an_automatic_fold_gives_way_to_busy_coordination_instead_of_waiting() {
22017        use std::os::fd::AsRawFd as _;
22018        use std::time::Duration;
22019
22020        let tmp = tempfile::tempdir().unwrap();
22021        let repo = tmp.path().join("repo");
22022        std::fs::create_dir_all(&repo).unwrap();
22023        init_repo(&repo);
22024        let common = repo.join(".git");
22025        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
22026        let home = tmp.path().join("home");
22027        let mut config = Config::default();
22028        config.coordination = crate::config::test_coordination();
22029        config.graph.worktree_root = Some(tmp.path().join("wt"));
22030        config.graph.timeout_resource_wait = 60;
22031        let mut state = RunState::new(
22032            repo.clone(),
22033            "main".into(),
22034            "deadbeef".into(),
22035            "task".into(),
22036            config,
22037        );
22038        let candidate = state.worktree_root().join("cand-A");
22039        let branch = state.branch_for('A');
22040        git::worktree_add_branch(&repo, &candidate, &branch, "main")
22041            .await
22042            .unwrap();
22043        state.status = RunStatus::Ready;
22044        state.driver_exited = true;
22045        state.candidates.push(Candidate {
22046            index: 0,
22047            label: 'A',
22048            agent: "implement".into(),
22049            branch: branch.clone(),
22050            worktree: candidate.clone(),
22051            summary: String::new(),
22052            stat: String::new(),
22053            files: 0,
22054            commits: 0,
22055            empty: false,
22056            failed: None,
22057            verified_noop: None,
22058            duration_ms: 0,
22059            folded: false,
22060        });
22061        state.save_under(&home).unwrap();
22062        let id = state.id.clone();
22063        let record = std::fs::read(home.join("runs").join(&id).join("run.json")).unwrap();
22064
22065        // A separate OS handle bypasses the launcher's local gate, exactly as
22066        // another process holding coordination does.
22067        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
22068        assert_eq!(
22069            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
22070            0
22071        );
22072        let error = tokio::time::timeout(
22073            Duration::from_secs(10),
22074            fold_run_when(&mut state, &home, &|_| Ok(true)),
22075        )
22076        .await
22077        .expect("the automatic fold does not wait out the 60 s resource wait")
22078        .unwrap_err();
22079        assert!(
22080            matches!(
22081                error.downcast_ref::<FoldRefusal>(),
22082                Some(FoldRefusal::Live(_))
22083            ),
22084            "{error:#}"
22085        );
22086        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
22087        // It gave way: both locks it held are free, nothing was removed and
22088        // nothing was saved (no resource block recorded on the record either).
22089        drop(crate::pr_head::owner_lock(&home, &id).expect("the owner lock was released"));
22090        drop(crate::driver::maintenance(&home, &id).expect("the execution lease was released"));
22091        assert!(candidate.exists() && git::branch_exists(&repo, &branch).await.unwrap());
22092        assert_eq!(
22093            std::fs::read(home.join("runs").join(&id).join("run.json")).unwrap(),
22094            record
22095        );
22096
22097        // The explicit entry point was asked for by a person and still waits.
22098        assert!(
22099            tokio::time::timeout(
22100                Duration::from_millis(300),
22101                fold_run(&mut state, true, &home)
22102            )
22103            .await
22104            .is_err(),
22105            "an explicit fold keeps waiting for coordination"
22106        );
22107        assert!(candidate.exists());
22108
22109        drop(external);
22110        let removed = fold_run_when(&mut state, &home, &|_| Ok(true))
22111            .await
22112            .unwrap();
22113        assert!(removed.contains(&branch));
22114        assert!(!candidate.exists());
22115    }
22116
22117    /// A branch handed to a later run is that run's (and its pull request's):
22118    /// folding the run that released it must not delete it.
22119    #[tokio::test]
22120    async fn fold_run_keeps_a_branch_that_was_handed_to_a_later_run() {
22121        let tmp = tempfile::tempdir().expect("tempdir");
22122        let repo = tmp.path().join("repo");
22123        std::fs::create_dir_all(&repo).unwrap();
22124        init_repo(&repo);
22125        let home = tmp.path().join("home");
22126
22127        let mut config = Config::default();
22128        config.graph.worktree_root = Some(tmp.path().join("wt"));
22129        let mut state = RunState::new(
22130            repo.clone(),
22131            "main".to_owned(),
22132            "deadbeef".to_owned(),
22133            "task".to_owned(),
22134            config,
22135        );
22136        // The worktree is already gone (released); the branch survives.
22137        git::git(&repo, &["branch", "magi/x/A", "main"])
22138            .await
22139            .expect("branch");
22140        state.candidates = vec![Candidate {
22141            index: 0,
22142            label: 'A',
22143            agent: "alpha".to_owned(),
22144            branch: "magi/x/A".to_owned(),
22145            worktree: state.worktree_root().join("cand-A"),
22146            summary: String::new(),
22147            stat: String::new(),
22148            files: 0,
22149            commits: 0,
22150            empty: false,
22151            failed: None,
22152            verified_noop: None,
22153            duration_ms: 0,
22154            folded: true,
22155        }];
22156        state.released_to = Some("20260901-000000-new1".to_owned());
22157        state.released_branches = vec!["magi/x/A".to_owned()];
22158
22159        state.save_under(&home).unwrap();
22160        fold_run(&mut state, true, &home).await.expect("fold_run");
22161        state.status = RunStatus::Merged;
22162        state.base_commit = git::rev_parse(&repo, "main").await.unwrap();
22163        state.merge = Some(crate::run::MergeOutcome {
22164            mode: MergeMode::Pr,
22165            ok: true,
22166            detail: "confirmed merged".into(),
22167            empty: false,
22168        });
22169        state.save_under(&home).unwrap();
22170        fold_run(&mut state, true, &home)
22171            .await
22172            .expect("merged fold");
22173
22174        assert!(
22175            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
22176            "the handed-over branch survives a fold"
22177        );
22178    }
22179
22180    /// A winner with nothing ahead of the base is caught before `gh` is ever
22181    /// asked for a pull request, and the message carries what the task's
22182    /// references resolved to.
22183    #[tokio::test]
22184    async fn an_empty_winner_is_detected_before_a_pull_request_is_attempted() {
22185        let tmp = tempfile::tempdir().expect("tempdir");
22186        let repo = tmp.path().join("repo");
22187        std::fs::create_dir_all(&repo).unwrap();
22188        init_repo(&repo);
22189        let run = |args: &[&str]| {
22190            let out = std::process::Command::new("git")
22191                .quiet()
22192                .args(args)
22193                .current_dir(&repo)
22194                .output()
22195                .expect("spawn git");
22196            assert!(out.status.success(), "git {args:?}");
22197        };
22198        run(&["branch", "magi/x/A"]);
22199        run(&["checkout", "-q", "-b", "magi/x/B"]);
22200        std::fs::write(repo.join("f.txt"), "x\n").unwrap();
22201        run(&["add", "-A"]);
22202        run(&["commit", "-q", "-m", "work"]);
22203        run(&["checkout", "-q", "main"]);
22204
22205        // A pull request is compared against the remote's base, so the
22206        // fixture needs one. Before it exists nothing can be read, and the
22207        // answer must be "not empty".
22208        let probe = RunState::new(
22209            repo.clone(),
22210            "main".to_owned(),
22211            "deadbeef".to_owned(),
22212            "task".to_owned(),
22213            Config::default(),
22214        );
22215        assert!(!merge_is_empty(&repo, &probe, "magi/x/A", MergeMode::Pr).await);
22216        let bare = tmp.path().join("origin.git");
22217        let out = std::process::Command::new("git")
22218            .quiet()
22219            .args(["init", "-q", "--bare"])
22220            .arg(&bare)
22221            .output()
22222            .expect("spawn git");
22223        assert!(out.status.success(), "git init --bare");
22224        run(&["remote", "add", "origin", bare.to_str().unwrap()]);
22225        run(&["push", "-q", "origin", "main"]);
22226
22227        let mut state = RunState::new(
22228            repo.clone(),
22229            "main".to_owned(),
22230            "deadbeef".to_owned(),
22231            "task".to_owned(),
22232            Config::default(),
22233        );
22234        state.seeds = vec![refs::Seed {
22235            token: "magi/27b2/A".to_owned(),
22236            kind: refs::SeedKind::Unresolved,
22237            sha: String::new(),
22238            branch: true,
22239            detail: "no branch or commit named magi/27b2/A".to_owned(),
22240        }];
22241
22242        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Pr).await);
22243        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Local).await);
22244        assert!(!merge_is_empty(&repo, &state, "magi/x/B", MergeMode::Pr).await);
22245        let detail = empty_candidate_detail(&state, "main");
22246        assert!(detail.starts_with("empty candidate"), "{detail}");
22247        assert!(!detail.contains("magi/27b2/A"), "{detail}");
22248        assert!(detail.contains("--start-from"), "{detail}");
22249    }
22250
22251    /// `status == Ready` used to be read as "this is the harmless
22252    /// `MergeMode::None` no-op path, nothing to guard" (graph.rs, prior to
22253    /// this test). But `land` sets the very same status when a `MergeMode::Pr`
22254    /// run's PR was closed without merging — and reentering `merge` with
22255    /// `mode` still `Pr` does not know the difference, so it pushed and
22256    /// opened a second pull request. `mode == Local` reproduces the same
22257    /// blind spot without a network call: reentry must not attempt another
22258    /// git merge once this node has already recorded an outcome.
22259    #[tokio::test]
22260    async fn merge_does_not_reattempt_once_a_run_has_concluded() {
22261        let tmp = tempfile::tempdir().expect("tempdir");
22262        let repo = tmp.path().join("repo");
22263        std::fs::create_dir_all(&repo).unwrap();
22264        init_repo(&repo);
22265
22266        let mut config = Config::default();
22267        config.merge.mode = MergeMode::Local;
22268
22269        let mut state = RunState::new(
22270            repo.clone(),
22271            "main".to_owned(),
22272            "deadbeef".to_owned(),
22273            "task".to_owned(),
22274            config,
22275        );
22276        state.candidates = vec![Candidate {
22277            index: 0,
22278            label: 'A',
22279            agent: "alpha".to_owned(),
22280            branch: "does-not-exist".to_owned(),
22281            worktree: repo.clone(),
22282            summary: String::new(),
22283            stat: String::new(),
22284            files: 0,
22285            commits: 0,
22286            empty: false,
22287            failed: None,
22288            verified_noop: None,
22289            duration_ms: 0,
22290            folded: false,
22291        }];
22292        state.tally = Some(Tally {
22293            first_choice: BTreeMap::from([('A', 1)]),
22294            borda: BTreeMap::new(),
22295            winner: 'A',
22296            rankings: 1,
22297            unanimous_initial: true,
22298            deliberated: false,
22299            changed_votes: 0,
22300            unanimous_final: true,
22301            tie_break: None,
22302            judges: 0,
22303            present: 0,
22304            quorum: 0,
22305            met_quorum: true,
22306            uncontested: Some("only candidate A produced a change".to_owned()),
22307        });
22308        state.reviews = vec![ReviewRound {
22309            round: 1,
22310            head: "deadbeef".to_owned(),
22311            verified_head: None,
22312            verified_at: None,
22313            reviews: Vec::new(),
22314            e2e: Vec::new(),
22315            fix: None,
22316            blocking: 0,
22317            answered: 0,
22318            expected: 0,
22319            clean: true,
22320            verify_retried: false,
22321            e2e_deferred: false,
22322            e2e_defer_reason: None,
22323            progressed: false,
22324            vote_split: false,
22325            reconsideration: Vec::new(),
22326            verdict: None,
22327        }];
22328        state.gate = vec![CommandOutcome {
22329            command: "test".to_owned(),
22330            code: Some(0),
22331            output_tail: String::new(),
22332            duration_ms: 0,
22333            resource_blocked: false,
22334            ..Default::default()
22335        }];
22336        state.gate_ran = true;
22337        // Reached its conclusion already — e.g. `land` closing the PR without
22338        // merging it, which (like the honest `MergeMode::None` path) leaves
22339        // `status` at `Ready`. The recorded outcome is what actually marks
22340        // this node done.
22341        state.status = RunStatus::Ready;
22342        state.merge = Some(MergeOutcome {
22343            mode: MergeMode::Local,
22344            ok: false,
22345            detail: "already concluded".to_owned(),
22346            empty: false,
22347        });
22348
22349        let mut runner = Runner {
22350            state,
22351            roles: ResolvedRoles {
22352                implementers: Vec::new(),
22353                judges: Vec::new(),
22354                reviewers: Vec::new(),
22355                fixer: None,
22356                conductor: conductor(),
22357                implementer_roster: Vec::new(),
22358                judge_roster: Vec::new(),
22359                reviewer_roster: Vec::new(),
22360            },
22361            sem: Arc::new(Semaphore::new(1)),
22362            pause: Pause::new(),
22363            interrupt: Pause::new(),
22364        };
22365
22366        runner.merge().await.expect("merge");
22367
22368        assert_eq!(
22369            runner.state.status,
22370            RunStatus::Ready,
22371            "a concluded run's status must not change on reentry"
22372        );
22373        assert_eq!(
22374            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
22375            Some("already concluded"),
22376            "merge must not run again once the node already recorded an outcome"
22377        );
22378    }
22379
22380    /// `gate` leaves `state.gate_ran` false both before it has ever run and
22381    /// when its last attempt was resource-blocked (the shared build cache
22382    /// could not be acquired or confirmed fresh in time - see
22383    /// `CommandOutcome::resource_blocked`'s own doc). Trusting the empty
22384    /// `Vec` this also leaves behind used to read as "nothing failed" and let
22385    /// a run merge a tree the gate never actually checked - exactly the case
22386    /// a contended cache produces on every retry until it clears. `merge`
22387    /// must refuse until `gate` has actually recorded an attempt.
22388    #[tokio::test]
22389    async fn merge_refuses_a_gate_that_has_not_actually_run() {
22390        let tmp = tempfile::tempdir().expect("tempdir");
22391        let repo = tmp.path().join("repo");
22392        std::fs::create_dir_all(&repo).unwrap();
22393        init_repo(&repo);
22394
22395        let mut config = Config::default();
22396        config.merge.mode = MergeMode::Local;
22397
22398        let mut state = RunState::new(
22399            repo.clone(),
22400            "main".to_owned(),
22401            "deadbeef".to_owned(),
22402            "task".to_owned(),
22403            config,
22404        );
22405        state.candidates = vec![Candidate {
22406            index: 0,
22407            label: 'A',
22408            agent: "alpha".to_owned(),
22409            branch: "does-not-exist".to_owned(),
22410            worktree: repo.clone(),
22411            summary: String::new(),
22412            stat: String::new(),
22413            files: 0,
22414            commits: 0,
22415            empty: false,
22416            failed: None,
22417            verified_noop: None,
22418            duration_ms: 0,
22419            folded: false,
22420        }];
22421        state.tally = Some(Tally {
22422            first_choice: BTreeMap::from([('A', 1)]),
22423            borda: BTreeMap::new(),
22424            winner: 'A',
22425            rankings: 1,
22426            unanimous_initial: true,
22427            deliberated: false,
22428            changed_votes: 0,
22429            unanimous_final: true,
22430            tie_break: None,
22431            judges: 0,
22432            present: 0,
22433            quorum: 0,
22434            met_quorum: true,
22435            uncontested: Some("only candidate A produced a change".to_owned()),
22436        });
22437        state.reviews = vec![ReviewRound {
22438            round: 1,
22439            head: "deadbeef".to_owned(),
22440            verified_head: None,
22441            verified_at: None,
22442            reviews: Vec::new(),
22443            e2e: Vec::new(),
22444            fix: None,
22445            blocking: 0,
22446            answered: 0,
22447            expected: 0,
22448            clean: true,
22449            verify_retried: false,
22450            e2e_deferred: false,
22451            e2e_defer_reason: None,
22452            progressed: false,
22453            vote_split: false,
22454            reconsideration: Vec::new(),
22455            verdict: None,
22456        }];
22457        // The point: `gate` has not recorded anything yet.
22458        state.gate = Vec::new();
22459        state.gate_ran = false;
22460        state.status = RunStatus::Gating;
22461
22462        let mut runner = Runner {
22463            state,
22464            roles: ResolvedRoles {
22465                implementers: Vec::new(),
22466                judges: Vec::new(),
22467                reviewers: Vec::new(),
22468                fixer: None,
22469                conductor: conductor(),
22470                implementer_roster: Vec::new(),
22471                judge_roster: Vec::new(),
22472                reviewer_roster: Vec::new(),
22473            },
22474            sem: Arc::new(Semaphore::new(1)),
22475            pause: Pause::new(),
22476            interrupt: Pause::new(),
22477        };
22478
22479        runner.merge().await.expect("merge");
22480
22481        assert!(
22482            runner.state.merge.is_none(),
22483            "an empty gate must never be read as a passing one: {:?}",
22484            runner.state.merge
22485        );
22486    }
22487
22488    /// The `shoka` repro this schema bump exists for: `verify.gate` has no
22489    /// commands configured and `merge.mode` is `none` (a review-only run).
22490    /// `gate` must still record a real attempt — zero commands, vacuously
22491    /// passed — rather than leaving `state.gate` empty in a way `merge`
22492    /// cannot tell apart from "never ran"; otherwise the run reaches
22493    /// `Gating` and can never leave it. See `RunState::gate_ran`'s own doc.
22494    #[tokio::test]
22495    async fn gate_and_merge_reach_ready_when_no_gate_commands_are_configured() {
22496        let tmp = tempfile::tempdir().expect("tempdir");
22497        let repo = tmp.path().join("repo");
22498        std::fs::create_dir_all(&repo).unwrap();
22499        init_repo(&repo);
22500
22501        // Default config: `verify.gate` empty, `merge.mode` is `none`.
22502        let config = Config::default();
22503
22504        let mut state = RunState::new(
22505            repo.clone(),
22506            "main".to_owned(),
22507            "deadbeef".to_owned(),
22508            "task".to_owned(),
22509            config,
22510        );
22511        state.candidates = vec![Candidate {
22512            index: 0,
22513            label: 'A',
22514            agent: "alpha".to_owned(),
22515            branch: "does-not-exist".to_owned(),
22516            worktree: repo.clone(),
22517            summary: String::new(),
22518            stat: String::new(),
22519            files: 0,
22520            commits: 0,
22521            empty: false,
22522            failed: None,
22523            verified_noop: None,
22524            duration_ms: 0,
22525            folded: false,
22526        }];
22527        state.tally = Some(Tally {
22528            first_choice: BTreeMap::from([('A', 1)]),
22529            borda: BTreeMap::new(),
22530            winner: 'A',
22531            rankings: 1,
22532            unanimous_initial: true,
22533            deliberated: false,
22534            changed_votes: 0,
22535            unanimous_final: true,
22536            tie_break: None,
22537            judges: 0,
22538            present: 0,
22539            quorum: 0,
22540            met_quorum: true,
22541            uncontested: Some("only candidate A produced a change".to_owned()),
22542        });
22543        state.reviews = vec![ReviewRound {
22544            round: 1,
22545            head: "deadbeef".to_owned(),
22546            verified_head: None,
22547            verified_at: None,
22548            reviews: Vec::new(),
22549            e2e: Vec::new(),
22550            fix: None,
22551            blocking: 0,
22552            answered: 0,
22553            expected: 0,
22554            clean: true,
22555            verify_retried: false,
22556            e2e_deferred: false,
22557            e2e_defer_reason: None,
22558            progressed: false,
22559            vote_split: false,
22560            reconsideration: Vec::new(),
22561            verdict: None,
22562        }];
22563
22564        let mut runner = Runner {
22565            state,
22566            roles: ResolvedRoles {
22567                implementers: Vec::new(),
22568                judges: Vec::new(),
22569                reviewers: Vec::new(),
22570                fixer: None,
22571                conductor: conductor(),
22572                implementer_roster: Vec::new(),
22573                judge_roster: Vec::new(),
22574                reviewer_roster: Vec::new(),
22575            },
22576            sem: Arc::new(Semaphore::new(1)),
22577            pause: Pause::new(),
22578            interrupt: Pause::new(),
22579        };
22580
22581        runner.gate().await.expect("gate");
22582        assert!(
22583            runner.state.gate_ran,
22584            "zero configured commands is still a real attempt, not an unrun gate"
22585        );
22586        assert!(runner.state.gate.is_empty());
22587        assert_eq!(runner.state.gate_status(), GateStatus::NotConfigured);
22588        assert_ne!(
22589            runner.state.status,
22590            RunStatus::Blocked,
22591            "a gate with nothing to check must not read as failed"
22592        );
22593
22594        runner.merge().await.expect("merge");
22595        assert_eq!(
22596            runner.state.status,
22597            RunStatus::Ready,
22598            "a clean review-only run with no gate commands must reach Ready, not stay stuck in Gating"
22599        );
22600    }
22601
22602    /// `Config::cache_dir` is derived from `verify.e2e` as well as
22603    /// `verify.gate` (so the e2e leg and the final gate never build against
22604    /// different directories). With zero `verify.gate` commands but a
22605    /// `CARGO_TARGET_DIR`-using `verify.e2e`, `gate` used to still queue for
22606    /// that lease before discovering it had nothing to run - so a repo with
22607    /// no gate commands could come back `resource_blocked` (and therefore
22608    /// still `gate_ran == false`) on nothing but an unrelated run holding the
22609    /// cache, exactly the contention this run's own zero commands could
22610    /// never have touched. `gate` must recognise there is nothing to check
22611    /// before it ever asks for the lease.
22612    #[tokio::test]
22613    async fn gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run() {
22614        crate::run::pin_test_home();
22615        let home = crate::run::home();
22616
22617        let tmp = tempfile::tempdir().expect("tempdir");
22618        let repo = tmp.path().join("repo");
22619        std::fs::create_dir_all(&repo).unwrap();
22620        init_repo(&repo);
22621        // Unique to this test, so holding its lease cannot collide with
22622        // another test sharing the same process-wide `home`.
22623        let cache_dir = tmp.path().join("target");
22624
22625        let mut config = Config::default();
22626        config.verify.e2e = vec![format!("CARGO_TARGET_DIR='{}' true", cache_dir.display())];
22627        // `verify.gate` stays empty (the default). Any accidental cache
22628        // acquisition must report contention immediately, regardless of how
22629        // long unrelated Git subprocesses take under parallel test load.
22630        config.graph.timeout_verify = Some(2);
22631        config.graph.timeout_resource_wait = 0;
22632
22633        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
22634        let _held = match crate::cache::try_acquire(&home, &cache_dir, &other)
22635            .expect("no io error acquiring directly")
22636        {
22637            crate::cache::AcquireOutcome::Acquired(g) => g,
22638            crate::cache::AcquireOutcome::Busy(b) => {
22639                panic!("expected the direct acquire to win the lease first: {b:?}")
22640            }
22641        };
22642
22643        let mut state = RunState::new(
22644            repo.clone(),
22645            "main".to_owned(),
22646            "deadbeef".to_owned(),
22647            "task".to_owned(),
22648            config,
22649        );
22650        state.candidates = vec![Candidate {
22651            index: 0,
22652            label: 'A',
22653            agent: "alpha".to_owned(),
22654            branch: "does-not-exist".to_owned(),
22655            worktree: repo.clone(),
22656            summary: String::new(),
22657            stat: String::new(),
22658            files: 0,
22659            commits: 0,
22660            empty: false,
22661            failed: None,
22662            verified_noop: None,
22663            duration_ms: 0,
22664            folded: false,
22665        }];
22666        state.tally = Some(Tally {
22667            first_choice: BTreeMap::from([('A', 1)]),
22668            borda: BTreeMap::new(),
22669            winner: 'A',
22670            rankings: 1,
22671            unanimous_initial: true,
22672            deliberated: false,
22673            changed_votes: 0,
22674            unanimous_final: true,
22675            tie_break: None,
22676            judges: 0,
22677            present: 0,
22678            quorum: 0,
22679            met_quorum: true,
22680            uncontested: Some("only candidate A produced a change".to_owned()),
22681        });
22682        state.reviews = vec![ReviewRound {
22683            round: 1,
22684            head: "deadbeef".to_owned(),
22685            verified_head: None,
22686            verified_at: None,
22687            reviews: Vec::new(),
22688            e2e: Vec::new(),
22689            fix: None,
22690            blocking: 0,
22691            answered: 0,
22692            expected: 0,
22693            clean: true,
22694            verify_retried: false,
22695            e2e_deferred: false,
22696            e2e_defer_reason: None,
22697            progressed: false,
22698            vote_split: false,
22699            reconsideration: Vec::new(),
22700            verdict: None,
22701        }];
22702
22703        state.reviews[0].verified_head = Some(git::rev_parse(&repo, "HEAD").await.unwrap());
22704        state.reviews[0].e2e = vec![CommandOutcome {
22705            command: state.config.verify.e2e[0].clone(),
22706            code: Some(0),
22707            output_tail: String::new(),
22708            duration_ms: 0,
22709            resource_blocked: false,
22710            ..Default::default()
22711        }];
22712        let mut runner = Runner {
22713            state,
22714            roles: ResolvedRoles {
22715                implementers: Vec::new(),
22716                judges: Vec::new(),
22717                reviewers: Vec::new(),
22718                fixer: None,
22719                conductor: conductor(),
22720                implementer_roster: Vec::new(),
22721                judge_roster: Vec::new(),
22722                reviewer_roster: Vec::new(),
22723            },
22724            sem: Arc::new(Semaphore::new(1)),
22725            pause: Pause::new(),
22726            interrupt: Pause::new(),
22727        };
22728
22729        runner.gate().await.expect("gate");
22730        assert!(runner.state.resource_block.is_none());
22731        assert!(
22732            !runner
22733                .state
22734                .events
22735                .iter()
22736                .any(|event| { event.message.contains("waiting for the shared build cache") }),
22737            "a gate with nothing to run must never request the held cache lease"
22738        );
22739        assert!(
22740            runner.state.gate_ran,
22741            "zero commands is still a real, immediate attempt"
22742        );
22743        assert!(runner.state.gate.is_empty());
22744        assert_ne!(
22745            runner.state.status,
22746            RunStatus::Blocked,
22747            "must not read as resource-blocked on a lease it never asked for"
22748        );
22749    }
22750
22751    /// A separate process carries a live worker's environment throughout all
22752    /// verification entry points; the parallel harness never changes its env.
22753    #[cfg(unix)]
22754    #[tokio::test]
22755    async fn verification_is_standalone_inside_a_live_worker() {
22756        const CHILD: &str = "MAGI_VERIFY_WORKER_TEST";
22757        if std::env::var_os(CHILD).is_none() {
22758            let home = tempfile::tempdir().unwrap();
22759            let generation = crate::worker::pin_current(home.path()).unwrap();
22760            let output = std::process::Command::new(std::env::current_exe().unwrap())
22761                .args([
22762                    "--exact",
22763                    "graph::tests::verification_is_standalone_inside_a_live_worker",
22764                    "--nocapture",
22765                ])
22766                .env(CHILD, "1")
22767                .env("MAGI_HOME", home.path())
22768                .env("MAGI_WORKER_HOME", home.path())
22769                .env("MAGI_WORKER_ID", "abcdef")
22770                .env("MAGI_WORKER_GENERATION", &generation.id)
22771                .env("MAGI_WORKER_EXE", &generation.executable)
22772                .env("MAGI_RUN", "verification-parent")
22773                .env("MAGI_NODE", "gate")
22774                .env("MAGI_SEAT", "worker-fixture")
22775                .env("MAGI_PROCESS_OWNER", "fixture-owner")
22776                .env("MAGI_NO_AUTOUPDATE", "0")
22777                .env("VERIFY_EXPECT_PATH", std::env::var_os("PATH").unwrap())
22778                .env("VERIFY_AUTH_TOKEN", "fixture-auth")
22779                .env(
22780                    "VERIFY_EXPECT_TOOLCHAIN",
22781                    std::env::var_os("RUSTUP_TOOLCHAIN").unwrap_or_default(),
22782                )
22783                .env(
22784                    "VERIFY_EXPECT_CACHE",
22785                    std::env::var_os("CARGO_TARGET_DIR").unwrap_or_default(),
22786                )
22787                .output()
22788                .unwrap();
22789            assert!(
22790                output.status.success()
22791                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
22792                "{}\n{}",
22793                String::from_utf8_lossy(&output.stdout),
22794                String::from_utf8_lossy(&output.stderr)
22795            );
22796            return;
22797        }
22798        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
22799        let home = crate::run::home();
22800        let directory = home.join("workers/jobs/abcdef");
22801        std::fs::create_dir_all(&directory).unwrap();
22802        let job = crate::worker::Job {
22803            id: "abcdef".into(),
22804            sequence: 1,
22805            kind: "task".into(),
22806            key: "task:verification".into(),
22807            payload: serde_json::json!({}),
22808            generation: std::env::var("MAGI_WORKER_GENERATION").unwrap(),
22809            version: Some(env!("CARGO_PKG_VERSION").into()),
22810            status: crate::worker::Status::Running,
22811            result: None,
22812            pid: Some(std::process::id()),
22813            created_at: 0,
22814            finished_at: None,
22815        };
22816        std::fs::write(
22817            directory.join("job.json"),
22818            serde_json::to_vec(&job).unwrap(),
22819        )
22820        .unwrap();
22821        let _lease = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
22822        let assert_worker = || {
22823            assert_eq!(
22824                crate::worker::current_job(&home).unwrap().unwrap().id,
22825                job.id
22826            );
22827            assert_eq!(crate::worker::active(&home).unwrap().len(), 1);
22828            assert_eq!(
22829                crate::worker::helper_executable(&home).unwrap(),
22830                PathBuf::from(std::env::var_os("MAGI_WORKER_EXE").unwrap())
22831            );
22832            assert!(
22833                crate::updater::Checker::new(&crate::config::Update {
22834                    mode: crate::config::UpdateMode::Notify,
22835                    interval: None,
22836                    auto_restart: false,
22837                })
22838                .is_none(),
22839                "the driver remains pinned, even while tests are standalone"
22840            );
22841        };
22842        assert_worker();
22843        let repo = home.join("repo");
22844        std::fs::create_dir_all(&repo).unwrap();
22845        init_repo(&repo);
22846        // Keep storage, seat/control context, containment and tool lookup.
22847        // No inherited values (or credentials) are printed on success.
22848        let probe = r#"test -z "${MAGI_WORKER_ID+x}" &&
22849            test -z "${MAGI_WORKER_GENERATION+x}" &&
22850            test -z "${MAGI_WORKER_HOME+x}" &&
22851            test -z "${MAGI_WORKER_EXE+x}" &&
22852            test "$MAGI_HOME/repo" -ef . &&
22853            test "$MAGI_RUN" = verification-parent &&
22854            test "$MAGI_NODE" = gate &&
22855            test "$MAGI_SEAT" = worker-fixture &&
22856            test -n "$MAGI_PROCESS_OWNER" &&
22857            test "$PATH" = "$VERIFY_EXPECT_PATH" &&
22858            test "$VERIFY_AUTH_TOKEN" = fixture-auth &&
22859            test "$RUSTUP_TOOLCHAIN" = "$VERIFY_EXPECT_TOOLCHAIN" &&
22860            test "$CARGO_TARGET_DIR" = "$VERIFY_EXPECT_CACHE""#;
22861        // Negative control: an ordinary child inherits the contamination.
22862        assert!(
22863            !std::process::Command::new("sh")
22864                .args(["-c", probe])
22865                .current_dir(&repo)
22866                .status()
22867                .unwrap()
22868                .success()
22869        );
22870        let unrelated_home = tempfile::tempdir().unwrap();
22871        assert!(
22872            crate::worker::current_job(unrelated_home.path()).is_err(),
22873            "an inherited worker id cannot be resolved in a unit fixture's home"
22874        );
22875        let mut runner = runner_at(RunStatus::Gating);
22876        runner.state.repo = repo.clone();
22877        runner.state.config.disk.min_free_bytes = 0;
22878        runner.state.config.coordination = crate::config::test_coordination();
22879        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
22880        runner.state.config.verify.e2e = vec![format!("{probe} && printf 'e2e\\n' >> phases")];
22881        runner.state.config.verify.pre_gate = vec![format!("{probe} && printf 'pre\\n' >> phases")];
22882        runner.state.config.verify.gate = vec![format!("{probe} && printf 'gate\\n' >> phases")];
22883        let winner = Candidate {
22884            index: 0,
22885            label: 'A',
22886            agent: "fixture".into(),
22887            branch: "main".into(),
22888            worktree: repo.clone(),
22889            summary: String::new(),
22890            stat: String::new(),
22891            files: 0,
22892            commits: 0,
22893            empty: false,
22894            failed: None,
22895            verified_noop: None,
22896            duration_ms: 0,
22897            folded: false,
22898        };
22899        let (e2e, retried, pids) = run_e2e_with_retry(
22900            &mut runner.state,
22901            &["sh".into(), "-c".into()],
22902            &[format!("{probe} && printf initial")],
22903            &repo,
22904            Duration::from_secs(10),
22905            "initial",
22906            None,
22907        )
22908        .await;
22909        assert!(!retried && pids.is_empty());
22910        assert_eq!(e2e[0].code, Some(0), "{e2e:?}");
22911        assert_eq!(e2e[0].output_tail, "initial");
22912        let gate = runner.run_gate(&winner).await.unwrap();
22913        assert!(gate.iter().all(CommandOutcome::ok), "{gate:?}");
22914        // An interrupted repair must recheck e2e from saved state. Landing
22915        // reuses that state and must run both pre-gate and gate again.
22916        runner.state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
22917            git::rev_parse(&repo, "HEAD").await.unwrap(),
22918            false,
22919            Vec::new(),
22920        ));
22921        runner.state.save().unwrap();
22922        let mut resumed = RunState::load(&runner.state.id).unwrap();
22923        let wait = crate::repo_lock::WaitPolicy::default();
22924        assert!(matches!(
22925            check_gate_repair_e2e(&mut resumed, &winner, &wait)
22926                .await
22927                .unwrap(),
22928            GateFix::Retry
22929        ));
22930        let saved = RunState::load(&resumed.id).unwrap();
22931        let repair = saved.gate_repair_e2e.unwrap();
22932        assert!(repair.passed);
22933        assert_eq!(repair.outcomes.len(), 1);
22934        assert!(repair.outcomes[0].ok());
22935        let landing = run_landing_gate(&mut resumed, &winner, &wait)
22936            .await
22937            .unwrap();
22938        assert_eq!(landing.len(), 1);
22939        assert!(landing[0].ok(), "{landing:?}");
22940        assert_eq!(
22941            std::fs::read_to_string(repo.join("phases")).unwrap(),
22942            "pre\ngate\ne2e\npre\ngate\n"
22943        );
22944        assert_worker();
22945    }
22946
22947    #[cfg(unix)]
22948    #[tokio::test]
22949    async fn verification_keeps_the_panic_and_the_full_output() {
22950        crate::run::pin_test_home();
22951        let tmp = tempfile::tempdir().unwrap();
22952        let mut config = Config::default();
22953        config.disk.min_free_bytes = 0;
22954        let mut state = RunState::new(
22955            tmp.path().to_owned(),
22956            "main".into(),
22957            "base".into(),
22958            "verification evidence".into(),
22959            config,
22960        );
22961        let script = "echo \"thread 'x' panicked at t.rs:1:1:\"; echo 'boom assertion'; \
22962                      i=0; while [ $i -lt 20000 ]; do echo \"  $i: 0xabc - <a::b>\"; \
22963                      echo '             at /x/y.rs:1:1'; i=$((i+1)); done; exit 101";
22964        let mut names = Vec::new();
22965        for _ in 0..2 {
22966            let (outcomes, _) = run_commands(
22967                &mut state,
22968                "gate",
22969                "gate",
22970                0,
22971                &["sh".into(), "-c".into()],
22972                &[script.into()],
22973                tmp.path(),
22974                Duration::from_secs(60),
22975            )
22976            .await;
22977            let tail = &outcomes[0].output_tail;
22978            assert!(tail.contains("panicked at t.rs:1:1"), "{tail}");
22979            assert!(tail.contains("boom assertion"));
22980            assert!(tail.len() <= crate::run::VERIFY_SUMMARY + 100);
22981            let line = tail.lines().next().unwrap();
22982            names.push(line.to_owned());
22983        }
22984        assert_ne!(names[0], names[1], "the second run must not overwrite");
22985        let full = crate::run::read_artifact(&state, "gate-1.out").unwrap();
22986        assert!(full.len() > 500_000 && full.contains("boom assertion"));
22987        assert!(crate::run::read_artifact(&state, "gate-2.out").is_some());
22988
22989        // Storage failures are evidence too; preserve the command's verdict.
22990        std::fs::remove_dir_all(state.dir().join("artifacts")).unwrap();
22991        std::fs::write(state.dir().join("artifacts"), "blocked").unwrap();
22992        let (outcomes, _) = run_commands(
22993            &mut state,
22994            "gate",
22995            "gate",
22996            0,
22997            &["sh".into(), "-c".into()],
22998            &["echo failure-output; exit 7".into()],
22999            tmp.path(),
23000            Duration::from_secs(10),
23001        )
23002        .await;
23003        assert_eq!(outcomes[0].code, Some(7));
23004        assert!(state.events.iter().any(|e| {
23005            e.node == "gate" && e.message.contains("could not save the full gate output:")
23006        }));
23007    }
23008
23009    #[cfg(unix)]
23010    #[tokio::test]
23011    async fn verification_commands_distinguish_timeouts_signals_and_exit_codes() {
23012        crate::run::pin_test_home();
23013        let tmp = tempfile::tempdir().unwrap();
23014        let mut config = Config::default();
23015        config.disk.min_free_bytes = 0;
23016        let mut state = RunState::new(
23017            tmp.path().to_owned(),
23018            "main".into(),
23019            "base".into(),
23020            "verification evidence".into(),
23021            config,
23022        );
23023        let (outcomes, pids) = run_commands(
23024            &mut state,
23025            "gate",
23026            "gate",
23027            1,
23028            &["sh".into(), "-c".into()],
23029            &[
23030                "printf before-timeout; exec sleep 30".into(),
23031                "kill -TERM $$".into(),
23032                "exit 7".into(),
23033                "printf success".into(),
23034            ],
23035            tmp.path(),
23036            Duration::from_secs(1),
23037        )
23038        .await;
23039        wait_for_timed_out_children_to_die(&pids).await;
23040        assert_eq!(
23041            pids.len(),
23042            1,
23043            "unleased timeout retains its death-check PID"
23044        );
23045        assert_eq!(outcomes.len(), 4);
23046        assert_eq!(outcomes[0].code, None);
23047        assert!(outcomes[0].output_tail.contains("before-timeout"));
23048        assert!(outcomes[0].output_tail.contains("timed out after 1s"));
23049        assert_eq!(outcomes[1].code, None);
23050        assert!(outcomes[1].output_tail.contains("command terminated:"));
23051        assert!(!outcomes[1].output_tail.contains("timed out"));
23052        assert_eq!(outcomes[2].code, Some(7));
23053        assert!(!outcomes[2].output_tail.contains("timed out"));
23054        assert_eq!(outcomes[3].code, Some(0));
23055        assert_eq!(outcomes[3].output_tail, "success");
23056        assert!(outcomes.iter().all(|outcome| !outcome.resource_blocked));
23057    }
23058
23059    /// The addendum's second gap: a `verify.gate` command running for real
23060    /// wall-clock time had nothing at all to show for it in `active` before
23061    /// `run_commands` learned to record it — a run could sit in `Gating` for
23062    /// minutes with `magi show` and `GET /api/runs/{id}` both silent about
23063    /// what was actually happening. Proven with a genuinely still-running
23064    /// command, not just a before/after check on the final state: a poller
23065    /// task reads the same `run.json` `gate()` is writing, the same way the
23066    /// phone or `magi show` would, while the shell command is still blocked
23067    /// on its own release marker.
23068    #[tokio::test]
23069    async fn gate_records_a_running_task_entry_while_its_command_is_still_in_flight() {
23070        crate::run::pin_test_home();
23071
23072        let tmp = tempfile::tempdir().expect("tempdir");
23073        let repo = tmp.path().join("repo");
23074        std::fs::create_dir_all(&repo).unwrap();
23075        init_repo(&repo);
23076
23077        let mut config = Config::default();
23078        config.disk.min_free_bytes = 0;
23079        config.verify.gate = vec![
23080            "printf started > started.marker; i=0; while [ ! -f release.marker ] && \
23081             [ \"$i\" -lt 100 ]; do i=$((i+1)); sleep 0.05; done; test -f release.marker"
23082                .to_owned(),
23083        ];
23084
23085        let mut state = RunState::new(
23086            repo.clone(),
23087            "main".to_owned(),
23088            "deadbeef".to_owned(),
23089            "task".to_owned(),
23090            config,
23091        );
23092        let run_id = state.id.clone();
23093        state.candidates = vec![Candidate {
23094            index: 0,
23095            label: 'A',
23096            agent: "alpha".to_owned(),
23097            branch: "does-not-exist".to_owned(),
23098            worktree: repo.clone(),
23099            summary: String::new(),
23100            stat: String::new(),
23101            files: 0,
23102            commits: 0,
23103            empty: false,
23104            failed: None,
23105            verified_noop: None,
23106            duration_ms: 0,
23107            folded: false,
23108        }];
23109        state.tally = Some(Tally {
23110            first_choice: BTreeMap::from([('A', 1)]),
23111            borda: BTreeMap::new(),
23112            winner: 'A',
23113            rankings: 1,
23114            unanimous_initial: true,
23115            deliberated: false,
23116            changed_votes: 0,
23117            unanimous_final: true,
23118            tie_break: None,
23119            judges: 0,
23120            present: 0,
23121            quorum: 0,
23122            met_quorum: true,
23123            uncontested: Some("only candidate A produced a change".to_owned()),
23124        });
23125        state.reviews = vec![ReviewRound {
23126            round: 1,
23127            head: "deadbeef".to_owned(),
23128            verified_head: None,
23129            verified_at: None,
23130            reviews: Vec::new(),
23131            e2e: Vec::new(),
23132            fix: None,
23133            blocking: 0,
23134            answered: 0,
23135            expected: 0,
23136            clean: true,
23137            verify_retried: false,
23138            e2e_deferred: false,
23139            e2e_defer_reason: None,
23140            progressed: false,
23141            vote_split: false,
23142            reconsideration: Vec::new(),
23143            verdict: None,
23144        }];
23145
23146        let mut runner = Runner {
23147            state,
23148            roles: ResolvedRoles {
23149                implementers: Vec::new(),
23150                judges: Vec::new(),
23151                reviewers: Vec::new(),
23152                fixer: None,
23153                conductor: conductor(),
23154                implementer_roster: Vec::new(),
23155                judge_roster: Vec::new(),
23156                reviewer_roster: Vec::new(),
23157            },
23158            sem: Arc::new(Semaphore::new(1)),
23159            pause: Pause::new(),
23160            interrupt: Pause::new(),
23161        };
23162
23163        let started_marker = repo.join("started.marker");
23164        let release_marker = repo.join("release.marker");
23165        let observe = async {
23166            loop {
23167                if started_marker.exists()
23168                    && let Ok(s) = crate::run::RunState::load(&run_id)
23169                    && let Some(a) = s.active.get("gate")
23170                {
23171                    std::fs::write(&release_marker, b"go").expect("release marker");
23172                    break a.clone();
23173                }
23174                tokio::time::sleep(Duration::from_millis(50)).await;
23175            }
23176        };
23177        let captured = {
23178            let gate = runner.gate();
23179            tokio::pin!(gate);
23180            let captured = tokio::select! {
23181                observed = observe => observed,
23182                result = &mut gate => panic!(
23183                    "gate exited before its in-flight entry was observed: {result:?}"
23184                ),
23185            };
23186            gate.await.expect("gate");
23187            captured
23188        };
23189
23190        assert_eq!(captured.task.as_deref(), Some("gate"));
23191        assert_eq!(captured.node, "gate");
23192        assert_eq!(captured.index, Some(1));
23193        assert_eq!(captured.total, Some(1));
23194        assert!(
23195            captured
23196                .command
23197                .as_deref()
23198                .is_some_and(|c| c.contains("started.marker")),
23199            "{captured:?}"
23200        );
23201
23202        assert!(
23203            runner.state.active.is_empty(),
23204            "the entry must be cleared once the command actually finished: {:?}",
23205            runner.state.active
23206        );
23207        assert!(runner.state.gate_ran);
23208        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
23209    }
23210
23211    /// The hand-off over a blocking finding a reviewer rejected on leaves a
23212    /// record for `land`; one with only a Minor, or no reject, leaves none.
23213    #[tokio::test]
23214    async fn stop_reviewing_records_a_contested_hand_off_only_for_major_plus_reject() {
23215        use crate::verdict::{Finding, ReviewVote, Severity};
23216        crate::run::pin_test_home();
23217        let tmp = tempfile::tempdir().expect("tempdir");
23218        let repo = tmp.path().join("repo");
23219        std::fs::create_dir_all(&repo).unwrap();
23220        init_repo(&repo);
23221
23222        for (severity, vote, expect) in [
23223            (Severity::Major, ReviewVote::Reject, true),
23224            (Severity::Minor, ReviewVote::Reject, false),
23225            (Severity::Major, ReviewVote::Approve, false),
23226        ] {
23227            let mut round = review_round(false, 1, 1, 1, false, true);
23228            round.reviews = vec![ReviewRecord {
23229                reviewer: 1,
23230                agent: "alpha".to_owned(),
23231                summary: String::new(),
23232                findings: vec![Finding {
23233                    id: "R1-1-1".to_owned(),
23234                    severity,
23235                    file: None,
23236                    line: None,
23237                    title: "t".to_owned(),
23238                    detail: String::new(),
23239                }],
23240                vote: Some(vote),
23241                failed: None,
23242                duration_ms: 0,
23243                attempts: 0,
23244            }];
23245            let mut state = RunState::new(
23246                repo.clone(),
23247                "main".to_owned(),
23248                "deadbeef".to_owned(),
23249                "task".to_owned(),
23250                Config::default(),
23251            );
23252            state.reviews = vec![round];
23253            let mut runner = Runner {
23254                state,
23255                roles: ResolvedRoles {
23256                    implementers: Vec::new(),
23257                    judges: Vec::new(),
23258                    reviewers: Vec::new(),
23259                    fixer: None,
23260                    conductor: conductor(),
23261                    implementer_roster: Vec::new(),
23262                    judge_roster: Vec::new(),
23263                    reviewer_roster: Vec::new(),
23264                },
23265                sem: Arc::new(Semaphore::new(1)),
23266                pause: Pause::new(),
23267                interrupt: Pause::new(),
23268            };
23269            let shell = runner.state.config.shell();
23270            runner
23271                .stop_reviewing("round budget spent", &shell, &repo)
23272                .await
23273                .expect("stop_reviewing");
23274            assert_eq!(runner.state.status, RunStatus::Gating);
23275            assert_eq!(
23276                runner.state.contested_handoff.is_some(),
23277                expect,
23278                "{severity:?} + {vote:?}"
23279            );
23280        }
23281    }
23282
23283    /// The shape the incident this whole fix responds to actually had: the
23284    /// round budget spent, the last round's own e2e blocked on the shared
23285    /// build cache (held here by a live pid — this test process — exactly
23286    /// `cache`'s own unit tests' pattern for "another owner, still alive"
23287    /// without forking a process). `stop_reviewing` must retry it — not
23288    /// silently leave the round looking untouched (the catch-up-only half of
23289    /// the bug), and not read the contention as a red `e2e` and block the
23290    /// run on it (the other half). Called directly, the same way
23291    /// `gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run`
23292    /// above exercises `gate`, so this never needs a real cargo build to
23293    /// reach: the lease is never released, so `with_cache_lease` never gets
23294    /// past acquiring it into anything that would need a real workspace.
23295    #[tokio::test]
23296    async fn stop_reviewing_retries_a_resource_blocked_e2e_instead_of_reading_it_as_red() {
23297        crate::run::pin_test_home();
23298        let home = crate::run::home();
23299
23300        let tmp = tempfile::tempdir().expect("tempdir");
23301        let repo = tmp.path().join("repo");
23302        std::fs::create_dir_all(&repo).unwrap();
23303        init_repo(&repo);
23304        let head = crate::git::rev_parse(&repo, "HEAD")
23305            .await
23306            .expect("rev-parse");
23307        // Unique to this test, so holding its lease cannot collide with
23308        // another test sharing the same process-wide `home`.
23309        let cache_dir = tmp.path().join("target");
23310
23311        let mut config = Config::default();
23312        config.verify.e2e = vec![format!(
23313            "CARGO_TARGET_DIR='{}' test -f README.md",
23314            cache_dir.display()
23315        )];
23316        config.graph.review_rounds = 1;
23317        // Bounded so a regression that does start waiting fails the test in
23318        // seconds, not hangs it.
23319        config.graph.timeout_verify = Some(2);
23320        config.graph.timeout_resource_wait = 2;
23321
23322        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
23323        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
23324            .expect("no io error acquiring directly")
23325        {
23326            crate::cache::AcquireOutcome::Acquired(g) => g,
23327            crate::cache::AcquireOutcome::Busy(b) => {
23328                panic!("expected the direct acquire to win the lease first: {b:?}")
23329            }
23330        };
23331
23332        let mut state = RunState::new(
23333            repo.clone(),
23334            "main".to_owned(),
23335            head.clone(),
23336            "task".to_owned(),
23337            config,
23338        );
23339        state.candidates = vec![Candidate {
23340            index: 0,
23341            label: 'A',
23342            agent: "alpha".to_owned(),
23343            branch: "does-not-exist".to_owned(),
23344            worktree: repo.clone(),
23345            summary: String::new(),
23346            stat: String::new(),
23347            files: 0,
23348            commits: 0,
23349            empty: false,
23350            failed: None,
23351            verified_noop: None,
23352            duration_ms: 0,
23353            folded: false,
23354        }];
23355        state.tally = Some(Tally {
23356            first_choice: BTreeMap::from([('A', 1)]),
23357            borda: BTreeMap::new(),
23358            winner: 'A',
23359            rankings: 1,
23360            unanimous_initial: true,
23361            deliberated: false,
23362            changed_votes: 0,
23363            unanimous_final: true,
23364            tie_break: None,
23365            judges: 0,
23366            present: 0,
23367            quorum: 0,
23368            met_quorum: true,
23369            uncontested: Some("only candidate A produced a change".to_owned()),
23370        });
23371        // The round budget's last round, deferred: `needs_catchup_run`'s
23372        // other trigger. `stop_reviewing`'s retry machinery must treat this
23373        // exactly like a resource-blocked attempt once it actually runs.
23374        state.reviews = vec![ReviewRound {
23375            round: 1,
23376            head: head.clone(),
23377            verified_head: None,
23378            verified_at: None,
23379            reviews: Vec::new(),
23380            e2e: Vec::new(),
23381            fix: None,
23382            blocking: 1,
23383            answered: 1,
23384            expected: 1,
23385            clean: false,
23386            verify_retried: false,
23387            e2e_deferred: true,
23388            e2e_defer_reason: Some("1 blocking finding(s) already required a fix".to_owned()),
23389            progressed: false,
23390            vote_split: false,
23391            reconsideration: Vec::new(),
23392            verdict: None,
23393        }];
23394
23395        let mut runner = Runner {
23396            state,
23397            roles: ResolvedRoles {
23398                implementers: Vec::new(),
23399                judges: Vec::new(),
23400                reviewers: Vec::new(),
23401                fixer: None,
23402                conductor: conductor(),
23403                implementer_roster: Vec::new(),
23404                judge_roster: Vec::new(),
23405                reviewer_roster: Vec::new(),
23406            },
23407            sem: Arc::new(Semaphore::new(1)),
23408            pause: Pause::new(),
23409            interrupt: Pause::new(),
23410        };
23411
23412        let shell = runner.state.config.shell();
23413        runner
23414            .stop_reviewing("round budget spent", &shell, &repo)
23415            .await
23416            .expect("stop_reviewing");
23417
23418        let last = runner.state.reviews.last().expect("round record");
23419        assert_eq!(
23420            last.e2e_status(),
23421            E2eStatus::ResourceBlocked,
23422            "the shared cache is still held; the attempt must read as blocked, not deferred or \
23423             failed: {last:?}"
23424        );
23425        assert_eq!(
23426            last.verified_head.as_deref(),
23427            Some(head.as_str()),
23428            "which commit this attempt targeted is known even though nothing finished checking \
23429             it"
23430        );
23431        let first_attempt_at = last
23432            .verified_at
23433            .expect("when this attempt ran is known too");
23434        assert_ne!(
23435            runner.state.status,
23436            RunStatus::Blocked,
23437            "contention is evidence about the machine, not the patch — it must not settle the \
23438             run as blocked: {:?}",
23439            runner.state.status
23440        );
23441        assert!(
23442            !runner
23443                .state
23444                .events
23445                .iter()
23446                .any(|e| e.node == "review" && e.message.contains("e2e failed")),
23447            "a resource-blocked attempt must never be logged as a failed e2e: {:?}",
23448            runner.state.events
23449        );
23450
23451        // The cache is still held: a later reentry must retry the same
23452        // round's verification again — not leave it looking exactly as
23453        // untouched as the first blocked attempt, which is indistinguishable
23454        // from never having tried again at all.
23455        runner
23456            .stop_reviewing("round budget spent", &shell, &repo)
23457            .await
23458            .expect("stop_reviewing retry");
23459        assert_eq!(
23460            runner.state.reviews.len(),
23461            1,
23462            "no new round was started: {:?}",
23463            runner.state.reviews
23464        );
23465        let last = runner.state.reviews.last().expect("round record");
23466        assert_eq!(last.e2e_status(), E2eStatus::ResourceBlocked, "{last:?}");
23467        assert!(
23468            last.verified_at.expect("still known") > first_attempt_at,
23469            "a second reentry must be a fresh attempt, not a stale copy of the first"
23470        );
23471        assert_ne!(runner.state.status, RunStatus::Blocked);
23472
23473        held.release();
23474    }
23475
23476    #[cfg(unix)]
23477    #[tokio::test]
23478    async fn catchup_compile_failure_after_clean_base_sync_uses_remaining_review_rounds() {
23479        ask_test_home();
23480        for (max_rounds, reentry) in [(2, false), (2, true), (1, false)] {
23481            let tmp = tempfile::tempdir().unwrap();
23482            let repo = tmp.path().join("repo");
23483            std::fs::create_dir(&repo).unwrap();
23484            init_repo(&repo);
23485            let run_git = |args: &[&str]| {
23486                let out = std::process::Command::new("git")
23487                    .args(args)
23488                    .current_dir(&repo)
23489                    .output()
23490                    .unwrap();
23491                assert!(
23492                    out.status.success(),
23493                    "{args:?}: {}",
23494                    String::from_utf8_lossy(&out.stderr)
23495                );
23496            };
23497            let origin = tmp.path().join("origin.git");
23498            run_git(&["init", "--bare", origin.to_str().unwrap()]);
23499            run_git(&["remote", "add", "origin", origin.to_str().unwrap()]);
23500            std::fs::write(repo.join("spec.rs"), "struct AgentSpec {}\n").unwrap();
23501            run_git(&["add", "spec.rs"]);
23502            run_git(&["commit", "-m", "initial spec"]);
23503            run_git(&["push", "origin", "main"]);
23504            let base = git::rev_parse(&repo, "HEAD").await.unwrap();
23505            run_git(&["checkout", "-b", "fix/review"]);
23506            std::fs::write(
23507                repo.join("check.rs"),
23508                "include!(\"spec.rs\"); fn main() { let _ = AgentSpec {}; }\n",
23509            )
23510            .unwrap();
23511            run_git(&["add", "check.rs"]);
23512            run_git(&["commit", "-m", "use spec"]);
23513            let reviewed = git::rev_parse(&repo, "HEAD").await.unwrap();
23514            run_git(&["checkout", "main"]);
23515            std::fs::write(
23516                repo.join("spec.rs"),
23517                "struct AgentSpec { max_turn_secs: u64 }\n",
23518            )
23519            .unwrap();
23520            run_git(&["add", "spec.rs"]);
23521            run_git(&["commit", "-m", "extend spec"]);
23522            run_git(&["push", "origin", "main"]);
23523            run_git(&["checkout", "fix/review"]);
23524
23525            let mut runner = runner_at(RunStatus::Reviewing);
23526            runner.state.repo = repo.clone();
23527            runner.state.base_commit = base;
23528            runner.state.pr_head = Some("fix/review".into());
23529            runner.state.config.graph.review_rounds = max_rounds;
23530            runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
23531            runner.state.config.graph.sessions = false;
23532            runner.state.config.disk.min_free_bytes = 0;
23533            runner.state.config.verify.e2e =
23534                vec!["rustc --emit=metadata -o ../check.rmeta check.rs || { echo 'error: could not compile fixture' >&2; exit 101; }".into()];
23535            runner.state.candidates = vec![Candidate {
23536                index: 0,
23537                label: 'A',
23538                agent: "fixture".into(),
23539                branch: "fix/review".into(),
23540                worktree: repo.clone(),
23541                summary: String::new(),
23542                stat: String::new(),
23543                files: 1,
23544                commits: 1,
23545                empty: false,
23546                failed: None,
23547                verified_noop: None,
23548                duration_ms: 0,
23549                folded: false,
23550            }];
23551            runner.state.tally = Some(Tally {
23552                first_choice: BTreeMap::new(),
23553                borda: BTreeMap::new(),
23554                winner: 'A',
23555                rankings: 0,
23556                unanimous_initial: true,
23557                deliberated: false,
23558                changed_votes: 0,
23559                unanimous_final: true,
23560                tie_break: None,
23561                judges: 0,
23562                present: 0,
23563                quorum: 0,
23564                met_quorum: true,
23565                uncontested: Some("review-only".into()),
23566            });
23567            let mut last = review_round(false, 0, 1, 1, false, false);
23568            last.head = reviewed.clone();
23569            last.e2e_deferred = true;
23570            last.e2e[0].resource_blocked = true;
23571            last.e2e[0].output_tail = "waiting for the shared build cache".into();
23572            if max_rounds == 1 {
23573                last.e2e.clear();
23574            }
23575            runner.state.reviews = vec![last];
23576            let calls = tmp.path().join("fix-calls");
23577            let mut fixer = spec("repair");
23578            fixer
23579                .env
23580                .insert("FIX_CALLS".into(), calls.display().to_string());
23581            fixer.command = vec!["sh".into(), "-c".into(), r#"
23582                echo fix >> "$FIX_CALLS"
23583                grep -q E0063 "$MAGI_PROMPT_FILE" || exit 1
23584                grep -q max_turn_secs "$MAGI_PROMPT_FILE" || exit 1
23585                printf 'include!("spec.rs"); fn main() { let _ = AgentSpec { max_turn_secs: 0 }; }\n' > check.rs
23586                printf '{"addressed":[],"rejected":[],"notes":"initialize the new field"}\n'
23587            "#.into()];
23588            let mut reviewer = spec("reviewer");
23589            reviewer.command = vec![
23590                "sh".into(),
23591                "-c".into(),
23592                "printf '%s\\n' '{\"summary\":\"clean\",\"vote\":\"approve\",\"findings\":[]}'"
23593                    .into(),
23594            ];
23595            runner.roles.fixer = Some(vec![fixer]);
23596            runner.roles.reviewers = vec![reviewer];
23597
23598            runner.sync_to_base().await.unwrap();
23599            let rebased = git::rev_parse(&repo, "HEAD").await.unwrap();
23600            assert_ne!(rebased, reviewed);
23601            assert!(runner.state.base_sync.as_ref().unwrap().conflict.is_none());
23602            if reentry {
23603                // Simulate a crash after catch-up evidence was saved but before
23604                // dispatching the fixer. No dedicated pending-repair field exists.
23605                let shell = runner.state.config.shell();
23606                runner
23607                    .stop_unresolved_review("deferred verification", &shell, &repo)
23608                    .await
23609                    .unwrap();
23610                assert!(runner.catchup_repairable());
23611                assert!(!calls.exists());
23612                runner.state = RunState::load(&runner.state.id).unwrap();
23613                assert!(runner.catchup_repairable());
23614            }
23615            runner.review_loop().await.unwrap();
23616            let first = &runner.state.reviews[0];
23617            assert_eq!(first.head, reviewed);
23618            assert_eq!(first.verified_head.as_deref(), Some(rebased.as_str()));
23619            assert!(
23620                first.verify_retried,
23621                "a reproduced build failure gets exactly one retry: {:?}",
23622                first.e2e
23623            );
23624            assert!(first.e2e[0].output_tail.contains("E0063"));
23625            assert!(!runner.catchup_repairable());
23626            if max_rounds == 2 {
23627                assert_eq!(
23628                    runner.state.status,
23629                    RunStatus::Gating,
23630                    "{}",
23631                    crate::report::run(&runner.state)
23632                );
23633                assert_eq!(runner.state.reviews.len(), 2);
23634                assert!(first.fix.as_ref().unwrap().committed);
23635                assert!(runner.state.reviews[1].clean);
23636                assert_eq!(
23637                    runner
23638                        .state
23639                        .reviews
23640                        .iter()
23641                        .filter(|r| r.fix.is_some())
23642                        .count(),
23643                    1
23644                );
23645                assert_eq!(std::fs::read_to_string(&calls).unwrap().lines().count(), 1);
23646                assert_eq!(runner.state.reviews[1].e2e_status(), E2eStatus::Passed);
23647            } else {
23648                assert_eq!(runner.state.status, RunStatus::Blocked);
23649                assert!(first.fix.is_none());
23650                assert!(!calls.exists());
23651                let recovery = crate::recovery::assess(
23652                    "prior",
23653                    Some(&runner.state),
23654                    &runner.landing_base(),
23655                    crate::recovery::Relation::Diverged,
23656                );
23657                assert_eq!(recovery.mode, crate::recovery::Mode::FullReview);
23658                let reasons = recovery.reasons.join("\n");
23659                assert!(
23660                    reasons.contains(&reviewed) && reasons.contains(&rebased),
23661                    "{reasons}"
23662                );
23663                assert!(
23664                    reasons.contains("base sync to")
23665                        && reasons.contains("additional review is required"),
23666                    "{reasons}"
23667                );
23668            }
23669        }
23670    }
23671
23672    /// A resumed run — a fresh `Runner`, `self.state.reviews` already
23673    /// holding the round `stop_reviewing` left `ResourceBlocked` from a
23674    /// prior process — must not sit at `Reviewing` forever: `review_loop`'s
23675    /// own top-of-function fast path (`review_conclusion`) correctly reads
23676    /// this shape as `None` rather than guessing `Blocked`, and the loop's
23677    /// own `for` range is empty once the round budget is spent, so
23678    /// `review_loop` must retry the check itself rather than silently doing
23679    /// nothing. Reaches the exact same retry `stop_reviewing_retries_a_*`
23680    /// above exercises directly, but through `review_loop`'s own entry point
23681    /// this time, proving the wiring between the two rather than just the
23682    /// retry logic in isolation.
23683    #[tokio::test]
23684    async fn a_resumed_review_loop_retries_a_last_round_left_resource_blocked() {
23685        crate::run::pin_test_home();
23686        let home = crate::run::home();
23687
23688        let tmp = tempfile::tempdir().expect("tempdir");
23689        let repo = tmp.path().join("repo");
23690        std::fs::create_dir_all(&repo).unwrap();
23691        init_repo(&repo);
23692        let head = crate::git::rev_parse(&repo, "HEAD")
23693            .await
23694            .expect("rev-parse");
23695        let cache_dir = tmp.path().join("target");
23696
23697        let mut config = Config::default();
23698        config.verify.e2e = vec![format!(
23699            "CARGO_TARGET_DIR='{}' test -f README.md",
23700            cache_dir.display()
23701        )];
23702        config.graph.review_rounds = 1;
23703        config.graph.timeout_verify = Some(2);
23704        config.graph.timeout_resource_wait = 2;
23705
23706        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
23707        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
23708            .expect("no io error acquiring directly")
23709        {
23710            crate::cache::AcquireOutcome::Acquired(g) => g,
23711            crate::cache::AcquireOutcome::Busy(b) => {
23712                panic!("expected the direct acquire to win the lease first: {b:?}")
23713            }
23714        };
23715
23716        let mut state = RunState::new(
23717            repo.clone(),
23718            "main".to_owned(),
23719            head.clone(),
23720            "task".to_owned(),
23721            config,
23722        );
23723        state.candidates = vec![Candidate {
23724            index: 0,
23725            label: 'A',
23726            agent: "alpha".to_owned(),
23727            branch: "does-not-exist".to_owned(),
23728            worktree: repo.clone(),
23729            summary: String::new(),
23730            stat: String::new(),
23731            files: 0,
23732            commits: 0,
23733            empty: false,
23734            failed: None,
23735            verified_noop: None,
23736            duration_ms: 0,
23737            folded: false,
23738        }];
23739        state.tally = Some(Tally {
23740            first_choice: BTreeMap::from([('A', 1)]),
23741            borda: BTreeMap::new(),
23742            winner: 'A',
23743            rankings: 1,
23744            unanimous_initial: true,
23745            deliberated: false,
23746            changed_votes: 0,
23747            unanimous_final: true,
23748            tie_break: None,
23749            judges: 0,
23750            present: 0,
23751            quorum: 0,
23752            met_quorum: true,
23753            uncontested: Some("only candidate A produced a change".to_owned()),
23754        });
23755        // The exact shape a prior process's `stop_reviewing` would have left
23756        // on disk: the round budget's last round, a real attempt already
23757        // made and already resource-blocked.
23758        state.reviews = vec![ReviewRound {
23759            round: 1,
23760            head: head.clone(),
23761            verified_head: Some(head.clone()),
23762            verified_at: Some(jiff::Timestamp::now()),
23763            reviews: Vec::new(),
23764            e2e: vec![CommandOutcome {
23765                command: format!(
23766                    "CARGO_TARGET_DIR='{}' test -f README.md",
23767                    cache_dir.display()
23768                ),
23769                code: None,
23770                output_tail: "waiting for the shared build cache".to_owned(),
23771                duration_ms: 0,
23772                resource_blocked: true,
23773                ..Default::default()
23774            }],
23775            fix: None,
23776            blocking: 1,
23777            answered: 1,
23778            expected: 1,
23779            clean: false,
23780            verify_retried: false,
23781            e2e_deferred: false,
23782            e2e_defer_reason: None,
23783            progressed: false,
23784            vote_split: false,
23785            reconsideration: Vec::new(),
23786            verdict: None,
23787        }];
23788
23789        let first_attempt_at = state.reviews[0].verified_at.expect("set above");
23790        let mut runner = Runner {
23791            state,
23792            roles: ResolvedRoles {
23793                implementers: Vec::new(),
23794                judges: Vec::new(),
23795                reviewers: Vec::new(),
23796                fixer: None,
23797                conductor: conductor(),
23798                implementer_roster: Vec::new(),
23799                judge_roster: Vec::new(),
23800                reviewer_roster: Vec::new(),
23801            },
23802            sem: Arc::new(Semaphore::new(1)),
23803            pause: Pause::new(),
23804            interrupt: Pause::new(),
23805        };
23806
23807        // The lease is still held throughout, so this reentry's own retry is
23808        // also contended — proving `review_loop` actually tried again (not
23809        // that it happened to succeed) is what the timestamp comparison
23810        // below is for.
23811        runner.review_loop().await.expect("review_loop");
23812
23813        assert_eq!(
23814            runner.state.reviews.len(),
23815            1,
23816            "no new round was started on top of the unresolved one: {:?}",
23817            runner.state.reviews
23818        );
23819        let last = &runner.state.reviews[0];
23820        assert_eq!(
23821            last.e2e_status(),
23822            E2eStatus::ResourceBlocked,
23823            "still contended: {last:?}"
23824        );
23825        assert!(
23826            last.verified_at.expect("still known") > first_attempt_at,
23827            "review_loop must have actually retried the check, not left it exactly as found"
23828        );
23829        assert_ne!(
23830            runner.state.status,
23831            RunStatus::Blocked,
23832            "a resumed run must not read leftover contention as a verdict on the patch: {:?}",
23833            runner.state.status
23834        );
23835
23836        held.release();
23837    }
23838
23839    #[tokio::test]
23840    async fn stopped_landing_resumes_from_structured_pr_even_with_legacy_gating_status() {
23841        crate::run::pin_test_home();
23842        for status in [RunStatus::Blocked, RunStatus::Gating] {
23843            let mut runner = runner_at(status);
23844            runner.state.config.graph.land = true;
23845            runner.state.gate_ran = true;
23846            runner.state.merge = Some(MergeOutcome {
23847                mode: MergeMode::Pr,
23848                ok: false,
23849                detail: "the fixer produced no commit".into(),
23850                empty: false,
23851            });
23852            let url = "https://example.invalid/o/r/pull/1";
23853            runner.state.pr = Some(crate::run::PrRecord {
23854                url: url.into(),
23855                number: 1,
23856                state: "open".into(),
23857                checks: "red".into(),
23858                round: 1,
23859                rounds: 1,
23860                red_at_merge: Vec::new(),
23861            });
23862            runner.state.save().unwrap();
23863            // The nonexistent repository makes observation fail before a forge
23864            // command can run. We still must reach land, rather than silently
23865            // return from the graph with its old gate and merge records.
23866            runner.execute_graph().await.unwrap();
23867            assert_eq!(runner.state.status, RunStatus::Blocked);
23868            assert!(runner.state.land_sync_pending);
23869            assert!(runner.state.events.iter().any(|event|
23870                event.node == "land" && event.message == format!("watching {url}")));
23871            assert_eq!(
23872                runner.state.merge.as_ref().unwrap().detail,
23873                "the fixer produced no commit"
23874            );
23875        }
23876    }
23877
23878    #[tokio::test]
23879    async fn a_run_resumed_mid_landing_reenters_land_instead_of_opening_a_second_pull_request() {
23880        crate::run::pin_test_home();
23881        let tmp = tempfile::tempdir().expect("tempdir");
23882        let repo = tmp.path().join("repo");
23883        std::fs::create_dir_all(&repo).unwrap();
23884        init_repo(&repo);
23885
23886        let mut config = Config::default();
23887        config.merge.mode = MergeMode::Pr;
23888        config.graph.land = true;
23889        config.graph.land_approval = false;
23890
23891        let mut state = RunState::new(
23892            repo.clone(),
23893            "main".to_owned(),
23894            "deadbeef".to_owned(),
23895            "task".to_owned(),
23896            config,
23897        );
23898        state.candidates = vec![Candidate {
23899            index: 0,
23900            label: 'A',
23901            agent: "alpha".to_owned(),
23902            branch: "does-not-exist".to_owned(),
23903            worktree: repo.clone(),
23904            summary: String::new(),
23905            stat: String::new(),
23906            files: 0,
23907            commits: 0,
23908            empty: false,
23909            failed: None,
23910            verified_noop: None,
23911            duration_ms: 0,
23912            folded: false,
23913        }];
23914        state.tally = Some(Tally {
23915            first_choice: BTreeMap::from([('A', 1)]),
23916            borda: BTreeMap::new(),
23917            winner: 'A',
23918            rankings: 1,
23919            unanimous_initial: true,
23920            deliberated: false,
23921            changed_votes: 0,
23922            unanimous_final: true,
23923            tie_break: None,
23924            judges: 0,
23925            present: 0,
23926            quorum: 0,
23927            met_quorum: true,
23928            uncontested: Some("only candidate A produced a change".to_owned()),
23929        });
23930        state.reviews = vec![ReviewRound {
23931            round: 1,
23932            head: "deadbeef".to_owned(),
23933            verified_head: None,
23934            verified_at: None,
23935            reviews: Vec::new(),
23936            e2e: Vec::new(),
23937            fix: None,
23938            blocking: 0,
23939            answered: 0,
23940            expected: 0,
23941            clean: true,
23942            verify_retried: false,
23943            e2e_deferred: false,
23944            e2e_defer_reason: None,
23945            progressed: false,
23946            vote_split: false,
23947            reconsideration: Vec::new(),
23948            verdict: None,
23949        }];
23950        state.gate = vec![CommandOutcome {
23951            command: "test".to_owned(),
23952            code: Some(0),
23953            output_tail: String::new(),
23954            duration_ms: 0,
23955            resource_blocked: false,
23956            ..Default::default()
23957        }];
23958        state.gate_ran = true;
23959        // A first pass through `merge` already pushed and opened this pull
23960        // request; `status` is `Landing` because a previous call into `land`
23961        // parked or was interrupted before it reached a terminal outcome.
23962        state.status = RunStatus::Landing;
23963        state.merge = Some(MergeOutcome {
23964            mode: MergeMode::Pr,
23965            ok: true,
23966            detail: "https://example.invalid/x/y/pull/1".to_owned(),
23967            empty: false,
23968        });
23969
23970        // The Landing-resume shortcut calls `run_land` directly rather than
23971        // through `merge`, which is exactly the call site that used to skip
23972        // `settle_questions` - see the fixture below.
23973        ask_test_home();
23974        // A real resume loads a persisted run; driver ownership is checked
23975        // against that record before the Landing shortcut is entered.
23976        state.save().expect("save landing run");
23977        let store = ask::Questions::open();
23978        let q = ask_open_question(&store, &state.id);
23979
23980        let mut runner = Runner {
23981            state,
23982            roles: ResolvedRoles {
23983                implementers: Vec::new(),
23984                judges: Vec::new(),
23985                reviewers: Vec::new(),
23986                fixer: None,
23987                conductor: conductor(),
23988                implementer_roster: Vec::new(),
23989                judge_roster: Vec::new(),
23990                reviewer_roster: Vec::new(),
23991            },
23992            sem: Arc::new(Semaphore::new(1)),
23993            pause: Pause::new(),
23994            interrupt: Pause::new(),
23995        };
23996
23997        // `execute`, not `merge` directly: the Landing-resume shortcut lives
23998        // at the top of `execute`, not inside `merge` (see `execute`'s doc)
23999        // exactly because `review_loop` would otherwise clobber the marker
24000        // first.
24001        runner.execute().await.expect("execute");
24002
24003        assert_eq!(
24004            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
24005            Some("https://example.invalid/x/y/pull/1"),
24006            "reentry must not push again or open a second pull request over the \
24007             one `land` is already watching"
24008        );
24009        assert_ne!(
24010            runner.state.status,
24011            RunStatus::Landing,
24012            "land could not actually reach the fake pull request, so it must \
24013             have given up rather than left the run silently parked forever"
24014        );
24015        // `land` could not reach the fake pull request, so it gave up into
24016        // `Blocked` - still resumable, so the question must not have been
24017        // swept just because this branch now also calls `settle_questions`.
24018        assert_eq!(runner.state.status, RunStatus::Blocked);
24019        assert!(
24020            store.get(&q.id).unwrap().status.open(),
24021            "Blocked is still alive; settle_questions must have been a no-op here"
24022        );
24023    }
24024
24025    fn state_with_round(round: ReviewRound) -> RunState {
24026        let mut s = RunState::new(
24027            PathBuf::from("/repo"),
24028            "main".to_owned(),
24029            "abc1234".to_owned(),
24030            "add retries".to_owned(),
24031            Config::default(),
24032        );
24033        s.reviews = vec![round];
24034        s
24035    }
24036
24037    fn finding(id: &str, severity: Severity, title: &str) -> crate::verdict::Finding {
24038        crate::verdict::Finding {
24039            id: id.to_owned(),
24040            severity,
24041            file: None,
24042            line: None,
24043            title: title.to_owned(),
24044            detail: String::new(),
24045        }
24046    }
24047
24048    #[test]
24049    fn pr_body_names_open_findings_and_declined_ones() {
24050        let round = ReviewRound {
24051            round: 2,
24052            head: "deadbee".to_owned(),
24053            verified_head: None,
24054            verified_at: None,
24055            reviews: vec![ReviewRecord {
24056                attempts: 0,
24057                reviewer: 1,
24058                agent: "alpha".to_owned(),
24059                summary: String::new(),
24060                findings: vec![finding("R2-1-1", Severity::Minor, "unused import")],
24061                vote: None,
24062                failed: None,
24063                duration_ms: 0,
24064            }],
24065            e2e: vec![CommandOutcome {
24066                command: "cargo test".to_owned(),
24067                code: Some(0),
24068                output_tail: String::new(),
24069                duration_ms: 0,
24070                resource_blocked: false,
24071                ..Default::default()
24072            }],
24073            verify_retried: false,
24074            e2e_deferred: false,
24075            e2e_defer_reason: None,
24076            fix: Some(FixRecord {
24077                agent: "alpha".to_owned(),
24078                addressed: Vec::new(),
24079                rejected: vec![crate::verdict::Rejection {
24080                    id: "R1-1-1".to_owned(),
24081                    why: "not reachable from any caller".to_owned(),
24082                }],
24083                notes: String::new(),
24084                committed: true,
24085                failed: None,
24086                duration_ms: 0,
24087                continuation: None,
24088            }),
24089            blocking: 0,
24090            answered: 1,
24091            expected: 1,
24092            clean: false,
24093            progressed: true,
24094            vote_split: false,
24095            reconsideration: Vec::new(),
24096            verdict: None,
24097        };
24098        let state = state_with_round(round);
24099        let body = pr_message(&state, 'A').body;
24100
24101        assert!(body.contains("add retries"), "the task must still be there");
24102        assert!(body.contains("R2-1-1"), "{body}");
24103        assert!(!body.contains("unused import"), "{body}");
24104        assert!(body.contains("R1-1-1"), "the declined finding: {body}");
24105        assert!(
24106            !body.contains("not reachable from any caller"),
24107            "the reason it was declined: {body}"
24108        );
24109    }
24110
24111    #[test]
24112    fn pr_body_says_nothing_extra_when_the_round_was_clean() {
24113        let round = ReviewRound {
24114            round: 1,
24115            head: "deadbee".to_owned(),
24116            verified_head: None,
24117            verified_at: None,
24118            reviews: vec![ReviewRecord {
24119                attempts: 0,
24120                reviewer: 1,
24121                agent: "alpha".to_owned(),
24122                summary: String::new(),
24123                findings: Vec::new(),
24124                vote: None,
24125                failed: None,
24126                duration_ms: 0,
24127            }],
24128            e2e: Vec::new(),
24129            verify_retried: false,
24130            e2e_deferred: false,
24131            e2e_defer_reason: None,
24132            fix: None,
24133            blocking: 0,
24134            answered: 1,
24135            expected: 1,
24136            clean: true,
24137            progressed: false,
24138            vote_split: false,
24139            reconsideration: Vec::new(),
24140            verdict: None,
24141        };
24142        let state = state_with_round(round);
24143        let body = pr_message(&state, 'A').body;
24144        assert!(!body.contains("Open review findings"), "{body}");
24145        assert!(!body.contains("Declined"), "{body}");
24146    }
24147
24148    fn state_with_summary(instruction: &str, summary: &str) -> RunState {
24149        let mut state = RunState::new(
24150            PathBuf::from("/repo"),
24151            "main".to_owned(),
24152            "abc1234".to_owned(),
24153            instruction.to_owned(),
24154            Config::default(),
24155        );
24156        // These fixtures test execution flow, independent of host disk capacity.
24157        state.config.disk.min_free_bytes = 0;
24158        state.candidates.push(Candidate {
24159            index: 0,
24160            label: 'A',
24161            agent: "alpha".to_owned(),
24162            branch: "magi/x/A".to_owned(),
24163            worktree: PathBuf::from("/wt"),
24164            summary: summary.to_owned(),
24165            stat: String::new(),
24166            files: 1,
24167            commits: 1,
24168            empty: false,
24169            failed: None,
24170            verified_noop: None,
24171            folded: false,
24172            duration_ms: 0,
24173        });
24174        state
24175    }
24176
24177    fn review_state(subjects: &[&str]) -> RunState {
24178        let mut state = state_with_summary(
24179            "Review the work already on branch `magi/x/A`. There is no task statement: what the change claims to do is whatever its commits say.\n\nfirst\nsecond",
24180            "",
24181        );
24182        state.candidates[0].agent = EXISTING_BRANCH.to_owned();
24183        state.reviewed_commits = Some(subjects.iter().map(|s| (*s).to_owned()).collect());
24184        state
24185    }
24186
24187    /// A branch rebased onto a main that moved past the recorded
24188    /// `base_commit` is titled from its own first commit, never main's.
24189    #[tokio::test]
24190    async fn a_rebased_review_branch_is_titled_from_its_own_commits() {
24191        ask_test_home();
24192        let tmp = tempfile::tempdir().unwrap();
24193        let repo = tmp.path().join("repo");
24194        std::fs::create_dir_all(&repo).unwrap();
24195        init_repo(&repo);
24196        let origin = tmp.path().join("origin.git");
24197        let g = |dir: &Path, args: &[&str]| {
24198            let out = std::process::Command::new("git")
24199                .args(args)
24200                .current_dir(dir)
24201                .quiet()
24202                .output()
24203                .expect("spawn git");
24204            assert!(
24205                out.status.success(),
24206                "git {args:?}: {}",
24207                String::from_utf8_lossy(&out.stderr)
24208            );
24209        };
24210        g(
24211            tmp.path(),
24212            &[
24213                "clone",
24214                "--bare",
24215                "-q",
24216                repo.to_str().unwrap(),
24217                origin.to_str().unwrap(),
24218            ],
24219        );
24220        g(
24221            &repo,
24222            &["remote", "add", "origin", origin.to_str().unwrap()],
24223        );
24224        let c1 = git::rev_parse(&repo, "main").await.unwrap();
24225
24226        // Main moves on; the branch is built on top of the new main.
24227        std::fs::write(repo.join("dep.txt"), "bump\n").unwrap();
24228        g(&repo, &["add", "-A"]);
24229        g(
24230            &repo,
24231            &["commit", "-q", "-m", "chore(deps): update a crate"],
24232        );
24233        g(&repo, &["push", "-q", "origin", "main"]);
24234        g(&repo, &["checkout", "-q", "-b", "feat/own"]);
24235        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
24236        g(&repo, &["add", "-A"]);
24237        g(
24238            &repo,
24239            &["commit", "-q", "-m", "fix(daemon): apply a chosen action"],
24240        );
24241        g(&repo, &["checkout", "-q", "main"]);
24242
24243        let start = review_base(&repo, "origin", "main", &c1, "feat/own").await;
24244        assert_eq!(start, git::rev_parse(&repo, "main").await.unwrap());
24245        // Without a readable tracking ref the recorded base's merge base is used.
24246        let fallback = review_base(&repo, "nowhere", "main", &c1, "feat/own").await;
24247        assert_eq!(fallback, c1);
24248
24249        let mut state = review_state(&[
24250            "chore(deps): update a crate",
24251            "fix(daemon): apply a chosen action",
24252        ]);
24253        state.repo = repo.clone();
24254        state.base_branch = "main".to_owned();
24255        state.base_commit = c1;
24256        refresh_reviewed_commits(&mut state, "feat/own").await;
24257        assert_eq!(
24258            state.reviewed_commits,
24259            Some(vec!["fix(daemon): apply a chosen action".to_owned()])
24260        );
24261        assert_eq!(
24262            review_title(&state).as_deref(),
24263            Some("fix(daemon): apply a chosen action")
24264        );
24265        assert_eq!(
24266            leaked_subjects(&state, "feat/own").await,
24267            Some(vec!["chore(deps): update a crate".to_owned()])
24268        );
24269        // A stale tracking ref is still used when the fetch fails, but the
24270        // leak list is withheld.
24271        state.config.merge.remote = "nowhere".to_owned();
24272        assert_eq!(leaked_subjects(&state, "feat/own").await, None);
24273    }
24274
24275    /// A review-only run whose winner is `feat/own`, checked out in `repo`,
24276    /// with `origin/main` one commit behind it, and a summarizing agent that
24277    /// prints whatever `reply` holds.
24278    struct SummaryFixture {
24279        _tmp: tempfile::TempDir,
24280        repo: PathBuf,
24281        reply: PathBuf,
24282        runner: Runner,
24283    }
24284
24285    fn summary_fixture() -> SummaryFixture {
24286        ask_test_home();
24287        let tmp = tempfile::tempdir().unwrap();
24288        let repo = tmp.path().join("repo");
24289        std::fs::create_dir_all(&repo).unwrap();
24290        init_repo(&repo);
24291        let origin = tmp.path().join("origin.git");
24292        let g = |args: &[&str]| {
24293            let out = std::process::Command::new("git")
24294                .args(args)
24295                .current_dir(&repo)
24296                .quiet()
24297                .output()
24298                .expect("spawn git");
24299            assert!(
24300                out.status.success(),
24301                "git {args:?}: {}",
24302                String::from_utf8_lossy(&out.stderr)
24303            );
24304        };
24305        g(&["init", "-q", "--bare", origin.to_str().unwrap()]);
24306        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
24307        g(&["push", "-q", "origin", "main"]);
24308        g(&["checkout", "-q", "-b", "feat/own"]);
24309        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
24310        g(&["add", "-A"]);
24311        g(&["commit", "-q", "-m", "feat(own): add the own file"]);
24312        let reply = tmp.path().join("reply.txt");
24313        std::fs::write(
24314            &reply,
24315            "TITLE: feat(own): add the own file\nAdds `own.txt` so the first summary is read.",
24316        )
24317        .unwrap();
24318        let mut runner = runner_at(RunStatus::Gating);
24319        let mut state = review_state(&["feat(own): add the own file"]);
24320        state.repo = repo.clone();
24321        state.base_branch = "main".to_owned();
24322        state.candidates[0].branch = "feat/own".to_owned();
24323        state.candidates[0].worktree = repo.clone();
24324        let mut author = spec("alpha");
24325        author.command = vec!["sh".into(), "-c".into(), "cat \"$REPLY_FILE\"".into()];
24326        author
24327            .env
24328            .insert("REPLY_FILE".into(), reply.to_string_lossy().into_owned());
24329        state.config.agents = vec![author];
24330        runner.state = state;
24331        SummaryFixture {
24332            _tmp: tmp,
24333            repo,
24334            reply,
24335            runner,
24336        }
24337    }
24338
24339    async fn posted(f: &mut SummaryFixture) -> PrMessage {
24340        let winner = f.runner.state.candidates[0].clone();
24341        f.runner
24342            .guarded_pr_message(&winner, None, true)
24343            .await
24344            .unwrap()
24345            .expect("an English description never parks")
24346    }
24347
24348    fn clean_round_with_minor_findings() -> ReviewRound {
24349        let mut round = passing_round(2, None);
24350        round.verdict = Some(crate::verdict::ReviewVote::ApproveWithFindings);
24351        round.reviews = vec![ReviewRecord {
24352            attempts: 0,
24353            reviewer: 1,
24354            agent: "alpha".into(),
24355            summary: "内部レビュー".into(),
24356            findings: vec![
24357                finding("R2-1-1", Severity::Minor, "未修正の懸念その一"),
24358                finding("R2-1-2", Severity::Minor, "未修正の懸念その二"),
24359            ],
24360            vote: Some(crate::verdict::ReviewVote::ApproveWithFindings),
24361            failed: None,
24362            duration_ms: 0,
24363        }];
24364        round
24365    }
24366
24367    #[tokio::test]
24368    async fn public_descriptions_cover_minor_findings_from_clean_rounds_in_both_modes() {
24369        for review_only in [false, true] {
24370            let mut f = summary_fixture();
24371            if !review_only {
24372                f.runner.state.candidates[0].agent = "alpha".into();
24373            }
24374            f.runner.state.reviews = vec![clean_round_with_minor_findings()];
24375            assert!(f.runner.state.reviews[0].clean);
24376            assert!(f.runner.state.reviews[0].fix.is_none());
24377            assert!(f.runner.state.open_findings().is_empty());
24378            assert_eq!(
24379                crate::pr_outcome::required_finding_ids(&f.runner.state),
24380                ["R2-1-1", "R2-1-2"]
24381            );
24382            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24383            let evidence = crate::pr_outcome::summary_evidence(
24384                &f.runner.state,
24385                crate::pr_outcome::FinalHead::At(&head),
24386            );
24387            assert!(
24388                evidence.contains("未修正の懸念その一") && evidence.contains("未修正の懸念その二")
24389            );
24390            // The ordinary reply omits both IDs: no cached description is adopted.
24391            let omitted = posted(&mut f).await;
24392            assert!(omitted.body.contains("No description"));
24393            assert!(omitted.body.contains("`R2-1-1` [Minor]"));
24394            assert!(omitted.body.contains("`R2-1-2` [Minor]"));
24395            assert!(f.runner.state.change_summary.is_none());
24396            std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nAdds the own file. R2-1-1 [Minor]: improve documentation for callers. R2-1-2 [Minor]: consider the remaining edge case.").unwrap();
24397            let described = posted(&mut f).await;
24398            assert!(described.body.contains("improve documentation for callers"));
24399            assert!(described.body.contains("remaining edge case"));
24400            assert!(described.body.contains("## Open review findings"));
24401            assert!(!described.body.contains("未修正"));
24402        }
24403    }
24404
24405    async fn rewrite_fixture_with_findings(review_only: bool, reply: &str) -> SummaryFixture {
24406        let mut f = summary_fixture();
24407        if !review_only {
24408            f.runner.state.candidates[0].agent = "alpha".into();
24409        }
24410        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24411        let mut fixed = round_with_notes(1, Some("日本語の内部修正報告"));
24412        fixed
24413            .fix
24414            .as_mut()
24415            .unwrap()
24416            .rejected
24417            .push(crate::verdict::Rejection {
24418                id: "R1-1-1".into(),
24419                why: "呼び出されないコードのため辞退".into(),
24420            });
24421        let mut clean = clean_round_with_minor_findings();
24422        clean.verified_head = Some(head.clone());
24423        f.runner.state.reviews = vec![fixed, clean];
24424        ok_gate(&mut f.runner.state, Some(&head));
24425        std::fs::write(&f.reply, "TITLE: fix: public description\n日本語の公開用説明です。R1-1-1 は辞退。R2-1-1 と R2-1-2 の懸念が残ります。").unwrap();
24426        f.runner.state.config.agents.push(scripted("beta", reply));
24427        f.runner.state.config.roles.language_judge =
24428            Some(crate::config::AgentChoice::One("beta".into()));
24429        f
24430    }
24431
24432    #[tokio::test]
24433    async fn posting_rewrite_retains_structured_evidence_and_finding_explanations() {
24434        for review_only in [false, true] {
24435            let mut f = rewrite_fixture_with_findings(review_only,
24436                "TITLE: fix: public description\nR1-1-1: declined because no caller reaches this code. R2-1-1 [Minor]: documentation remains incomplete. R2-1-2 [Minor]: an edge case needs follow-up.").await;
24437            let m = posted(&mut f).await;
24438            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24439            let expected =
24440                public_pr_evidence(&f.runner.state, crate::pr_outcome::FinalHead::At(&head));
24441            assert!(m.body.contains(&expected));
24442            assert!(m.body.contains("## Review rounds"));
24443            assert!(
24444                m.body
24445                    .contains("Gate (`verify.gate`): passed on the final commit")
24446            );
24447            assert!(
24448                m.body
24449                    .contains("Tests (`verify.e2e`): passed on the final commit")
24450            );
24451            let c = f.runner.state.change_summary.as_ref().unwrap();
24452            assert!(
24453                m.body
24454                    .contains(&format!("Evidence: final diff `{}`..`{}`", c.base, head))
24455            );
24456            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
24457            assert!(crate::pr_outcome::covers_required_findings(
24458                &f.runner.state,
24459                &m.body
24460            ));
24461            assert!(m.body.contains("documentation remains incomplete"));
24462            assert!(!m.body.contains("内部") && !m.body.contains("辞退"));
24463            assert_eq!(f.runner.state.seats["github-text-rewrite"].turns, 1);
24464            assert!(f.runner.state.github_text.is_none());
24465        }
24466    }
24467
24468    #[tokio::test]
24469    async fn posting_rewrite_missing_required_finding_context_is_not_offered_or_published() {
24470        for review_only in [false, true] {
24471            for reply in [
24472                "TITLE: fix: public description\nA short English description.",
24473                "TITLE: fix: public description\nR1-1-1 and R2-1-2 remain; R2-1-1-extra is a different ID.",
24474            ] {
24475                let mut f = rewrite_fixture_with_findings(review_only, reply).await;
24476                let winner = f.runner.state.candidates[0].clone();
24477                let posted = f
24478                    .runner
24479                    .guarded_pr_message(&winner, None, true)
24480                    .await
24481                    .unwrap();
24482                assert!(posted.is_none());
24483                assert!(f.runner.state.parked);
24484                let withheld = f.runner.state.github_text.as_ref().unwrap();
24485                assert!(
24486                    withheld.rewrite.is_none(),
24487                    "an incomplete rewrite must not be selectable"
24488                );
24489                let q = ask::Questions::open()
24490                    .get(withheld.question.as_ref().unwrap())
24491                    .unwrap();
24492                assert!(
24493                    !q.choices
24494                        .contains(&crate::github_text::USE_REWRITE.to_owned())
24495                );
24496                assert!(
24497                    q.detail.contains("R1-1-1")
24498                        && q.detail.contains("R2-1-1")
24499                        && q.detail.contains("R2-1-2")
24500                );
24501            }
24502        }
24503    }
24504
24505    #[tokio::test]
24506    async fn japanese_reports_stay_local_in_both_public_run_modes() {
24507        for review_only in [false, true] {
24508            let mut f = summary_fixture();
24509            if !review_only {
24510                f.runner.state.candidates[0].agent = "alpha".into();
24511            }
24512            f.runner.state.instruction = "内部タスクの説明".into();
24513            f.runner.state.candidates[0].summary = "内部の候補報告".into();
24514            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24515            f.runner.state.reviews = vec![
24516                round_with_notes(1, Some("コミットできません。テストは実行できません。")),
24517                round_with_notes(2, Some("二回目の内部修正報告です。")),
24518                passing_round(3, Some(&head)),
24519            ];
24520            f.runner.state.reviews[0].fix.as_mut().unwrap().addressed = vec!["R1-1-1".into()];
24521            ok_gate(&mut f.runner.state, Some(&head));
24522            let captured = f.repo.join("public-prompt.txt");
24523            let author = &mut f.runner.state.config.agents[0];
24524            author.command = vec![
24525                "sh".into(),
24526                "-c".into(),
24527                "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
24528            ];
24529            author.env.insert(
24530                "PROMPT_FILE".into(),
24531                captured.to_string_lossy().into_owned(),
24532            );
24533            let m = posted(&mut f).await;
24534            assert!(m.body.contains("Adds `own.txt`"));
24535            assert!(m.body.contains("Round 1") && m.body.contains("Round 2"));
24536            assert!(m.body.contains("R1-1-1"));
24537            assert!(
24538                m.body
24539                    .contains("Gate (`verify.gate`): passed on the final commit")
24540            );
24541            assert!(
24542                m.body
24543                    .contains("Tests (`verify.e2e`): passed on the final commit")
24544            );
24545            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
24546            assert!(!m.body.contains("内部") && !m.body.contains("できません"));
24547            let prompt = std::fs::read_to_string(captured).unwrap();
24548            assert!(prompt.contains(&format!(
24549                "git diff {} {head}",
24550                f.runner.state.change_summary.as_ref().unwrap().base
24551            )));
24552            assert!(!prompt.contains("二回目") && !prompt.contains("コミットできません"));
24553            assert_eq!(
24554                f.runner.state.reviews[1].fix.as_ref().unwrap().notes,
24555                "二回目の内部修正報告です。"
24556            );
24557        }
24558    }
24559
24560    #[tokio::test]
24561    async fn public_generation_failure_never_falls_back_to_internal_notes_and_resume_retries() {
24562        for review_only in [false, true] {
24563            let mut f = summary_fixture();
24564            if !review_only {
24565                f.runner.state.candidates[0].agent = "alpha".into();
24566            }
24567            f.runner.state.candidates[0].summary = "内部報告を公開しない".into();
24568            f.runner.state.reviews = vec![round_with_notes(1, Some("日本語の修正報告"))];
24569            std::fs::write(&f.reply, "no usable description").unwrap();
24570            let failed = posted(&mut f).await;
24571            assert!(
24572                failed
24573                    .body
24574                    .contains("No description of what this change does could be generated")
24575            );
24576            assert!(failed.body.is_ascii());
24577            assert!(f.runner.state.github_text.is_none());
24578            assert!(f.runner.state.change_summary.is_none());
24579            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24580            let evidence = crate::pr_outcome::summary_evidence(
24581                &f.runner.state,
24582                crate::pr_outcome::FinalHead::At(&head),
24583            );
24584            let fp = crate::pr_outcome::summary_fingerprint(&f.runner.state, &evidence);
24585            assert!(
24586                crate::run::artifact_path(&f.runner.state, &format!("public-description-{fp}.md"))
24587                    .exists()
24588            );
24589            f.runner.state =
24590                serde_json::from_str(&serde_json::to_string(&f.runner.state).unwrap()).unwrap();
24591            std::fs::write(
24592                &f.reply,
24593                "TITLE: feat(own): add the own file\nAdds the committed own file.",
24594            )
24595            .unwrap();
24596            let retried = posted(&mut f).await;
24597            assert!(retried.body.contains("Adds the committed own file."));
24598            assert_eq!(
24599                f.runner.state.reviews[0].fix.as_ref().unwrap().notes,
24600                "日本語の修正報告"
24601            );
24602        }
24603    }
24604
24605    #[tokio::test]
24606    async fn same_head_verification_and_findings_invalidate_public_prose() {
24607        let mut f = summary_fixture();
24608        posted(&mut f).await;
24609        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24610        let original = f
24611            .runner
24612            .state
24613            .change_summary
24614            .as_ref()
24615            .unwrap()
24616            .evidence
24617            .clone();
24618        ok_gate(&mut f.runner.state, Some(&head));
24619        std::fs::write(
24620            &f.reply,
24621            "TITLE: feat(own): add the own file\nDescribes the now verified final change.",
24622        )
24623        .unwrap();
24624        let verified = posted(&mut f).await;
24625        assert!(verified.body.contains("now verified"));
24626        assert_ne!(
24627            f.runner.state.change_summary.as_ref().unwrap().evidence,
24628            original
24629        );
24630        let mut round = round_with_notes(1, Some("内部報告"));
24631        round.reviews.push(ReviewRecord {
24632            attempts: 0,
24633            reviewer: 1,
24634            agent: "alpha".into(),
24635            summary: "内部レビュー".into(),
24636            findings: vec![finding("R1-1-1", Severity::Minor, "残っている懸念")],
24637            vote: None,
24638            failed: None,
24639            duration_ms: 0,
24640        });
24641        round
24642            .fix
24643            .as_mut()
24644            .unwrap()
24645            .rejected
24646            .push(crate::verdict::Rejection {
24647                id: "R1-1-1".into(),
24648                why: "呼び出し元から到達できない".into(),
24649            });
24650        f.runner.state.reviews = vec![round];
24651        // A description omitting the required ID is unusable, even with a title.
24652        let omitted = posted(&mut f).await;
24653        assert!(omitted.body.contains("No description"));
24654        assert!(omitted.body.contains("R1-1-1"));
24655        assert!(!omitted.body.contains("到達"));
24656        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: declined because the code is unreachable from callers; confirm that assumption when adding callers.").unwrap();
24657        let described = posted(&mut f).await;
24658        assert!(described.body.contains("unreachable from callers"));
24659        assert!(described.body.contains("R1-1-1"));
24660        assert!(!described.body.contains("到達"));
24661        let evidence = f
24662            .runner
24663            .state
24664            .change_summary
24665            .as_ref()
24666            .unwrap()
24667            .evidence
24668            .clone();
24669        f.runner.state.reviews[0].fix.as_mut().unwrap().rejected[0].why = "別の根拠".into();
24670        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: decline rationale updated after review.").unwrap();
24671        assert!(posted(&mut f).await.body.contains("rationale updated"));
24672        assert_ne!(
24673            f.runner.state.change_summary.as_ref().unwrap().evidence,
24674            evidence
24675        );
24676        // Old serialized summaries have no evidence fingerprint and must regenerate.
24677        f.runner
24678            .state
24679            .change_summary
24680            .as_mut()
24681            .unwrap()
24682            .evidence
24683            .clear();
24684        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: regenerated under the current specification.").unwrap();
24685        assert!(posted(&mut f).await.body.contains("current specification"));
24686    }
24687
24688    #[tokio::test]
24689    async fn a_review_only_run_with_no_fixer_gets_a_summary_of_the_final_diff() {
24690        let mut f = summary_fixture();
24691        let m = posted(&mut f).await;
24692        assert_eq!(m.title, "feat(own): add the own file");
24693        assert!(
24694            m.body
24695                .contains("## Summary\n\nAdds `own.txt` so the first summary is read."),
24696            "{}",
24697            m.body
24698        );
24699        assert!(!m.body.contains("## Review fixes"), "{}", m.body);
24700        assert!(m.body.contains("Evidence: final diff"), "{}", m.body);
24701        assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
24702        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24703        let base = git::rev_parse(&f.repo, "origin/main").await.unwrap();
24704        let kept = f.runner.state.change_summary.as_ref().unwrap();
24705        assert_eq!(
24706            (kept.head.as_str(), kept.base.as_str()),
24707            (head.as_str(), base.as_str())
24708        );
24709        assert!(!f.runner.state.seats["change-summary"].key.is_empty());
24710    }
24711
24712    #[tokio::test]
24713    async fn review_only_summary_receives_the_configured_github_language() {
24714        let mut f = summary_fixture();
24715        f.runner.state.config.graph.github_language = "ja".into();
24716        let captured = f.repo.join("summary-prompt.txt");
24717        let author = &mut f.runner.state.config.agents[0];
24718        author.command = vec![
24719            "sh".into(),
24720            "-c".into(),
24721            "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
24722        ];
24723        author.env.insert(
24724            "PROMPT_FILE".into(),
24725            captured.to_string_lossy().into_owned(),
24726        );
24727        std::fs::write(
24728            &f.reply,
24729            "TITLE: feat(own): ファイルを追加\nown.txt を追加します。",
24730        )
24731        .unwrap();
24732        let m = posted(&mut f).await;
24733        let prompt = std::fs::read_to_string(captured).unwrap();
24734        assert!(prompt.contains("Write the TITLE line and the Markdown description in Japanese."));
24735        assert!(!prompt.contains("in English"));
24736        assert_eq!(m.title, "feat(own): ファイルを追加");
24737        assert!(m.body.contains("own.txt を追加します。"));
24738    }
24739
24740    #[tokio::test]
24741    async fn review_fixes_come_after_the_whole_change_summary() {
24742        let mut f = summary_fixture();
24743        f.runner.state.reviews = vec![
24744            round_with_notes(1, Some("handled the PATH case")),
24745            round_with_notes(2, None),
24746        ];
24747        let m = posted(&mut f).await;
24748        let summary = m.body.find("## Summary").expect("summary");
24749        let fixes = m.body.find("## Review rounds").expect("review rounds");
24750        assert!(summary < fixes, "{}", m.body);
24751        assert!(!m.body.contains("handled the PATH case"), "{}", m.body);
24752        assert!(m.body.contains("## Final verification"), "{}", m.body);
24753    }
24754
24755    #[tokio::test]
24756    async fn a_changed_final_diff_invalidates_the_earlier_summary() {
24757        let mut f = summary_fixture();
24758        let first = posted(&mut f).await;
24759        let first_head = f.runner.state.change_summary.clone().unwrap().head;
24760        // The same head reuses the record: a different reply is not read.
24761        std::fs::write(&f.reply, "TITLE: feat(own): other\nNot read yet.").unwrap();
24762        let again = posted(&mut f).await;
24763        assert_eq!((again.title, again.body), (first.title, first.body));
24764
24765        let g = |args: &[&str]| {
24766            let out = std::process::Command::new("git")
24767                .args(args)
24768                .current_dir(&f.repo)
24769                .quiet()
24770                .output()
24771                .expect("spawn git");
24772            assert!(out.status.success(), "git {args:?}");
24773        };
24774        std::fs::write(f.repo.join("more.txt"), "more\n").unwrap();
24775        g(&["add", "-A"]);
24776        g(&["commit", "-q", "-m", "fix(own): handle more"]);
24777        let second = posted(&mut f).await;
24778        let kept = f.runner.state.change_summary.clone().unwrap();
24779        assert_ne!(kept.head, first_head);
24780        assert!(second.body.contains("Not read yet."), "{}", second.body);
24781        assert!(!second.body.contains("so the first summary is read"));
24782        assert_eq!(second.title, "feat(own): other");
24783    }
24784
24785    #[tokio::test]
24786    async fn an_unavailable_summary_is_stated_and_never_invented() {
24787        let mut f = summary_fixture();
24788        std::fs::write(&f.reply, "no title line here").unwrap();
24789        let m = posted(&mut f).await;
24790        assert!(
24791            m.body
24792                .contains("No description of what this change does could be generated"),
24793            "{}",
24794            m.body
24795        );
24796        assert!(m.body.contains("internal reports remain in local records"));
24797        assert!(f.runner.state.change_summary.is_none());
24798        assert!(!m.body.contains("## Commits under review"), "{}", m.body);
24799        // A preview asks nobody and claims nothing.
24800        let winner = f.runner.state.candidates[0].clone();
24801        let preview = f
24802            .runner
24803            .guarded_pr_message(&winner, None, false)
24804            .await
24805            .unwrap()
24806            .unwrap();
24807        assert!(!preview.body.contains("## Summary"), "{}", preview.body);
24808    }
24809
24810    #[test]
24811    fn pr_message_review_single_commit_uses_its_subject() {
24812        let state = review_state(&["feat(nats): per-role user"]);
24813        let m = pr_message(&state, 'A');
24814        assert_eq!(m.title, "feat(nats): per-role user");
24815        assert!(!m.body.contains("Review the work already"), "{}", m.body);
24816        assert!(m.body.contains("## Commits under review"), "{}", m.body);
24817    }
24818
24819    #[test]
24820    fn pr_message_review_multi_commit_takes_the_oldest() {
24821        let state = review_state(&["feat: the change", "fix: typo", "fix: again"]);
24822        let m = pr_message(&state, 'A');
24823        assert_eq!(m.title, "feat: the change");
24824        for s in ["feat: the change", "fix: typo", "fix: again"] {
24825            assert!(m.body.contains(&format!("- {s}\n")), "{}", m.body);
24826        }
24827    }
24828
24829    #[test]
24830    fn pr_message_review_without_a_usable_first_subject_is_neutral() {
24831        for first in ["日本語の件名", "", "magi: candidate A (uncommitted work)"] {
24832            let mut state = review_state(&[first, "fix: later fixup"]);
24833            state.candidates[0].branch = "機能/ログイン".to_owned();
24834            let m = pr_message(&state, 'A');
24835            assert!(
24836                m.title.starts_with("chore: land candidate A of run"),
24837                "{}",
24838                m.title
24839            );
24840        }
24841    }
24842
24843    fn facts(commits: &[(&str, &str)], stat: &str) -> BranchFacts {
24844        BranchFacts {
24845            commits: commits
24846                .iter()
24847                .map(|(s, b)| ((*s).to_owned(), (*b).to_owned()))
24848                .collect(),
24849            stat: stat.to_owned(),
24850        }
24851    }
24852
24853    fn round_with_notes(round: usize, notes: Option<&str>) -> ReviewRound {
24854        let mut r = review_round(true, 0, 1, 1, true, true);
24855        r.round = round;
24856        r.fix = notes.map(|n| FixRecord {
24857            agent: "fixer".to_owned(),
24858            addressed: Vec::new(),
24859            rejected: Vec::new(),
24860            notes: n.to_owned(),
24861            committed: true,
24862            failed: None,
24863            duration_ms: 0,
24864            continuation: None,
24865        });
24866        r
24867    }
24868
24869    #[test]
24870    fn pr_message_review_with_branch_facts_uses_commits_and_stat() {
24871        let state = review_state(&["ignored"]);
24872        let f = facts(
24873            &[
24874                (
24875                    "fix(login): resolve PATH on macOS",
24876                    "Login shells skip rc files.",
24877                ),
24878                ("fix: address review", ""),
24879            ],
24880            " src/a.rs | 2 +-\n 1 file changed, 1 insertion(+), 1 deletion(-)",
24881        );
24882        let m = pr_message_with(&state, 'A', Some(&f));
24883        assert_eq!(m.title, "fix(login): resolve PATH on macOS");
24884        assert!(
24885            m.body
24886                .contains("- fix(login): resolve PATH on macOS\n  Login shells skip rc files.\n"),
24887            "{}",
24888            m.body
24889        );
24890        assert!(m.body.contains("- fix: address review\n"), "{}", m.body);
24891        assert!(m.body.contains("## Diff stat"), "{}", m.body);
24892        assert!(m.body.contains("src/a.rs | 2 +-"), "{}", m.body);
24893        for banned in [
24894            "Review the work already",
24895            "no task statement",
24896            "Original task",
24897        ] {
24898            assert!(!m.body.contains(banned), "{banned}: {}", m.body);
24899        }
24900        assert!(m.body.ends_with("magi:candidate-a\n"), "{}", m.body);
24901    }
24902
24903    #[test]
24904    fn pr_message_review_truncates_a_huge_first_commit_body() {
24905        let state = review_state(&["ignored"]);
24906        let f = facts(
24907            &[("feat: big", &"x".repeat(70_000)), ("fix: later", "")],
24908            "s",
24909        );
24910        let m = pr_message_with(&state, 'A', Some(&f));
24911        assert!(m.body.len() < 30_000, "{}", m.body.len());
24912        assert!(m.body.contains("(truncated)"), "{}", m.body.len());
24913        assert!(
24914            m.body.contains("- ... 1 more commit(s)"),
24915            "{}",
24916            m.body.len()
24917        );
24918        assert!(m.body.ends_with("magi:candidate-a\n"));
24919    }
24920
24921    #[test]
24922    fn pr_message_review_without_facts_falls_back_to_recorded_subjects() {
24923        let m = pr_message_with(&review_state(&["feat: x", "fix: y"]), 'A', None);
24924        assert_eq!(m.title, "feat: x");
24925        assert!(m.body.contains("- fix: y\n"), "{}", m.body);
24926        assert!(!m.body.contains("Diff stat"), "{}", m.body);
24927        assert!(!m.body.contains("no task statement"), "{}", m.body);
24928    }
24929
24930    #[test]
24931    fn pr_message_review_titles_from_the_branch_name_when_subjects_are_unusable() {
24932        let mut state = review_state(&["日本語の件名"]);
24933        state.candidates[0].branch = "fix/macos-login-path".to_owned();
24934        assert_eq!(pr_message(&state, 'A').title, "fix/macos-login-path");
24935        state.candidates[0].branch = "機能/ログイン".to_owned();
24936        assert!(
24937            pr_message(&state, 'A')
24938                .title
24939                .starts_with("chore: land candidate A")
24940        );
24941    }
24942
24943    #[test]
24944    fn pr_message_review_fixes_survive_a_clean_final_round() {
24945        let mut state = review_state(&["feat: x"]);
24946        state.reviews = vec![
24947            round_with_notes(1, Some("handled the PATH case")),
24948            round_with_notes(2, None),
24949        ];
24950        let body = pr_message(&state, 'A').body;
24951        assert!(
24952            body.contains("## Review rounds") && !body.contains("handled the PATH case"),
24953            "{body}"
24954        );
24955        assert!(body.contains("### Round 1"), "{body}");
24956
24957        state.reviews = vec![
24958            round_with_notes(1, Some("first fix")),
24959            round_with_notes(2, Some("")),
24960            round_with_notes(3, Some("second fix")),
24961            round_with_notes(4, None),
24962        ];
24963        let body = pr_message(&state, 'A').body;
24964        assert!(
24965            body.contains("### Round 1") && !body.contains("first fix"),
24966            "{body}"
24967        );
24968        assert!(
24969            body.contains("### Round 3") && !body.contains("second fix"),
24970            "{body}"
24971        );
24972        assert!(body.contains("### Round 2"), "{body}");
24973    }
24974
24975    const FINAL: &str = "abcdef1234567890";
24976
24977    fn passing_round(round: usize, verified: Option<&str>) -> ReviewRound {
24978        let mut r = round_with_notes(round, None);
24979        r.verified_head = verified.map(str::to_owned);
24980        r
24981    }
24982
24983    fn ok_gate(state: &mut RunState, head: Option<&str>) {
24984        state.gate = vec![CommandOutcome {
24985            command: "gate".to_owned(),
24986            code: Some(0),
24987            output_tail: String::new(),
24988            duration_ms: 0,
24989            resource_blocked: false,
24990            ..Default::default()
24991        }];
24992        state.gate_ran = true;
24993        state.gate_head = head.map(str::to_owned);
24994    }
24995
24996    fn body_at(state: &RunState) -> String {
24997        pr_message_raw(
24998            state,
24999            'A',
25000            None,
25001            crate::pr_outcome::FinalHead::At(FINAL),
25002            ChangeNote::NotAsked,
25003        )
25004        .body
25005    }
25006
25007    const SANDBOXED: &str = "Handled the PATH case.\nI could not commit because of the sandbox. HTTP tests could not run in the sandbox.";
25008
25009    #[test]
25010    fn rescued_commit_and_later_verification_override_the_fixers_limits() {
25011        let mut state = review_state(&["feat: x"]);
25012        state.reviews = vec![
25013            round_with_notes(1, Some(SANDBOXED)),
25014            passing_round(2, Some(FINAL)),
25015        ];
25016        ok_gate(&mut state, Some(FINAL));
25017        let body = body_at(&state);
25018        assert!(!body.contains("Handled the PATH case."), "{body}");
25019        assert!(!body.contains("could not commit"), "{body}");
25020        assert!(!body.contains("could not run"), "{body}");
25021        assert!(
25022            body.contains("The fix is committed on the branch"),
25023            "{body}"
25024        );
25025        assert!(!body.contains("sandbox"), "{body}");
25026        assert!(
25027            body.contains("Tests (`verify.e2e`): passed on the final commit"),
25028            "{body}"
25029        );
25030        assert!(
25031            body.contains("Gate (`verify.gate`): passed on the final commit"),
25032            "{body}"
25033        );
25034        // The raw report is untouched in the record.
25035        assert!(
25036            state.reviews[0]
25037                .fix
25038                .as_ref()
25039                .unwrap()
25040                .notes
25041                .contains("could not commit")
25042        );
25043    }
25044
25045    #[test]
25046    fn unresolved_commit_and_test_limits_stay_and_nothing_claims_success() {
25047        let mut state = review_state(&["feat: x"]);
25048        let mut r1 = round_with_notes(1, Some(SANDBOXED));
25049        r1.fix.as_mut().unwrap().committed = false;
25050        let mut r2 = passing_round(2, Some(FINAL));
25051        r2.e2e[0].code = Some(1);
25052        state.reviews = vec![r1, r2];
25053        let body = body_at(&state);
25054        assert!(!body.contains("could not commit"), "{body}");
25055        assert!(!body.contains("could not run"), "{body}");
25056        assert!(body.contains("This round produced no commit"), "{body}");
25057        assert!(body.contains("Tests (`verify.e2e`): FAILED"), "{body}");
25058        assert!(body.contains("Gate (`verify.gate`): not run"), "{body}");
25059        assert!(!body.contains("passed"), "{body}");
25060    }
25061
25062    #[test]
25063    fn verification_on_an_earlier_commit_does_not_supersede_test_limits() {
25064        let mut state = review_state(&["feat: x"]);
25065        state.reviews = vec![
25066            round_with_notes(1, Some(SANDBOXED)),
25067            passing_round(2, Some("0123456789abcdef")),
25068        ];
25069        ok_gate(&mut state, Some("0123456789abcdef"));
25070        let body = body_at(&state);
25071        assert!(!body.contains("HTTP tests could not run"), "{body}");
25072        // The commit claim is still settled by the structured record.
25073        assert!(!body.contains("could not commit"), "{body}");
25074        assert!(
25075            body.contains("passed on an earlier commit (`0123456`)"),
25076            "{body}"
25077        );
25078        assert!(!body.contains("passed on the final commit"), "{body}");
25079
25080        // A gate recorded before `gate_head` existed is "not recorded".
25081        ok_gate(&mut state, None);
25082        let body = body_at(&state);
25083        assert!(
25084            body.contains("passed on a commit that was not recorded"),
25085            "{body}"
25086        );
25087    }
25088
25089    #[test]
25090    fn pr_message_implementation_run_keeps_its_shape_and_marker() {
25091        let state = state_with_summary(
25092            "add retries to the client",
25093            "TITLE: feat: retries\n\nDid it.",
25094        );
25095        let m = pr_message_with(&state, 'A', Some(&facts(&[("x", "")], "s")));
25096        assert_eq!(m.title, "feat: retries");
25097        assert!(
25098            m.body.contains("<summary>Original task</summary>"),
25099            "{}",
25100            m.body
25101        );
25102        assert!(!m.body.contains("Commits under review"), "{}", m.body);
25103        assert!(
25104            m.body
25105                .ends_with(&format!("magi:run/{} magi:candidate-a\n", state.id)),
25106            "{}",
25107            m.body
25108        );
25109    }
25110
25111    #[test]
25112    fn pr_message_review_bounds_a_long_english_subject() {
25113        let long = format!("feat: {}", "word ".repeat(100));
25114        let m = pr_message(&review_state(&[&long]), 'A');
25115        assert!(m.title.starts_with("feat: word"), "{}", m.title);
25116        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
25117    }
25118
25119    #[test]
25120    fn pr_message_implementation_run_is_unchanged_by_review_support() {
25121        let state = state_with_summary("add retries\n\ndetails", "- did some things");
25122        let m = pr_message(&state, 'A');
25123        assert_eq!(m.title, "add retries");
25124        assert!(m.body.contains("<summary>Original task</summary>"));
25125        assert!(!m.body.contains("Commits under review"));
25126        assert_eq!(landing_subject_source(&state), state.instruction);
25127    }
25128
25129    #[test]
25130    fn review_run_squash_subject_is_the_change_not_the_prompt() {
25131        let state = review_state(&["feat: the change", "fix: typo"]);
25132        let source = landing_subject_source(&state);
25133        assert_eq!(land::merge_subject("", &source), "feat: the change");
25134        assert_eq!(
25135            land::merge_subject("magi: candidate A (uncommitted work)", &source),
25136            "feat: the change"
25137        );
25138        // An operator's rename still wins.
25139        assert_eq!(
25140            land::merge_subject("feat: renamed by hand", &source),
25141            "feat: renamed by hand"
25142        );
25143        let blank = review_state(&["日本語"]);
25144        assert!(
25145            land::merge_subject("", &landing_subject_source(&blank)).starts_with("chore: land")
25146        );
25147    }
25148
25149    #[test]
25150    fn review_run_drops_a_prompt_shaped_pr_title_at_landing() {
25151        let state = review_state(&["feat: the change"]);
25152        let source = landing_subject_source(&state);
25153        let old = "Review the work already on branch `magi/x/A`. There is no task statement";
25154        assert_eq!(
25155            land::merge_subject(landing_title(&state, old), &source),
25156            "feat: the change"
25157        );
25158        assert_eq!(landing_title(&state, "feat: renamed"), "feat: renamed");
25159        let task = state_with_summary("add retries", "");
25160        assert_eq!(landing_title(&task, old), old);
25161    }
25162
25163    #[test]
25164    fn pr_message_describes_the_change_not_the_task() {
25165        let state = state_with_summary(
25166            "今回やってほしいこと: results projector を直す",
25167            "TITLE: fix(web): batch the runs list reads\n- reads run.json once\n- risk: none",
25168        );
25169        let m = pr_message(&state, 'A');
25170        assert_eq!(m.title, "fix(web): batch the runs list reads");
25171        assert!(
25172            m.body.starts_with("## Summary\n\n- reads run.json once"),
25173            "{}",
25174            m.body
25175        );
25176        assert!(!m.body.contains("TITLE:"), "{}", m.body);
25177        let task_at = m.body.find("今回やってほしいこと").unwrap();
25178        let details_at = m.body.find("<details>").unwrap();
25179        assert!(
25180            details_at < task_at,
25181            "the task lives inside <details>: {}",
25182            m.body
25183        );
25184        assert!(m.body.contains(&format!("magi:run/{}", state.id)));
25185        assert!(m.body.contains("magi:candidate-a"));
25186    }
25187
25188    #[test]
25189    fn pr_message_falls_back_to_the_task_without_a_title_line() {
25190        let state = state_with_summary("\n\nadd retries\n\ndetails", "- did some things");
25191        let m = pr_message(&state, 'A');
25192        assert_eq!(m.title, "add retries");
25193        assert!(
25194            m.body.contains("## Summary\n\n- did some things"),
25195            "{}",
25196            m.body
25197        );
25198
25199        let none = RunState::new(
25200            PathBuf::from("/repo"),
25201            "main".to_owned(),
25202            "abc1234".to_owned(),
25203            "add retries".to_owned(),
25204            Config::default(),
25205        );
25206        let m = pr_message(&none, 'A');
25207        assert_eq!(m.title, "add retries");
25208        assert!(!m.body.contains("## Summary"), "{}", m.body);
25209    }
25210
25211    #[test]
25212    fn pr_message_refuses_the_candidate_commit_subject() {
25213        for bad in [
25214            "TITLE: magi: candidate A (uncommitted work)",
25215            "TITLE: chore: stuff (uncommitted work)",
25216            "TITLE:   ",
25217        ] {
25218            let state = state_with_summary("add retries", bad);
25219            assert_eq!(pr_message(&state, 'A').title, "add retries", "{bad}");
25220        }
25221    }
25222
25223    #[test]
25224    fn pr_message_bounds_a_very_long_task_and_title() {
25225        let long = format!("fix the thing 🎉 {}", "x".repeat(5000));
25226        let state = state_with_summary(&long, "- nothing");
25227        let m = pr_message(&state, 'A');
25228        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
25229        assert!(!m.title.contains('\n'));
25230
25231        let state = state_with_summary("task", &format!("TITLE: feat: {}", "y".repeat(5000)));
25232        let m = pr_message(&state, 'A');
25233        assert!(m.title.starts_with("feat: "));
25234        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
25235        assert_eq!(m.commit_message().lines().next(), Some(m.title.as_str()));
25236    }
25237
25238    fn long_title_of(instruction: &str) -> String {
25239        pr_message(&state_with_summary(instruction, "- nothing"), 'A').title
25240    }
25241
25242    #[test]
25243    fn pr_message_cuts_a_long_english_line_at_its_first_sentence() {
25244        let first = "Make the landing path keep a readable title for long tasks";
25245        let line = format!(
25246            "{first}. {}",
25247            "And then keep going with more words ".repeat(20)
25248        );
25249        let t = long_title_of(&line);
25250        assert_eq!(t, first);
25251        assert!(!t.starts_with("chore: land"));
25252    }
25253
25254    #[test]
25255    fn pr_message_cuts_a_sentenceless_long_line_at_a_word() {
25256        let line = "word ".repeat(200);
25257        let t = long_title_of(&line);
25258        assert!(t.ends_with("word..."), "{t}");
25259        assert!(t.is_ascii() && t.chars().count() <= PR_TITLE_MAX, "{t}");
25260    }
25261
25262    #[test]
25263    fn pr_message_long_non_english_or_letterless_line_is_neutral() {
25264        for line in ["日本語のタスク ".repeat(80), "1234 ".repeat(100)] {
25265            assert!(long_title_of(&line).starts_with("chore: land"), "{line}");
25266        }
25267    }
25268
25269    #[test]
25270    fn pr_message_keeps_a_japanese_title_when_github_language_is_japanese() {
25271        let mut state = state_with_summary("再試行を追加する", "- nothing");
25272        assert!(pr_message(&state, 'A').title.starts_with("chore: land"));
25273        state.config.graph.github_language = "ja".into();
25274        assert_eq!(pr_message(&state, 'A').title, "再試行を追加する");
25275    }
25276
25277    #[test]
25278    fn pr_message_title_limit_is_exact() {
25279        let at = "a".repeat(PR_TITLE_MAX);
25280        assert_eq!(long_title_of(&at), at);
25281        let over = long_title_of(&"a".repeat(PR_TITLE_MAX + 1));
25282        assert!(over.ends_with("..."), "{over}");
25283        assert_eq!(over.chars().count(), PR_TITLE_MAX);
25284    }
25285
25286    #[test]
25287    fn pr_message_judges_the_kept_text_not_what_follows_the_cut() {
25288        let line = format!("{} \u{2014} tail", "alpha beta ".repeat(40));
25289        let t = long_title_of(&line);
25290        assert!(t.ends_with("..."), "{t}");
25291        assert!(t.is_ascii(), "{t}");
25292    }
25293
25294    #[test]
25295    fn pr_message_sentence_cut_skips_abbreviations_and_decimals() {
25296        let line = format!(
25297            "Support several shells, e.g. bash and zsh, at version 1.5 or newer when it matters {}",
25298            "plus more filler words ".repeat(20)
25299        );
25300        let t = long_title_of(&line);
25301        assert!(t.contains("e.g. bash") && t.contains("1.5 or newer"), "{t}");
25302    }
25303
25304    #[test]
25305    fn pr_message_long_title_survives_a_blank_first_line_and_the_squash_subject() {
25306        let line = format!("\n\n# {}", "title words ".repeat(40));
25307        let state = state_with_summary(&line, "- nothing");
25308        let m = pr_message(&state, 'A');
25309        assert!(m.title.starts_with("title words"), "{}", m.title);
25310        assert_eq!(
25311            land::merge_subject(&m.title, &landing_subject_source(&state)),
25312            m.title
25313        );
25314        // An operator's rename wins untouched.
25315        assert_eq!(
25316            land::merge_subject("feat: renamed by hand", &landing_subject_source(&state)),
25317            "feat: renamed by hand"
25318        );
25319    }
25320
25321    #[tokio::test]
25322    async fn github_text_rewrite_is_bounded_and_falls_back() {
25323        crate::run::pin_test_home();
25324        for (reply, accepted) in [
25325            (
25326                "TITLE: fix: retries\nAdd retries for failed requests.",
25327                true,
25328            ),
25329            (
25330                "TITLE: fix: retries\n日本語の説明をもう一度書きます。",
25331                false,
25332            ),
25333            (
25334                "TITLE: fix: retries\nAdd retries for failed requests. Use token=secret",
25335                true,
25336            ),
25337            (
25338                "TITLE: fix: retries\nAdd retries for failed requests. Example: password=\"prefix\\\"secret tail\"",
25339                true,
25340            ),
25341            (
25342                "TITLE: fix: retries token=secret\nAdd retries for failed requests. Example: password=\"日本語の秘密secret\"",
25343                true,
25344            ),
25345            (
25346                "TITLE: fix: retries\n日本語の説明です。 token=secret",
25347                false,
25348            ),
25349            ("TITLE: fix: retries\n", false),
25350        ] {
25351            let dir = tempfile::tempdir().unwrap();
25352            let mut runner = runner_at(RunStatus::Gating);
25353            runner.state = state_with_summary(
25354                "add retries",
25355                "TITLE: fix: retries\n日本語の説明を書きます。",
25356            );
25357            runner.state.repo = dir.path().to_owned();
25358            runner.state.candidates[0].worktree = dir.path().to_owned();
25359            let mut author = spec("alpha");
25360            author.command = vec![
25361                "sh".into(),
25362                "-c".into(),
25363                "printf '%s' \"$REWRITE_REPLY\"".into(),
25364            ];
25365            author.env.insert("REWRITE_REPLY".into(), reply.into());
25366            runner.state.config.agents = vec![author];
25367            seed_public_summary(&mut runner);
25368            let winner = runner.state.candidates[0].clone();
25369            let first = runner
25370                .guarded_pr_message(&winner, None, true)
25371                .await
25372                .unwrap();
25373            let message = if accepted {
25374                first.expect("a passing rewrite never asks")
25375            } else {
25376                // Withheld: the run parks on a question and posts nothing yet.
25377                assert!(first.is_none());
25378                assert!(runner.state.parked);
25379                let store = ask::Questions::open();
25380                let asked: Vec<_> = store
25381                    .list()
25382                    .into_iter()
25383                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
25384                    .collect();
25385                assert_eq!(asked.len(), 1);
25386                assert!(!asked[0].detail.contains("secret"));
25387                let rewrite = runner.state.github_text.as_ref().unwrap().rewrite.as_ref();
25388                assert_eq!(rewrite.is_some(), !reply.ends_with('\n'));
25389                assert_eq!(
25390                    asked[0]
25391                        .choices
25392                        .contains(&crate::github_text::USE_REWRITE.to_owned()),
25393                    rewrite.is_some()
25394                );
25395                // Silence: the question lapses and the neutral text is used,
25396                // without a second rewrite call or a second question.
25397                store
25398                    .update(&asked[0].id, |q| {
25399                        q.abandon("test");
25400                        Ok(())
25401                    })
25402                    .unwrap();
25403                let again = runner
25404                    .guarded_pr_message(&winner, None, true)
25405                    .await
25406                    .unwrap()
25407                    .expect("an abandoned question falls back");
25408                let n = store
25409                    .list()
25410                    .into_iter()
25411                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
25412                    .count();
25413                assert_eq!(n, 1, "asked once per rejected text");
25414                again
25415            };
25416            assert!(crate::github_text::check(&message.title, &message.body).is_empty());
25417            assert!(!message.body.contains("secret"));
25418            assert!(!message.body.contains("prefix"));
25419            assert!(!message.title.contains("secret"));
25420            assert_eq!(
25421                message.body.contains("Add retries for failed requests."),
25422                accepted
25423            );
25424            assert_eq!(
25425                runner.state.seats["github-text-rewrite"].turns, 1,
25426                "only one rewrite invocation"
25427            );
25428            assert!(runner.state.events.iter().any(|e| e.node == "github-text"));
25429            if accepted {
25430                assert!(runner.state.github_text.is_none());
25431                assert!(!runner.state.parked);
25432                assert!(!message.body.contains(crate::github_text::NEUTRAL_BODY));
25433                assert!(message.body.contains("## Final verification"));
25434                assert!(message.body.contains("Evidence: final diff"));
25435                assert!(
25436                    message
25437                        .body
25438                        .contains(&format!("magi:run/{}", runner.state.id))
25439                );
25440            }
25441            if !accepted {
25442                assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
25443                assert!(
25444                    message
25445                        .body
25446                        .contains(&format!("magi:run/{}", runner.state.id))
25447                );
25448            }
25449        }
25450    }
25451
25452    fn scripted(id: &str, reply: &str) -> AgentSpec {
25453        let mut a = spec(id);
25454        a.command = vec![
25455            "sh".into(),
25456            "-c".into(),
25457            "printf '%s' \"$REWRITE_REPLY\"".into(),
25458        ];
25459        a.env.insert("REWRITE_REPLY".into(), reply.into());
25460        a
25461    }
25462
25463    const JA_SUMMARY: &str = "TITLE: fix: retries\n日本語の説明を書きます。";
25464    const EN_REWRITE: &str = "TITLE: fix: retries\nAdd retries in `src/net.rs` for 3 failed requests.\n\n<details>kept</details>";
25465
25466    /// Gate tests inject generated public output, not internal reports.
25467    fn seed_public_summary(runner: &mut Runner) {
25468        let repo = &runner.state.repo;
25469        let g = |args: &[&str]| {
25470            let out = std::process::Command::new("git")
25471                .args(args)
25472                .current_dir(repo)
25473                .quiet()
25474                .output()
25475                .unwrap();
25476            assert!(out.status.success(), "git {args:?}");
25477            String::from_utf8_lossy(&out.stdout).trim().to_owned()
25478        };
25479        g(&["init", "-q", "-b", "main"]);
25480        g(&[
25481            "-c",
25482            "user.name=Test",
25483            "-c",
25484            "user.email=test@example.invalid",
25485            "commit",
25486            "-q",
25487            "--allow-empty",
25488            "-m",
25489            "feat: fixture",
25490        ]);
25491        let head = g(&["rev-parse", "HEAD"]);
25492        g(&["update-ref", "refs/remotes/origin/main", &head]);
25493        let evidence = crate::pr_outcome::summary_evidence(
25494            &runner.state,
25495            crate::pr_outcome::FinalHead::At(&head),
25496        );
25497        let generated = &runner.state.candidates[0].summary;
25498        runner.state.change_summary = Some(crate::run::ChangeSummary {
25499            base: head.clone(),
25500            head,
25501            evidence: crate::pr_outcome::summary_fingerprint(&runner.state, &evidence),
25502            title: summary_title(generated).unwrap(),
25503            body: summary_without_title(generated),
25504        });
25505    }
25506
25507    fn rewrite_runner(dir: &Path, review_only: bool, agents: Vec<AgentSpec>) -> Runner {
25508        let mut runner = runner_at(RunStatus::Gating);
25509        runner.state = state_with_summary("add retries", JA_SUMMARY);
25510        if review_only {
25511            runner.state.candidates[0].agent = EXISTING_BRANCH.to_owned();
25512        }
25513        runner.state.repo = dir.to_owned();
25514        runner.state.candidates[0].worktree = dir.to_owned();
25515        runner.state.config.agents = agents;
25516        seed_public_summary(&mut runner);
25517        runner
25518    }
25519
25520    fn gate_questions(runner: &Runner) -> usize {
25521        ask::Questions::open()
25522            .list()
25523            .into_iter()
25524            .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
25525            .count()
25526    }
25527
25528    #[tokio::test]
25529    async fn review_only_description_is_rewritten_by_the_language_judge_role() {
25530        crate::run::pin_test_home();
25531        let dir = tempfile::tempdir().unwrap();
25532        let mut runner = rewrite_runner(
25533            dir.path(),
25534            true,
25535            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
25536        );
25537        runner.state.config.roles.language_judge =
25538            Some(crate::config::AgentChoice::Chain(vec!["beta".into()]));
25539        let winner = runner.state.candidates[0].clone();
25540        let msg = runner
25541            .guarded_pr_message(&winner, None, true)
25542            .await
25543            .unwrap()
25544            .expect("an English rewrite posts without asking");
25545        assert!(msg.body.contains("`src/net.rs` for 3 failed requests"));
25546        assert!(msg.body.contains("<details>kept</details>"));
25547        assert!(msg.body.contains(&format!("magi:run/{}", runner.state.id)));
25548        assert_eq!(gate_questions(&runner), 0);
25549        assert!(runner.state.github_text.is_none());
25550        assert!(!runner.state.seats.contains_key("impl-A"));
25551        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
25552    }
25553
25554    #[tokio::test]
25555    async fn rewrite_without_an_implementer_session_uses_the_role_not_the_seat() {
25556        crate::run::pin_test_home();
25557        let dir = tempfile::tempdir().unwrap();
25558        let mut runner = rewrite_runner(
25559            dir.path(),
25560            false,
25561            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
25562        );
25563        runner.state.config.roles.language_judge =
25564            Some(crate::config::AgentChoice::One("beta".into()));
25565        runner.state.seats.insert(
25566            "impl-A".into(),
25567            SeatState::new("impl-A", "alpha", runner.state.seed),
25568        );
25569        let winner = runner.state.candidates[0].clone();
25570        let msg = runner
25571            .guarded_pr_message(&winner, None, true)
25572            .await
25573            .unwrap()
25574            .expect("rewritten");
25575        assert!(msg.body.contains("<details>kept</details>"));
25576        assert_eq!(runner.state.seats["impl-A"].turns, 0);
25577        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
25578        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
25579    }
25580
25581    #[tokio::test]
25582    async fn rewrite_reuses_a_resumable_implementer_session() {
25583        crate::run::pin_test_home();
25584        let dir = tempfile::tempdir().unwrap();
25585        let mut runner = rewrite_runner(
25586            dir.path(),
25587            false,
25588            vec![scripted("alpha", EN_REWRITE), scripted("beta", "nope")],
25589        );
25590        runner.state.config.roles.language_judge =
25591            Some(crate::config::AgentChoice::One("beta".into()));
25592        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
25593        seat.turns = 1;
25594        runner.state.seats.insert("impl-A".into(), seat);
25595        let winner = runner.state.candidates[0].clone();
25596        runner
25597            .guarded_pr_message(&winner, None, true)
25598            .await
25599            .unwrap()
25600            .expect("rewritten");
25601        assert_eq!(runner.state.seats["impl-A"].turns, 2);
25602        assert!(!runner.state.seats.contains_key("github-text-rewrite"));
25603    }
25604
25605    #[tokio::test]
25606    async fn a_failing_resumed_implementer_falls_back_to_the_language_judge_role() {
25607        // Runs 7861 / 344a: the winning implementer (agy) had a resumable
25608        // session, was out of quota, and nothing else was asked.
25609        crate::run::pin_test_home();
25610        let dir = tempfile::tempdir().unwrap();
25611        let mut exhausted = spec("alpha");
25612        exhausted.command = vec!["false".into()];
25613        let mut runner = rewrite_runner(
25614            dir.path(),
25615            false,
25616            vec![exhausted, scripted("beta", EN_REWRITE)],
25617        );
25618        // The implementer's own agent is in the role too: it is not asked twice.
25619        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
25620            "alpha".into(),
25621            "beta".into(),
25622        ]));
25623        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
25624        seat.turns = 1;
25625        runner.state.seats.insert("impl-A".into(), seat);
25626        let winner = runner.state.candidates[0].clone();
25627        let msg = runner
25628            .guarded_pr_message(&winner, None, true)
25629            .await
25630            .unwrap()
25631            .expect("the role rewrites after the implementer fails");
25632        assert!(msg.body.contains("`src/net.rs`"));
25633        assert_eq!(
25634            runner.state.seats["impl-A"].turns, 2,
25635            "the implementer was tried once"
25636        );
25637        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
25638        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
25639    }
25640
25641    #[tokio::test]
25642    async fn rewrite_chain_advances_past_a_failing_or_unparsable_agent() {
25643        crate::run::pin_test_home();
25644        let dir = tempfile::tempdir().unwrap();
25645        let mut broken = spec("bad");
25646        broken.command = vec!["false".into()];
25647        let mut runner = rewrite_runner(
25648            dir.path(),
25649            true,
25650            vec![
25651                broken,
25652                scripted("noformat", "Add retries."),
25653                scripted("good", EN_REWRITE),
25654            ],
25655        );
25656        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
25657            "bad".into(),
25658            "noformat".into(),
25659            "good".into(),
25660        ]));
25661        let winner = runner.state.candidates[0].clone();
25662        let msg = runner
25663            .guarded_pr_message(&winner, None, true)
25664            .await
25665            .unwrap()
25666            .expect("the third agent rewrites");
25667        assert!(msg.body.contains("`src/net.rs`"));
25668        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "good");
25669        assert!(runner.state.handovers.is_empty(), "no handover is recorded");
25670    }
25671
25672    #[tokio::test]
25673    async fn unsuccessful_review_only_rewrites_ask_the_owner_and_never_post_the_original() {
25674        crate::run::pin_test_home();
25675        // (agents, role): still Japanese; no TITLE; nothing resolvable.
25676        for (agents, role, saved) in [
25677            (
25678                vec![scripted("beta", "TITLE: fix: retries\n日本語の説明です。")],
25679                Some("beta"),
25680                true,
25681            ),
25682            (vec![scripted("beta", "Add retries.")], Some("beta"), false),
25683            (Vec::new(), None, false),
25684        ] {
25685            let dir = tempfile::tempdir().unwrap();
25686            let mut runner = rewrite_runner(dir.path(), true, agents);
25687            runner.state.config.roles.language_judge =
25688                role.map(|r| crate::config::AgentChoice::One(r.into()));
25689            let winner = runner.state.candidates[0].clone();
25690            let first = runner
25691                .guarded_pr_message(&winner, None, true)
25692                .await
25693                .unwrap();
25694            assert!(first.is_none(), "withheld text parks the run");
25695            assert!(runner.state.parked);
25696            assert_eq!(gate_questions(&runner), 1);
25697            let g = runner.state.github_text.as_ref().unwrap();
25698            assert_eq!(g.rewrite.is_some(), saved);
25699            assert!(g.choice.is_none() && !g.resolved, "nothing posts unasked");
25700        }
25701    }
25702
25703    #[tokio::test]
25704    async fn github_text_rejected_rewrite_survives_retry_and_posts_verbatim() {
25705        crate::run::pin_test_home();
25706        let dir = tempfile::tempdir().unwrap();
25707        let mut runner = runner_at(RunStatus::Gating);
25708        runner.state =
25709            state_with_summary("add retries", "TITLE: 日本語のタイトル\n日本語の説明です。");
25710        runner.state.repo = dir.path().to_owned();
25711        runner.state.candidates[0].worktree = dir.path().to_owned();
25712        let mut author = spec("alpha");
25713        author.command = vec![
25714            "sh".into(),
25715            "-c".into(),
25716            "printf '%s' \"$REWRITE_REPLY\"".into(),
25717        ];
25718        author.env.insert(
25719            "REWRITE_REPLY".into(),
25720            format!(
25721                "TITLE: fix: rewritten title\n{}\n日本語の説明です。",
25722                "English sentence. ".repeat(600)
25723            ),
25724        );
25725        runner.state.config.agents = vec![author];
25726        seed_public_summary(&mut runner);
25727        let winner = runner.state.candidates[0].clone();
25728        assert!(
25729            runner
25730                .guarded_pr_message(&winner, None, true)
25731                .await
25732                .unwrap()
25733                .is_none()
25734        );
25735        let record = runner.state.github_text.clone().unwrap();
25736        let rewrite = record.rewrite.clone().unwrap();
25737        assert_eq!(rewrite.failed, ["body-language"]);
25738        assert!(
25739            rewrite
25740                .body
25741                .ends_with(&format!("magi:run/{}", runner.state.id))
25742        );
25743        let store = ask::Questions::open();
25744        let q = store.get(record.question.as_ref().unwrap()).unwrap();
25745        assert!(
25746            q.choices
25747                .contains(&crate::github_text::USE_REWRITE.to_owned())
25748        );
25749        for label in [
25750            "ORIGINAL",
25751            "FALLBACK",
25752            "REWRITE",
25753            "Rules still failed: body-language",
25754            "truncated",
25755        ] {
25756            assert!(q.detail.contains(label), "{label}");
25757        }
25758        let artifact = std::fs::read_to_string(crate::run::artifact_path(
25759            &runner.state,
25760            &crate::github_text::artifact_name(&record.fingerprint),
25761        ))
25762        .unwrap();
25763        assert!(artifact.contains(&rewrite.title) && artifact.contains(&rewrite.body));
25764        // Restart from serialized state, then retry after a bad owner title.
25765        runner.state =
25766            serde_json::from_str(&serde_json::to_string(&runner.state).unwrap()).unwrap();
25767        store
25768            .update(&q.id, |q| {
25769                q.say("まだ日本語")?;
25770                q.answer(ask::Answer::Choice(crate::github_text::USE_MY_TEXT.into()))
25771            })
25772            .unwrap();
25773        assert!(
25774            runner
25775                .guarded_pr_message(&winner, None, true)
25776                .await
25777                .unwrap()
25778                .is_none()
25779        );
25780        let retry = runner.state.github_text.as_ref().unwrap();
25781        assert_eq!(retry.rewrite.as_ref(), Some(&rewrite));
25782        let q = store.get(retry.question.as_ref().unwrap()).unwrap();
25783        assert!(q.detail.contains("REWRITE") && q.detail.contains(&rewrite.title));
25784        assert!(
25785            q.posting_comparison
25786                .as_ref()
25787                .unwrap()
25788                .matches_detail(&q.detail)
25789        );
25790        store
25791            .update(&q.id, |q| {
25792                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
25793            })
25794            .unwrap();
25795        let message = runner
25796            .guarded_pr_message(&winner, None, true)
25797            .await
25798            .unwrap()
25799            .unwrap();
25800        assert_eq!(message.title, rewrite.title);
25801        assert_eq!(message.body, rewrite.body);
25802        assert_eq!(
25803            runner.state.github_text.as_ref().unwrap().choice,
25804            Some(GithubTextChoice::Rewrite)
25805        );
25806        let again = runner
25807            .guarded_pr_message(&winner, None, true)
25808            .await
25809            .unwrap()
25810            .unwrap();
25811        assert_eq!(again.title, message.title);
25812        assert_eq!(again.body, message.body);
25813        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
25814        assert!(
25815            !runner
25816                .state
25817                .events
25818                .iter()
25819                .any(|e| e.message.contains(&rewrite.title)
25820                    || e.message.contains("English sentence."))
25821        );
25822    }
25823
25824    #[tokio::test]
25825    async fn historical_posting_reply_never_expires_into_fallback() {
25826        crate::run::pin_test_home();
25827        let dir = tempfile::tempdir().unwrap();
25828        let mut runner = runner_at(RunStatus::Gating);
25829        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
25830        runner.state.repo = dir.path().to_owned();
25831        runner.state.candidates[0].worktree = dir.path().to_owned();
25832        seed_public_summary(&mut runner);
25833        let winner = runner.state.candidates[0].clone();
25834        assert!(
25835            runner
25836                .guarded_pr_message(&winner, None, true)
25837                .await
25838                .unwrap()
25839                .is_none()
25840        );
25841        let id = runner
25842            .state
25843            .github_text
25844            .as_ref()
25845            .unwrap()
25846            .question
25847            .clone()
25848            .unwrap();
25849        let store = ask::Questions::open();
25850        let mut q = store.get(&id).unwrap();
25851        q.asked_at = "2020-01-01T00:00:00Z".parse().unwrap();
25852        q.answer(ask::Answer::Choice(
25853            crate::github_text::POST_ORIGINAL.into(),
25854        ))
25855        .unwrap();
25856        q.answer_delivered = true;
25857        store.put(&mut q).unwrap();
25858        let source = std::fs::read(store.path_of(&id)).unwrap();
25859        let migration = crate::run::home().join("notifications/task-chat-migration-v1");
25860        std::fs::create_dir_all(&migration).unwrap();
25861        std::fs::write(
25862            migration.join("state.json"),
25863            serde_json::to_vec(&serde_json::json!({
25864                "schema": 1, "sources": [id], "pending": [id]
25865            }))
25866            .unwrap(),
25867        )
25868        .unwrap();
25869        for _ in 0..2 {
25870            assert!(
25871                runner
25872                    .guarded_pr_message(&winner, None, true)
25873                    .await
25874                    .unwrap()
25875                    .is_none()
25876            );
25877            assert!(!runner.state.github_text.as_ref().unwrap().resolved);
25878            assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
25879        }
25880        let home = crate::run::home();
25881        crate::task_chat::sweep(
25882            &crate::queue::Queue::at(home.join("queue")),
25883            &crate::talk::Talks::at(home.join("talks")),
25884            &store,
25885            &home,
25886        );
25887        let outbox = crate::task_inquiry::Outbox::at(&home);
25888        outbox
25889            .update_decision(&id, |d| {
25890                d.accept(&format!("decision: {}", crate::github_text::POST_ORIGINAL))?;
25891                d.source_answer_at = q.answered_at;
25892                Ok(true)
25893            })
25894            .unwrap();
25895        outbox
25896            .settle(
25897                &id,
25898                "owner-chat",
25899                "Owner confirms no publication remains necessary",
25900                None,
25901            )
25902            .unwrap();
25903        assert!(
25904            runner
25905                .guarded_pr_message(&winner, None, true)
25906                .await
25907                .unwrap()
25908                .is_none()
25909        );
25910        assert!(!runner.state.github_text.as_ref().unwrap().resolved);
25911        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
25912    }
25913
25914    #[tokio::test]
25915    async fn github_text_rewrite_choice_without_saved_text_falls_back() {
25916        crate::run::pin_test_home();
25917        let dir = tempfile::tempdir().unwrap();
25918        let mut runner = runner_at(RunStatus::Gating);
25919        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
25920        runner.state.repo = dir.path().to_owned();
25921        runner.state.candidates[0].worktree = dir.path().to_owned();
25922        seed_public_summary(&mut runner);
25923        let winner = runner.state.candidates[0].clone();
25924        assert!(
25925            runner
25926                .guarded_pr_message(&winner, None, true)
25927                .await
25928                .unwrap()
25929                .is_none()
25930        );
25931        let record = runner.state.github_text.as_ref().unwrap();
25932        assert!(record.rewrite.is_none());
25933        // Records written before the additive field deserialize with no rewrite.
25934        let mut old = serde_json::to_value(record).unwrap();
25935        old.as_object_mut().unwrap().remove("rewrite");
25936        let old: crate::run::GithubTextAsk = serde_json::from_value(old).unwrap();
25937        assert!(old.rewrite.is_none());
25938        let id = record.question.clone().unwrap();
25939        ask::Questions::open()
25940            .update(&id, |q| {
25941                q.choices.push(crate::github_text::USE_REWRITE.into());
25942                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
25943            })
25944            .unwrap();
25945        let message = runner
25946            .guarded_pr_message(&winner, None, true)
25947            .await
25948            .unwrap()
25949            .unwrap();
25950        assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
25951        assert_eq!(
25952            runner.state.github_text.as_ref().unwrap().choice,
25953            Some(GithubTextChoice::Fallback)
25954        );
25955    }
25956
25957    #[tokio::test]
25958    async fn withheld_title_takes_the_owner_replacement_and_rechecks_it() {
25959        crate::run::pin_test_home();
25960        let dir = tempfile::tempdir().unwrap();
25961        let mut runner = runner_at(RunStatus::Gating);
25962        runner.state = state_with_summary("add retries", "TITLE: 日本語のタイトル\nAdd retries.");
25963        runner.state.repo = dir.path().to_owned();
25964        runner.state.candidates[0].worktree = dir.path().to_owned();
25965        seed_public_summary(&mut runner);
25966        let winner = runner.state.candidates[0].clone();
25967        assert!(
25968            runner
25969                .guarded_pr_message(&winner, None, true)
25970                .await
25971                .unwrap()
25972                .is_none()
25973        );
25974        let store = ask::Questions::open();
25975        let find = |run: &str| {
25976            store
25977                .list()
25978                .into_iter()
25979                .find(|q| q.run == run && q.node == crate::github_text::ASK_NODE && q.status.open())
25980                .unwrap()
25981        };
25982        let run = runner.state.id.clone();
25983        let q = find(&run);
25984        let fp = runner
25985            .state
25986            .github_text
25987            .as_ref()
25988            .unwrap()
25989            .fingerprint
25990            .clone();
25991        let name = crate::github_text::artifact_name(&fp);
25992        let path = crate::run::artifact_path(&runner.state, &name);
25993        assert!(q.detail.contains(&path.display().to_string()));
25994        assert!(q.detail.contains("title-language: title"));
25995        let saved = std::fs::read_to_string(&path).expect("artifact written");
25996        assert!(saved.contains("日本語のタイトル"));
25997        assert!(q.cwd.is_none());
25998        assert_eq!(q.choices, ["use fallback", "post original", "use my text"]);
25999        // A bad replacement is refused and asked about once more.
26000        let say = |id: &str, text: &str, choice: &str| {
26001            store
26002                .update(id, |q| {
26003                    q.thread.push(ask::Turn {
26004                        who: ask::Who::Operator,
26005                        body: text.to_owned(),
26006                        at: jiff::Timestamp::now(),
26007                        note: None,
26008                    });
26009                    q.answer(ask::Answer::Choice(choice.to_owned()))
26010                })
26011                .unwrap();
26012        };
26013        say(&q.id, "まだ日本語", "use my text");
26014        assert!(
26015            runner
26016                .guarded_pr_message(&winner, None, true)
26017                .await
26018                .unwrap()
26019                .is_none()
26020        );
26021        let second = find(&run);
26022        assert_ne!(second.id, q.id);
26023        assert!(second.detail.contains("did not pass"));
26024        // The retry still compares the original text; the rejected
26025        // replacement is named by category only.
26026        assert!(second.detail.contains("日本語のタイトル"));
26027        assert!(!second.detail.contains("まだ日本語"));
26028        assert!(second.detail.contains(&path.display().to_string()));
26029        say(&second.id, "fix: retry failed requests", "use my text");
26030        let message = runner
26031            .guarded_pr_message(&winner, None, true)
26032            .await
26033            .unwrap()
26034            .expect("a vetted replacement is posted");
26035        assert_eq!(message.title, "fix: retry failed requests");
26036        assert_eq!(
26037            runner
26038                .state
26039                .github_text
26040                .as_ref()
26041                .unwrap()
26042                .chosen_title
26043                .as_deref(),
26044            Some("fix: retry failed requests")
26045        );
26046        assert!(runner.state.github_text.as_ref().unwrap().resolved);
26047        // Resumed again: the saved decision is applied, nothing is re-asked.
26048        let again = runner
26049            .guarded_pr_message(&winner, None, true)
26050            .await
26051            .unwrap()
26052            .unwrap();
26053        assert_eq!(again.title, message.title);
26054        assert_eq!(
26055            store
26056                .list()
26057                .into_iter()
26058                .filter(|q| q.run == run && q.node == crate::github_text::ASK_NODE)
26059                .count(),
26060            2
26061        );
26062    }
26063
26064    #[test]
26065    fn pr_message_magi_text_is_english_and_the_task_is_verbatim() {
26066        // What magi itself writes stays English under any configured language,
26067        // so a future localisation of these headings fails here. (The agents'
26068        // own text is also checked by the posting gate.)
26069        let mut state = state_with_summary(
26070            "add retries",
26071            "TITLE: fix(web): batch reads\n- reads run.json once",
26072        );
26073        state.config.graph.language = "ja".to_owned();
26074        let m = pr_message(&state, 'A');
26075        assert!(crate::github_text::check(&m.title, &m.body).is_empty());
26076        assert!(m.title.is_ascii() && m.body.is_ascii(), "{}", m.body);
26077
26078        // The task is the operator's own text: it goes in untouched, and the
26079        // fallback title (no summary) may be in its language too.
26080        let task = "今回やってほしいこと: results projector を直す";
26081        let mut state = state_with_summary(task, "- no title line");
26082        state.config.graph.language = "ja".to_owned();
26083        let m = pr_message(&state, 'A');
26084        assert_eq!(
26085            m.title,
26086            format!("chore: land candidate A of run {}", state.id)
26087        );
26088        assert!(
26089            m.body.contains(&format!(
26090                "<summary>Original task</summary>\n\n{task}\n\n</details>"
26091            )),
26092            "{}",
26093            m.body
26094        );
26095    }
26096
26097    #[test]
26098    fn pr_message_scrubs_home_paths_and_addresses() {
26099        let state = state_with_summary(
26100            "fix it in /Users/someone/src/x",
26101            "TITLE: fix(x): y\n- edited /home/someone/repo/src/a.rs on 10.1.2.3",
26102        );
26103        let m = pr_message(&state, 'A');
26104        for leak in ["/Users/someone", "/home/someone", "10.1.2.3"] {
26105            assert!(!m.body.contains(leak), "{}", m.body);
26106        }
26107        assert!(m.body.contains("~/repo/src/a.rs"), "{}", m.body);
26108    }
26109
26110    #[test]
26111    fn pr_message_survives_a_task_that_closes_details() {
26112        let state = state_with_summary("a </details> b", "TITLE: fix: x");
26113        let m = pr_message(&state, 'A');
26114        assert_eq!(m.body.matches("</details>").count(), 1, "{}", m.body);
26115    }
26116
26117    #[test]
26118    fn manual_squash_subject_cannot_break_out_of_its_quotes() {
26119        let cmd = manual_merge_command(
26120            MergeStyle::Squash,
26121            Path::new("/repo"),
26122            "b",
26123            "fix: \"quoted\" $(x) `y`\n\nbody",
26124        );
26125        assert!(cmd.ends_with("commit -m \"fix: quoted (x) y\""), "{cmd}");
26126    }
26127
26128    #[test]
26129    fn manual_merge_command_matches_the_configured_style() {
26130        let repo = Path::new("/repo");
26131        let message = "Merge magi run 0832 (candidate A)\n\nadd retries";
26132
26133        let merge = manual_merge_command(MergeStyle::Merge, repo, "magi/0832/A", message);
26134        assert_eq!(merge, "git -C /repo merge --no-ff magi/0832/A");
26135
26136        let squash = manual_merge_command(MergeStyle::Squash, repo, "magi/0832/A", message);
26137        assert_eq!(
26138            squash,
26139            "git -C /repo merge --squash magi/0832/A && git -C /repo commit -m \
26140             \"Merge magi run 0832 (candidate A)\""
26141        );
26142
26143        let rebase = manual_merge_command(MergeStyle::Rebase, repo, "magi/0832/A", message);
26144        assert_eq!(rebase, "git -C /repo merge --ff-only magi/0832/A");
26145    }
26146
26147    #[test]
26148    fn a_nudge_gets_a_quarter_of_the_budget() {
26149        // The judge and implement budgets magi ships with.
26150        assert_eq!(retry_budget(secs(1200), true), secs(300));
26151        assert_eq!(retry_budget(secs(3600), true), secs(900));
26152    }
26153
26154    #[test]
26155    fn a_resent_prompt_keeps_the_whole_budget() {
26156        // The seat kept no context, so the retry is the original job again and
26157        // shortening it would only guarantee a second failure.
26158        assert_eq!(retry_budget(secs(1200), false), secs(1200));
26159        assert_eq!(retry_budget(secs(60), false), secs(60));
26160    }
26161
26162    #[test]
26163    fn the_floor_never_exceeds_the_original_budget() {
26164        // A short configured timeout must not be *raised* by the floor: the
26165        // operator asked for a bound, and a retry may not outlast the attempt
26166        // it is retrying.
26167        assert_eq!(retry_budget(secs(60), true), secs(60));
26168        assert_eq!(retry_budget(secs(480), true), secs(120));
26169        assert_eq!(retry_budget(secs(0), true), secs(0));
26170    }
26171
26172    fn evidence(exit_code: Option<i32>) -> agent::CommandEvidence {
26173        agent::CommandEvidence {
26174            id: "item1".to_owned(),
26175            description: "cargo test".to_owned(),
26176            exit_code,
26177            result_summary: String::new(),
26178            source: "codex".to_owned(),
26179        }
26180    }
26181
26182    #[test]
26183    fn a_reply_with_no_commands_at_all_is_not_unconfirmed() {
26184        // No evidence is not the same fact as unconfirmed evidence: a
26185        // backend with no adapter, or a reply that ran no commands at all,
26186        // must not be misread as carrying a dangling job.
26187        assert!(!has_unconfirmed_command(&[]));
26188    }
26189
26190    fn reply(tool_calls: Option<u64>) -> AgentOutput {
26191        AgentOutput {
26192            text: "## SUMMARY\nImplementation incomplete.".to_owned(),
26193            exit_code: Some(0),
26194            timed_out: false,
26195            duration_ms: 7_000,
26196            artifacts: Vec::new(),
26197            quota: None,
26198            dropped: None,
26199            commands: Vec::new(),
26200            context_tokens: None,
26201            tool_calls,
26202        }
26203    }
26204
26205    #[test]
26206    fn a_clean_reply_with_no_tool_call_on_an_untouched_tree_is_unstarted() {
26207        assert!(ended_unstarted(
26208            &reply(Some(0)),
26209            Some("abc"),
26210            Some("abc"),
26211            Some(true)
26212        ));
26213    }
26214
26215    #[test]
26216    fn unknown_or_real_tool_activity_is_never_unstarted() {
26217        // A backend that reports no tool calls says nothing about them.
26218        assert!(!ended_unstarted(
26219            &reply(None),
26220            Some("abc"),
26221            Some("abc"),
26222            Some(true)
26223        ));
26224        // A seat that looked and then wrote nothing did start.
26225        assert!(!ended_unstarted(
26226            &reply(Some(3)),
26227            Some("abc"),
26228            Some("abc"),
26229            Some(true)
26230        ));
26231        let mut ran = reply(Some(0));
26232        ran.commands.push(evidence(Some(0)));
26233        assert!(!ended_unstarted(&ran, Some("abc"), Some("abc"), Some(true)));
26234    }
26235
26236    #[test]
26237    fn work_in_the_tree_or_an_unreadable_one_is_never_unstarted() {
26238        let out = reply(Some(0));
26239        // A commit, uncommitted edits, and each unknown: none may be replayed.
26240        assert!(!ended_unstarted(&out, Some("abc"), Some("def"), Some(true)));
26241        assert!(!ended_unstarted(
26242            &out,
26243            Some("abc"),
26244            Some("abc"),
26245            Some(false)
26246        ));
26247        assert!(!ended_unstarted(&out, None, Some("abc"), Some(true)));
26248        assert!(!ended_unstarted(&out, Some("abc"), None, Some(true)));
26249        assert!(!ended_unstarted(&out, Some("abc"), Some("abc"), None));
26250        assert!(!ended_unstarted(&out, None, None, Some(true)));
26251    }
26252
26253    #[test]
26254    fn a_failed_or_empty_turn_is_not_an_unstarted_reply() {
26255        let mut failed = reply(Some(0));
26256        failed.exit_code = Some(1);
26257        assert!(!ended_unstarted(
26258            &failed,
26259            Some("abc"),
26260            Some("abc"),
26261            Some(true)
26262        ));
26263        let mut silent = reply(Some(0));
26264        silent.text = String::new();
26265        assert!(!ended_unstarted(
26266            &silent,
26267            Some("abc"),
26268            Some("abc"),
26269            Some(true)
26270        ));
26271    }
26272
26273    #[test]
26274    fn a_command_with_a_real_exit_code_is_confirmed_whatever_its_value() {
26275        // Deliberately not a check on the exit code's *value*: a fixer
26276        // legitimately runs something that fails mid-iteration before it
26277        // succeeds, and that must never by itself reopen a valid report.
26278        assert!(!has_unconfirmed_command(&[evidence(Some(0))]));
26279        assert!(!has_unconfirmed_command(&[evidence(Some(1))]));
26280        assert!(!has_unconfirmed_command(&[
26281            evidence(Some(0)),
26282            evidence(Some(101))
26283        ]));
26284    }
26285
26286    #[test]
26287    fn one_command_with_no_readable_exit_code_is_enough_to_flag_the_reply() {
26288        assert!(has_unconfirmed_command(&[
26289            evidence(Some(0)),
26290            evidence(None)
26291        ]));
26292    }
26293
26294    fn evidence_with(
26295        description: &str,
26296        exit_code: Option<i32>,
26297        result_summary: &str,
26298    ) -> agent::CommandEvidence {
26299        agent::CommandEvidence {
26300            id: "item1".to_owned(),
26301            description: description.to_owned(),
26302            exit_code,
26303            result_summary: result_summary.to_owned(),
26304            source: "codex".to_owned(),
26305        }
26306    }
26307
26308    fn valid_noop_summary(commit: &str, test_name: &str) -> String {
26309        format!(
26310            r#"NO CHANGE NEEDED: {{"status":"already_satisfied","requirements":[{{"requirement":"requested fix already landed","satisfied":true,"evidence":["c1","c2"]}}],"checks":[{{"id":"c1","kind":"commit","target":"{commit}","method":"git merge-base --is-ancestor {commit} HEAD","observed":"exit 0; {commit} is on base","passed":true}},{{"id":"c2","kind":"test","target":"{test_name}","method":"cargo test --lib {test_name}","observed":"test result: ok. 1 passed; 0 failed","passed":true}}],"unresolved":[]}}"#
26311        )
26312    }
26313
26314    #[test]
26315    fn a_clean_usable_reply_with_the_marker_is_a_verified_claim() {
26316        let text = valid_noop_summary("b32cfc4", "retry_test");
26317        let claim = verified_noop_claim(true, &[], &text)
26318            .expect("valid structured report with no CommandEvidence must be accepted");
26319        assert!(claim.contains("b32cfc4"), "{claim}");
26320        assert!(claim.contains("retry_test"), "{claim}");
26321    }
26322
26323    #[test]
26324    fn operational_regression_and_legacy_noop_claims_are_rejected() {
26325        let regression = "NO CHANGE NEEDED: Not established. No source changes, commit, or reproduction checks were completed. The reported Git configuration lock contention remains unresolved.";
26326        assert!(verified_noop_claim(true, &[], regression).is_none());
26327        let err = evaluate_noop_claim(true, &[], regression).unwrap_err();
26328        assert!(err.contains("single JSON object"), "{err}");
26329
26330        let legacy = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
26331        assert!(verified_noop_claim(true, &[], legacy).is_none());
26332    }
26333
26334    #[test]
26335    fn an_unusable_reply_never_earns_the_benefit_of_the_doubt() {
26336        // A timeout or a bad exit code reads as the ordinary loss it is,
26337        // whatever the reply's own structured JSON claims.
26338        let text = valid_noop_summary("b32cfc4", "retry_test");
26339        assert!(verified_noop_claim(false, &[], &text).is_none());
26340    }
26341
26342    #[test]
26343    fn an_unconfirmed_command_disqualifies_the_claim_even_on_a_usable_reply() {
26344        let text = valid_noop_summary("b32cfc4", "retry_test");
26345        assert!(verified_noop_claim(true, &[evidence(None)], &text).is_none());
26346        // A matching confirmed command alongside the marker is fine.
26347        assert!(
26348            verified_noop_claim(
26349                true,
26350                &[evidence_with(
26351                    "cargo test --lib retry_test",
26352                    Some(0),
26353                    "1 passed"
26354                )],
26355                &text
26356            )
26357            .is_some()
26358        );
26359    }
26360
26361    #[test]
26362    fn contradictory_or_unrelated_command_evidence_is_rejected_while_mid_investigation_retry_passes()
26363     {
26364        let text = valid_noop_summary("b32cfc4", "retry_test");
26365
26366        // Unrelated passing command cannot substantiate a claimed test run.
26367        let err = evaluate_noop_claim(
26368            true,
26369            &[evidence_with("git status", Some(0), "nothing to commit")],
26370            &text,
26371        )
26372        .unwrap_err();
26373        assert!(err.contains("no matching command was recorded"), "{err}");
26374
26375        // Final matching command exited non-zero -> rejected even if an
26376        // unrelated command succeeded afterward.
26377        let err = evaluate_noop_claim(
26378            true,
26379            &[
26380                evidence_with("cargo test --lib retry_test", Some(0), "ok"),
26381                evidence_with("cargo test --lib retry_test", Some(101), "FAILED"),
26382                evidence_with("rg retry_test src", Some(0), "retry_test"),
26383            ],
26384            &text,
26385        )
26386        .unwrap_err();
26387        assert!(err.contains("exited with"), "{err}");
26388
26389        // A different invocation containing the entire method is not a rerun.
26390        let err = evaluate_noop_claim(
26391            true,
26392            &[evidence_with(
26393                "echo 'cargo test --lib retry_test'",
26394                Some(0),
26395                "retry_test",
26396            )],
26397            &text,
26398        )
26399        .unwrap_err();
26400        assert!(err.contains("no matching command was recorded"), "{err}");
26401
26402        // Mid-investigation failure followed by a passing re-run -> accepted!
26403        assert!(
26404            verified_noop_claim(
26405                true,
26406                &[
26407                    evidence_with("cargo test --lib retry_test", Some(101), "FAILED"),
26408                    evidence_with("cargo test --lib retry_test", Some(0), "1 passed"),
26409                ],
26410                &text
26411            )
26412            .is_some()
26413        );
26414    }
26415
26416    #[test]
26417    fn noop_test_claim_rejects_zero_tests_and_failed_results_despite_successful_exit() {
26418        let text = valid_noop_summary("b32cfc4", "retry_test");
26419        let method = "cargo test --lib retry_test";
26420        let empty = "running 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 42 filtered out";
26421        let ignored = "test result: ok. 0 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out";
26422        let failed =
26423            "test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out";
26424        let passed = "test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out";
26425        for output in [empty, ignored, failed] {
26426            let err = evaluate_noop_claim(true, &[evidence_with(method, Some(0), output)], &text)
26427                .unwrap_err();
26428            assert!(err.contains("failure or no passing tests"), "{err}");
26429        }
26430        // Multiple harnesses can legitimately include a filtered-out suite.
26431        let mixed = format!("{passed}\n{empty}");
26432        assert!(
26433            verified_noop_claim(true, &[evidence_with(method, Some(0), &mixed)], &text).is_some()
26434        );
26435        // A later real rerun of the same command can establish success.
26436        assert!(
26437            verified_noop_claim(
26438                true,
26439                &[
26440                    evidence_with(method, Some(0), empty),
26441                    evidence_with(method, Some(0), passed),
26442                ],
26443                &text,
26444            )
26445            .is_some()
26446        );
26447    }
26448
26449    #[test]
26450    fn path_claim_requires_matching_successful_command_when_commands_are_recorded() {
26451        let text = r#"NO CHANGE NEEDED: {"status":"already_satisfied","requirements":[{"requirement":"README includes the expected header","satisfied":true,"evidence":["p1"]}],"checks":[{"id":"p1","kind":"path","target":"README.md","method":"rg expected README.md","observed":"expected header found","passed":true}],"unresolved":[]}"#;
26452        let failed = evidence_with("rg expected README.md", Some(1), "");
26453        let unrelated = evidence_with("cat README.md", Some(0), "README");
26454        let err =
26455            evaluate_noop_claim(true, &[failed.clone(), unrelated.clone()], text).unwrap_err();
26456        assert!(err.contains("exited with"), "{err}");
26457        assert!(evaluate_noop_claim(true, &[unrelated], text).is_err());
26458        assert!(
26459            evaluate_noop_claim(
26460                true,
26461                &[
26462                    failed,
26463                    evidence_with("rg expected README.md", Some(0), "expected header"),
26464                ],
26465                text,
26466            )
26467            .unwrap()
26468            .is_some()
26469        );
26470    }
26471
26472    #[test]
26473    fn an_ordinary_reply_with_no_marker_is_never_a_claim() {
26474        assert!(verified_noop_claim(true, &[], "- did the thing\n- tested it").is_none());
26475        assert!(matches!(
26476            evaluate_noop_claim(true, &[], "- did the thing\n- tested it"),
26477            Ok(None)
26478        ));
26479    }
26480
26481    #[tokio::test]
26482    async fn repo_cross_verification_validates_commits_and_worktree_paths() {
26483        let tmp = tempfile::tempdir().unwrap();
26484        let repo = tmp.path().join("repo");
26485        std::fs::create_dir_all(&repo).unwrap();
26486        let run_git = |args: &[&str]| {
26487            let out = std::process::Command::new("git")
26488                .args(args)
26489                .current_dir(&repo)
26490                .output()
26491                .unwrap();
26492            assert!(out.status.success(), "git {args:?} failed");
26493            String::from_utf8_lossy(&out.stdout).trim().to_owned()
26494        };
26495        run_git(&["init", "-b", "main"]);
26496        run_git(&["config", "user.name", "test"]);
26497        run_git(&["config", "user.email", "test@example.com"]);
26498        std::fs::write(repo.join("README.md"), "hello\n").unwrap();
26499        run_git(&["add", "-A"]);
26500        run_git(&["commit", "-m", "base commit"]);
26501        let base = run_git(&["rev-parse", "HEAD"]);
26502
26503        // Create a commit on a side branch not on `base`.
26504        run_git(&["checkout", "-b", "side"]);
26505        std::fs::write(repo.join("side.txt"), "side\n").unwrap();
26506        run_git(&["add", "-A"]);
26507        run_git(&["commit", "-m", "side commit"]);
26508        let side = run_git(&["rev-parse", "HEAD"]);
26509        run_git(&["checkout", "main"]);
26510
26511        // Valid commit on base + existing path -> Accepted.
26512        let valid = format!(
26513            r#"NO CHANGE NEEDED: {{"status":"already_satisfied","requirements":[{{"requirement":"readme exists","satisfied":true,"evidence":["c1","c2"]}}],"checks":[{{"id":"c1","kind":"commit","target":"{base}","method":"git merge-base --is-ancestor {base} HEAD","observed":"exit 0; base commit is on main","passed":true}},{{"id":"c2","kind":"path","target":"README.md:1","method":"read README.md","observed":"contains expected greeting","passed":true}}],"unresolved":[]}}"#
26514        );
26515        assert!(matches!(
26516            verified_noop_claim_in_worktree(true, &[], &valid, &repo, &base).await,
26517            NoopClaimVerdict::Accepted
26518        ));
26519
26520        // Non-existent commit SHA -> Rejected.
26521        let missing_sha = valid.replace(&base, "deadbeef");
26522        assert!(matches!(
26523            verified_noop_claim_in_worktree(true, &[], &missing_sha, &repo, &base).await,
26524            NoopClaimVerdict::Rejected(ref r) if r.contains("does not exist in git history")
26525        ));
26526
26527        // Commit on unmerged side branch -> Rejected.
26528        let side_sha = valid.replace(&base, &side);
26529        assert!(matches!(
26530            verified_noop_claim_in_worktree(true, &[], &side_sha, &repo, &base).await,
26531            NoopClaimVerdict::Rejected(ref r) if r.contains("not an ancestor of base commit")
26532        ));
26533
26534        // Missing file path -> Rejected.
26535        let missing_path = valid.replace("README.md:1", "src/does_not_exist.rs");
26536        assert!(matches!(
26537            verified_noop_claim_in_worktree(true, &[], &missing_path, &repo, &base).await,
26538            NoopClaimVerdict::Rejected(ref r) if r.contains("does not exist in the worktree")
26539        ));
26540    }
26541
26542    /// Sets `runner.state.candidates` to one candidate per `(empty, verified)`
26543    /// pair, in order, labelled A, B, C, ...
26544    fn set_candidates(runner: &mut Runner, shape: &[(bool, Option<&str>)]) {
26545        runner.state.candidates = shape
26546            .iter()
26547            .enumerate()
26548            .map(|(i, &(empty, verified))| {
26549                let (summary, verified_noop) = match verified {
26550                    Some(raw) => (raw.to_owned(), Some(raw.to_owned())),
26551                    None => (String::new(), None),
26552                };
26553                Candidate {
26554                    index: i,
26555                    label: (b'A' + i as u8) as char,
26556                    agent: "sonnet".to_owned(),
26557                    branch: format!("magi/x/{}", (b'A' + i as u8) as char),
26558                    worktree: PathBuf::from(format!("/wt/{i}")),
26559                    summary,
26560                    stat: String::new(),
26561                    files: 0,
26562                    commits: 0,
26563                    empty,
26564                    failed: None,
26565                    verified_noop,
26566                    duration_ms: 0,
26567                    folded: false,
26568                }
26569            })
26570            .collect();
26571    }
26572
26573    #[test]
26574    fn after_implement_reads_all_candidates_verified_as_a_noop_not_a_failure() {
26575        ask_test_home();
26576        let mut runner = runner_at(RunStatus::Implementing);
26577        let a = valid_noop_summary("b32cfc4", "test_a");
26578        let b = valid_noop_summary("b32cfc4", "test_b");
26579        set_candidates(
26580            &mut runner,
26581            &[(true, Some(a.as_str())), (true, Some(b.as_str()))],
26582        );
26583
26584        runner
26585            .after_implement()
26586            .expect("a verified no-op is not an error");
26587
26588        assert_eq!(runner.state.status, RunStatus::VerifiedNoop);
26589    }
26590
26591    #[test]
26592    fn after_implement_does_not_accept_one_candidates_claim_next_to_an_ordinary_loss() {
26593        ask_test_home();
26594        let mut runner = runner_at(RunStatus::Implementing);
26595        let a = valid_noop_summary("b32cfc4", "test_a");
26596        // Candidate A declares a verified no-op; candidate B simply wrote
26597        // nothing and said nothing about why. One candidate's claim is not
26598        // the whole run's agreement.
26599        set_candidates(&mut runner, &[(true, Some(a.as_str())), (true, None)]);
26600
26601        let err = runner
26602            .after_implement()
26603            .expect_err("an unverified empty candidate must still fail the run");
26604
26605        assert!(
26606            err.to_string().contains("no candidate produced a change"),
26607            "{err}"
26608        );
26609        assert_eq!(runner.state.status, RunStatus::Failed);
26610    }
26611
26612    #[test]
26613    fn after_implement_invalidates_inconsistent_or_legacy_saved_noop_claims() {
26614        ask_test_home();
26615        let mut runner = runner_at(RunStatus::Implementing);
26616        // Simulate a saved incomplete run that stored a legacy/incomplete
26617        // `verified_noop` string before this build's strict contract.
26618        set_candidates(
26619            &mut runner,
26620            &[(
26621                true,
26622                Some(
26623                    "NO CHANGE NEEDED: Not established. The reported Git configuration lock contention remains unresolved.",
26624                ),
26625            )],
26626        );
26627
26628        let err = runner
26629            .after_implement()
26630            .expect_err("invalid saved noop claim must fail the run");
26631        assert!(
26632            err.to_string().contains("no candidate produced a change"),
26633            "{err}"
26634        );
26635        assert_eq!(runner.state.status, RunStatus::Failed);
26636        assert!(runner.state.candidates[0].verified_noop.is_none());
26637        assert!(runner.state.candidates[0].failed.is_some());
26638        assert!(runner.state.events.iter().any(|e| {
26639            e.message
26640                .contains("invalidated inconsistent saved NO CHANGE NEEDED")
26641        }));
26642    }
26643
26644    #[test]
26645    fn after_implement_rejects_candidate_with_failure_or_commits_on_verified_noop() {
26646        ask_test_home();
26647        let mut runner = runner_at(RunStatus::Implementing);
26648        let a = valid_noop_summary("b32cfc4", "test_a");
26649        set_candidates(&mut runner, &[(true, Some(a.as_str()))]);
26650        runner.state.candidates[0].failed = Some("agent timed out".to_owned());
26651
26652        let err = runner
26653            .after_implement()
26654            .expect_err("a failed candidate must never settle as verified no-op");
26655        assert!(err.to_string().contains("no candidate produced a change"));
26656        assert_eq!(runner.state.status, RunStatus::Failed);
26657        assert!(runner.state.candidates[0].verified_noop.is_none());
26658    }
26659
26660    #[test]
26661    fn after_implement_still_fails_an_ordinary_all_empty_run() {
26662        ask_test_home();
26663        let mut runner = runner_at(RunStatus::Implementing);
26664        set_candidates(&mut runner, &[(true, None), (true, None)]);
26665
26666        let err = runner
26667            .after_implement()
26668            .expect_err("no candidate declared anything; this is an ordinary failure");
26669
26670        assert!(
26671            err.to_string().contains("no candidate produced a change"),
26672            "{err}"
26673        );
26674        assert_eq!(runner.state.status, RunStatus::Failed);
26675    }
26676}
26677
26678/// A graft rollback whose restore could not be confirmed (see
26679/// [`Runner::graft`]).
26680#[derive(Debug)]
26681struct GraftRestoreFailed(String);
26682
26683impl std::fmt::Display for GraftRestoreFailed {
26684    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26685        write!(
26686            f,
26687            "could not restore the winner to its pre-graft commit: {}",
26688            self.0
26689        )
26690    }
26691}
26692
26693impl std::error::Error for GraftRestoreFailed {}
26694
26695/// The pre-spawn waits (shared build cache, parallelism slot) are infrastructure,
26696/// not the agent: they never draw on an agent's own timeout, and running out of
26697/// them never reads as an agent failure.
26698#[cfg(test)]
26699mod resource_wait_tests {
26700    use super::*;
26701    use std::collections::BTreeMap;
26702
26703    fn sh(id: &str, script: &str) -> AgentSpec {
26704        AgentSpec {
26705            id: id.to_owned(),
26706            kind: crate::config::AgentKind::Command,
26707            model: None,
26708            command: vec!["sh".to_owned(), "-c".to_owned(), script.to_owned()],
26709            extra_args: Vec::new(),
26710            env: BTreeMap::new(),
26711            prompt_delivery: None,
26712            max_turn_secs: None,
26713        }
26714    }
26715
26716    fn job(spec: AgentSpec, dir: &Path, timeout: Duration) -> SeatJob {
26717        SeatJob {
26718            seat: SeatState::new("impl-A", &spec.id, 1),
26719            spec,
26720            cwd: dir.to_path_buf(),
26721            prompt: "do it".to_owned(),
26722            timeout,
26723            allow_write: true,
26724            sessions: false,
26725            artifacts: dir.join("art"),
26726            stem: "impl-A".to_owned(),
26727            handover: None,
26728        }
26729    }
26730
26731    fn state(resource_wait_secs: u64) -> RunState {
26732        let mut config = Config::default();
26733        config.graph.timeout_resource_wait = resource_wait_secs;
26734        RunState::new(
26735            PathBuf::from("/repo"),
26736            "main".to_owned(),
26737            "abc1234".to_owned(),
26738            "task".to_owned(),
26739            config,
26740        )
26741    }
26742
26743    fn hold(cache: &Path) -> crate::cache::Guard {
26744        let owner = crate::cache::Owner::here("other-run", "e2e", "e2e", cache, "deadbeef");
26745        match crate::cache::try_acquire(&crate::run::home(), cache, &owner).expect("io") {
26746            crate::cache::AcquireOutcome::Acquired(g) => g,
26747            crate::cache::AcquireOutcome::Busy(b) => panic!("lease was not free: {b:?}"),
26748        }
26749    }
26750
26751    async fn run(
26752        jobs: Vec<SeatJob>,
26753        sem: Arc<Semaphore>,
26754        cache: Option<&Path>,
26755        st: &mut RunState,
26756    ) -> Vec<(usize, SeatState, AgentOutcome)> {
26757        let prompts = Prompts::default();
26758        let ctx = WaveCtx {
26759            run: "r",
26760            node: "implement",
26761            prompts: &prompts,
26762            cache,
26763            round: None,
26764            carry_seats: false,
26765            pauses: None,
26766        };
26767        wave(jobs, sem, &ctx, st, 0).await
26768    }
26769
26770    #[tokio::test]
26771    async fn isolated_editing_seat_wait_releases_only_after_its_own_target_is_free() {
26772        crate::run::pin_test_home();
26773        let home = crate::run::home();
26774        let tmp = tempfile::tempdir().unwrap();
26775        let repo = tmp.path().join("repo");
26776        let checkout = tmp.path().join("checkout");
26777        std::fs::create_dir(&repo).unwrap();
26778        git::git(&repo, &["init"]).await.unwrap();
26779        git::git(
26780            &repo,
26781            &[
26782                "-c",
26783                "user.name=Fixture",
26784                "-c",
26785                "user.email=fixture@example.invalid",
26786                "commit",
26787                "--allow-empty",
26788                "-m",
26789                "initial",
26790            ],
26791        )
26792        .await
26793        .unwrap();
26794        git::worktree_add_detached(&repo, &checkout, "HEAD")
26795            .await
26796            .unwrap();
26797        let target = crate::build_target::resolve(&home, &checkout).unwrap();
26798        let target_lease = hold(&target);
26799        let shared = tmp.path().join("unrelated");
26800        let _shared_lease = hold(&shared);
26801        let mut st = state(0);
26802        st.repo = repo.clone();
26803        st.config.verify.build_cache = crate::config::BuildCache::Isolated;
26804        st.config.verify.e2e = vec![format!(
26805            "CARGO_TARGET_DIR='{}' cargo test",
26806            git::path_arg(&shared)
26807        )];
26808        let config = tmp.path().join("config.toml");
26809        std::fs::write(&config, toml::to_string(&st.config).unwrap()).unwrap();
26810        let prompts = Prompts::default();
26811        let run_id = st.id.clone();
26812        let ctx = WaveCtx {
26813            run: &run_id,
26814            node: "implement",
26815            prompts: &prompts,
26816            cache: None,
26817            round: None,
26818            carry_seats: false,
26819            pauses: None,
26820        };
26821        let writer = job(sh("writer", "exit 99"), &checkout, Duration::from_secs(30));
26822        let results = wave(vec![writer], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0).await;
26823        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
26824        assert_eq!(results[0].1.turns, 0);
26825        let saved = RunState::load_under(&run_id, &home).unwrap();
26826        let block = saved.resource_block.unwrap();
26827        assert!(matches!(
26828            block.cause,
26829            crate::run::ResourceBlockCause::IsolatedCacheTimeout { target: ref actual, .. }
26830                if actual == &target
26831        ));
26832        let queue = crate::queue::Queue::at(tmp.path().join("queue"));
26833        let mut task = crate::queue::Task::new(
26834            "build".into(),
26835            "build".into(),
26836            repo,
26837            crate::queue::Source::Human,
26838        );
26839        task.runs.push(run_id);
26840        task.hold_machine(Some(format!(
26841            "{}{}",
26842            crate::cache::RESOURCE_HOLD,
26843            block.description()
26844        )));
26845        queue.put(&mut task).unwrap();
26846        let questions = crate::ask::Questions::at(tmp.path().join("questions"));
26847        let triage =
26848            || crate::triage::run_once(&queue, &questions, Some(&config), Timestamp::now());
26849        let pending = triage();
26850        assert!(pending.resumed.is_empty() && pending.asked.is_empty());
26851        assert_eq!(
26852            queue.get(&task.id).unwrap().status,
26853            crate::queue::TaskStatus::Held
26854        );
26855        drop(target_lease);
26856        assert_eq!(triage().resumed, vec![task.id.clone()]);
26857        assert_eq!(
26858            queue.get(&task.id).unwrap().status,
26859            crate::queue::TaskStatus::Queued
26860        );
26861        assert!(crate::cache::in_use(&home, &shared));
26862    }
26863
26864    #[tokio::test]
26865    async fn verification_cache_wait_preserves_the_command_budget() {
26866        crate::run::pin_test_home();
26867        let tmp = tempfile::tempdir().unwrap();
26868        let cache = tmp.path().join("target");
26869        let guard = hold(&cache);
26870        let release = tokio::spawn(async move {
26871            tokio::time::sleep(Duration::from_millis(100)).await;
26872            guard.release();
26873        });
26874        let mut st = state(10);
26875        let budget = Duration::from_millis(50);
26876        let wait = repository_wait(&st, None);
26877        let (outcomes, _) = with_cache_lease(
26878            &mut st,
26879            Some(&cache),
26880            "gate",
26881            "gate",
26882            tmp.path(),
26883            "abc1234",
26884            budget,
26885            "test gate",
26886            &wait,
26887            |_, available| async move {
26888                assert_eq!(
26889                    available, budget,
26890                    "contention must not shorten verification"
26891                );
26892                (Vec::new(), false, Vec::new())
26893            },
26894        )
26895        .await
26896        .unwrap();
26897        release.await.unwrap();
26898        assert!(outcomes.is_empty(), "{outcomes:?}");
26899        assert!(
26900            st.events
26901                .iter()
26902                .any(|event| event.message.contains("waiting for"))
26903        );
26904        assert!(st.resource_wait.is_none());
26905        // The verification body no longer owns the lease after returning.
26906        hold(&cache).release();
26907    }
26908
26909    #[tokio::test]
26910    async fn verification_cache_wait_expires_without_starting_commands() {
26911        crate::run::pin_test_home();
26912        let tmp = tempfile::tempdir().unwrap();
26913        let cache = tmp.path().join("target");
26914        let _held = hold(&cache);
26915        let mut st = state(0);
26916        let wait = repository_wait(&st, None);
26917        let (outcomes, _) = with_cache_lease(
26918            &mut st,
26919            Some(&cache),
26920            "gate",
26921            "gate",
26922            tmp.path(),
26923            "abc1234",
26924            Duration::from_secs(60),
26925            "test gate",
26926            &wait,
26927            |_, _| async { panic!("commands must not start without the cache lease") },
26928        )
26929        .await
26930        .unwrap();
26931        assert_eq!(outcomes.len(), 1);
26932        assert!(outcomes[0].resource_blocked);
26933        assert!(st.resource_wait.is_none());
26934        assert!(matches!(
26935            st.resource_block.unwrap().cause,
26936            crate::run::ResourceBlockCause::Timeout { limit_secs: 0, .. }
26937        ));
26938    }
26939
26940    #[tokio::test]
26941    async fn verification_resource_error_does_not_claim_an_elapsed_timeout() {
26942        crate::run::pin_test_home();
26943        let tmp = tempfile::tempdir().unwrap();
26944        std::fs::write(tmp.path().join("Cargo.toml"), "[invalid").unwrap();
26945        let cache = tmp.path().join("cache");
26946        let mut state = state(21600);
26947        let wait = repository_wait(&state, None);
26948        let (outcomes, _) = with_cache_lease(
26949            &mut state,
26950            Some(&cache),
26951            "gate",
26952            "gate",
26953            tmp.path(),
26954            "head",
26955            Duration::from_secs(60),
26956            "gate",
26957            &wait,
26958            |_, _| async { panic!("freshness failure must not start verification") },
26959        )
26960        .await
26961        .unwrap();
26962        assert_eq!(outcomes.len(), 1);
26963        assert!(outcomes[0].resource_blocked);
26964        let block = state.resource_block.unwrap();
26965        assert_eq!(block.cause, crate::run::ResourceBlockCause::Other);
26966        assert!(!block.description().contains("timed out"));
26967    }
26968
26969    #[tokio::test]
26970    async fn cancelled_cache_wait_preserves_the_park_cause_without_starting_an_agent() {
26971        crate::run::pin_test_home();
26972        let tmp = tempfile::tempdir().unwrap();
26973        let cache = tmp.path().join("cache");
26974        let _held = hold(&cache);
26975        let mut state = state(21600);
26976        let pause = Pause::new();
26977        let interrupt = Pause::new();
26978        let cause = ParkCause::Operator;
26979        pause.park_for(cause.clone());
26980        let prompts = Prompts::default();
26981        let ctx = WaveCtx {
26982            run: "test",
26983            node: "fix",
26984            prompts: &prompts,
26985            cache: Some(&cache),
26986            round: None,
26987            carry_seats: false,
26988            pauses: Some((&pause, &interrupt)),
26989        };
26990        let result = wave(
26991            vec![job(
26992                sh("writer", "exit 99"),
26993                tmp.path(),
26994                Duration::from_secs(1),
26995            )],
26996            Arc::new(Semaphore::new(1)),
26997            &ctx,
26998            &mut state,
26999            0,
27000        )
27001        .await;
27002        assert!(matches!(result[0].2, AgentOutcome::ResourceBlocked(_)));
27003        assert_eq!(result[0].1.turns, 0);
27004        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
27005        assert_eq!(
27006            state.resource_block.unwrap().cause,
27007            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
27008        );
27009        assert!(state.active.is_empty());
27010    }
27011
27012    #[tokio::test]
27013    async fn a_cache_wait_longer_than_the_agent_budget_leaves_the_budget_whole() {
27014        crate::run::pin_test_home();
27015        let tmp = tempfile::tempdir().unwrap();
27016        let cache = tmp.path().join("target-a");
27017        let guard = hold(&cache);
27018        // Held for longer than the agent's whole 1s budget.
27019        tokio::spawn(async move {
27020            tokio::time::sleep(Duration::from_millis(1500)).await;
27021            guard.release();
27022        });
27023        let mut st = state(60);
27024        let results = run(
27025            vec![job(
27026                sh("alpha", "echo ok"),
27027                tmp.path(),
27028                Duration::from_secs(1),
27029            )],
27030            Arc::new(Semaphore::new(1)),
27031            Some(&cache),
27032            &mut st,
27033        )
27034        .await;
27035        assert!(
27036            matches!(results[0].2, AgentOutcome::Ok(_)),
27037            "the wait must not be charged to the agent"
27038        );
27039        assert!(st.resource_block.is_none());
27040        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
27041        assert!(st.resource_wait.is_none() && st.active.is_empty());
27042    }
27043
27044    #[tokio::test]
27045    #[cfg(unix)]
27046    async fn repository_wait_in_a_wave_is_a_bounded_cancellable_resource_block() {
27047        use std::os::fd::AsRawFd as _;
27048        crate::run::pin_test_home();
27049        let tmp = tempfile::tempdir().unwrap();
27050        crate::git::git(tmp.path(), &["init"]).await.unwrap();
27051        let common = tmp.path().join(".git");
27052        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
27053        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
27054        assert_eq!(
27055            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
27056            0
27057        );
27058        let mut st = state(1);
27059        st.config.coordination = crate::config::test_coordination();
27060        let mut reader = job(
27061            sh("reader", "echo must-not-run"),
27062            tmp.path(),
27063            Duration::from_secs(30),
27064        );
27065        reader.allow_write = false;
27066        let results = run(
27067            vec![reader.clone()],
27068            Arc::new(Semaphore::new(1)),
27069            None,
27070            &mut st,
27071        )
27072        .await;
27073        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
27074        assert_eq!(results[0].1.turns, 0);
27075        assert!(FailClass::of(&results[0].2).is_none());
27076        assert_eq!(
27077            st.resource_block.as_ref().unwrap().kind,
27078            "repository coordination"
27079        );
27080        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
27081        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
27082        drop(external);
27083        let editor = crate::repo_lock::SeatLease::for_checkout(
27084            tmp.path(),
27085            true,
27086            crate::config::test_coordination().as_ref(),
27087        )
27088        .await
27089        .unwrap();
27090        let pause = Pause::new();
27091        let interrupt = Pause::new();
27092        let prompts = Prompts::default();
27093        let ctx = WaveCtx {
27094            run: "r",
27095            node: "review",
27096            prompts: &prompts,
27097            cache: None,
27098            round: None,
27099            carry_seats: false,
27100            pauses: Some((&pause, &interrupt)),
27101        };
27102        let (results, ()) = tokio::join!(
27103            wave(vec![reader], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0),
27104            async {
27105                tokio::time::sleep(Duration::from_millis(50)).await;
27106                pause.park();
27107            }
27108        );
27109        assert!(
27110            matches!(&results[0].2, AgentOutcome::ResourceBlocked(why) if why.contains("parking"))
27111        );
27112        assert_eq!(results[0].1.turns, 0);
27113        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
27114        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
27115        drop(editor);
27116    }
27117
27118    #[tokio::test]
27119    async fn an_expired_cache_wait_blocks_without_asking_or_rotating_the_agent() {
27120        crate::run::pin_test_home();
27121        let tmp = tempfile::tempdir().unwrap();
27122        let cache = tmp.path().join("target-b");
27123        let _held = hold(&cache);
27124        let mut st = state(1);
27125        let results = run(
27126            vec![job(
27127                sh("alpha", "echo ok"),
27128                tmp.path(),
27129                Duration::from_secs(1),
27130            )],
27131            Arc::new(Semaphore::new(1)),
27132            Some(&cache),
27133            &mut st,
27134        )
27135        .await;
27136        let (_, seat, out) = &results[0];
27137        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
27138        assert!(wave_blocked(&results));
27139        assert_eq!(seat.agent, "alpha", "the chosen agent is kept");
27140        assert_eq!(seat.turns, 0, "nothing was asked");
27141        assert!(
27142            !tmp.path().join("art").join("impl-A.prompt.md").exists(),
27143            "no agent was spawned"
27144        );
27145        assert!(FailClass::of(out).is_none(), "not a failure class");
27146        let block = st.resource_block.as_ref().expect("recorded for the resume");
27147        assert_eq!(block.kind, "shared build cache");
27148        assert!(matches!(
27149            block.cause,
27150            crate::run::ResourceBlockCause::Timeout { limit_secs: 1, .. }
27151        ));
27152        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
27153        assert!(st.active.is_empty());
27154    }
27155
27156    #[tokio::test]
27157    async fn a_semaphore_with_no_permits_ends_as_a_bounded_resource_block() {
27158        crate::run::pin_test_home();
27159        let tmp = tempfile::tempdir().unwrap();
27160        let mut st = state(1);
27161        let results = run(
27162            vec![job(
27163                sh("alpha", "echo ok"),
27164                tmp.path(),
27165                Duration::from_secs(1),
27166            )],
27167            Arc::new(Semaphore::new(0)),
27168            None,
27169            &mut st,
27170        )
27171        .await;
27172        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
27173        assert_eq!(st.resource_block.as_ref().unwrap().kind, "parallel slot");
27174        assert!(!tmp.path().join("art").join("impl-A.prompt.md").exists());
27175    }
27176
27177    #[tokio::test]
27178    async fn an_agent_that_really_hangs_still_times_out_and_hands_over() {
27179        crate::run::pin_test_home();
27180        let tmp = tempfile::tempdir().unwrap();
27181        let mut st = state(60);
27182        let results = run(
27183            vec![job(
27184                sh("alpha", "sleep 30"),
27185                tmp.path(),
27186                Duration::from_secs(1),
27187            )],
27188            Arc::new(Semaphore::new(1)),
27189            None,
27190            &mut st,
27191        )
27192        .await;
27193        let out = &results[0].2;
27194        assert!(matches!(out, AgentOutcome::Failed(e) if e == TIMED_OUT));
27195        let class = FailClass::of(out).expect("a failure");
27196        assert_eq!(class, FailClass::Timeout);
27197        assert!(should_hand_over(None, &class), "existing handover policy");
27198        assert!(st.resource_block.is_none());
27199    }
27200}
27201
27202/// A fold acts on the record it locked, and on nothing else.
27203#[cfg(test)]
27204mod fold_record_tests {
27205    use super::*;
27206
27207    fn refusal(error: &anyhow::Error) -> Option<&FoldRefusal> {
27208        error.downcast_ref::<FoldRefusal>()
27209    }
27210
27211    /// A deletion that lands after the fold's look at the record and before its
27212    /// locks must neither be undone (the fold's lock files bring the directory
27213    /// back, its stale copy the record) nor be acted on.
27214    #[tokio::test]
27215    async fn a_run_deleted_between_the_look_and_the_locks_is_refused_and_not_recreated() {
27216        let dir = tempfile::tempdir().unwrap();
27217        let home = dir.path();
27218        let repo = home.join("repo");
27219        std::fs::create_dir_all(&repo).unwrap();
27220        crate::clean::tests::init_repo(&repo);
27221        let (id, worktree) = crate::clean::tests::due_run_with_winner_worktree(
27222            &home.join("runs"),
27223            &home.join("wt"),
27224            &repo,
27225            "20260801-000000-y001",
27226            RunStatus::Superseded,
27227        )
27228        .await;
27229        let mut state = RunState::load_under(&id, home).unwrap();
27230        BEFORE_LOCKS.with(|hook| {
27231            *hook.borrow_mut() = Some(Box::new(|home: &Path, id: &str| {
27232                std::fs::remove_dir_all(home.join("runs").join(id)).unwrap();
27233            }));
27234        });
27235
27236        let error = fold_run(&mut state, true, home).await.unwrap_err();
27237        assert_eq!(refusal(&error), Some(&FoldRefusal::RecordGone), "{error:#}");
27238        assert!(
27239            !home.join("runs").join(&id).exists(),
27240            "the fold's own lock files must not bring a deleted run back"
27241        );
27242        assert!(worktree.exists(), "nothing of a deleted run is removed");
27243    }
27244
27245    /// The caller's `state` is only a first look: a record that was never
27246    /// saved is not a record the fold may write.
27247    #[tokio::test]
27248    async fn a_record_that_was_never_saved_is_not_folded_or_written() {
27249        let dir = tempfile::tempdir().unwrap();
27250        let home = dir.path();
27251        let mut state = RunState::new(
27252            home.join("repo"),
27253            "main".to_owned(),
27254            "abc".to_owned(),
27255            "fixture".to_owned(),
27256            crate::config::Config::default(),
27257        );
27258        state.status = RunStatus::Superseded;
27259        let error = fold_run(&mut state, true, home).await.unwrap_err();
27260        assert_eq!(refusal(&error), Some(&FoldRefusal::RecordGone), "{error:#}");
27261        assert!(
27262            !home.join("runs").exists(),
27263            "nothing was created: {error:#}"
27264        );
27265    }
27266
27267    /// A refusal changes nothing. A directory whose record is another run's is
27268    /// not the run that was locked: every entry point answers `record gone`,
27269    /// the other run's worktree is left alone, the record stays as it was, and
27270    /// the lock files are not unlinked (an unlinked lock file lets the next
27271    /// caller lock a different inode - `pr_head::owner_lock`).
27272    #[tokio::test]
27273    async fn a_record_naming_another_run_is_refused_by_every_entry_point_and_nothing_is_touched() {
27274        let dir = tempfile::tempdir().unwrap();
27275        let home = dir.path();
27276        let repo = home.join("repo");
27277        std::fs::create_dir_all(&repo).unwrap();
27278        crate::clean::tests::init_repo(&repo);
27279        let runs = home.join("runs");
27280        let (id, own) = crate::clean::tests::due_run_with_winner_worktree(
27281            &runs,
27282            &home.join("wt"),
27283            &repo,
27284            "20260801-000000-y101",
27285            RunStatus::Superseded,
27286        )
27287        .await;
27288        let (other, theirs) = crate::clean::tests::due_run_with_winner_worktree(
27289            &runs,
27290            &home.join("wt"),
27291            &repo,
27292            "20260801-000000-y102",
27293            RunStatus::Superseded,
27294        )
27295        .await;
27296        let first_look = RunState::load_under(&id, home).unwrap();
27297        let record = runs.join(&id).join("run.json");
27298        std::fs::copy(runs.join(&other).join("run.json"), &record).unwrap();
27299        let before = std::fs::read(&record).unwrap();
27300        for entry in ["fold_run", "fold_run_when", "override"] {
27301            let mut state = first_look.clone();
27302            let result = match entry {
27303                "fold_run" => fold_run(&mut state, true, home).await,
27304                "fold_run_when" => fold_run_when(&mut state, home, &|_| Ok(true)).await,
27305                _ => fold_run_overriding_recovery_retention(&mut state, true, home).await,
27306            };
27307            let error = result.unwrap_err();
27308            assert_eq!(
27309                refusal(&error),
27310                Some(&FoldRefusal::RecordGone),
27311                "{entry}: {error:#}"
27312            );
27313            assert!(own.exists() && theirs.exists(), "{entry}");
27314            assert_eq!(std::fs::read(&record).unwrap(), before, "{entry}");
27315            for lock in ["pr-owner.lock", "driver.lock"] {
27316                assert!(
27317                    runs.join(&id).join(lock).exists(),
27318                    "{entry}: {lock} stays in place"
27319                );
27320            }
27321            assert!(
27322                !RunState::load_under(&other, home).unwrap().candidates[0].folded,
27323                "{entry}: the other run was not folded"
27324            );
27325        }
27326    }
27327
27328    /// The refusal is added to the error underneath, never substituted for it:
27329    /// callers match `ResourceBlocked` for a coordination wait.
27330    #[test]
27331    fn a_live_refusal_keeps_the_error_callers_match() {
27332        let blocked = anyhow::Error::new(crate::repo_lock::ResourceBlocked(
27333            "repository coordination".into(),
27334        ));
27335        let error = live_or(blocked);
27336        assert!(error.is::<crate::repo_lock::ResourceBlocked>(), "{error:#}");
27337        assert!(matches!(refusal(&error), Some(FoldRefusal::Live(_))));
27338        // Anything that is not a held lock is passed through untouched.
27339        let other = live_or(anyhow::anyhow!("git exploded"));
27340        assert!(refusal(&other).is_none());
27341    }
27342
27343    /// Contention is `live`, a lock call that failed for another reason is a
27344    /// failure of its own (`failed`), missing evidence is an incomplete proof.
27345    #[test]
27346    fn source_verification_failures_are_told_apart() {
27347        let contended = anyhow::Error::new(std::io::Error::from(std::io::ErrorKind::WouldBlock))
27348            .context("Cargo build is active");
27349        let error = source_proof_failure(contended);
27350        assert!(
27351            matches!(refusal(&error), Some(FoldRefusal::Live(_))),
27352            "{error:#}"
27353        );
27354
27355        let failed = anyhow::Error::new(crate::retention::LockCallFailed::new(
27356            "Cargo lock target/debug/.cargo-lock".into(),
27357            std::io::Error::from(std::io::ErrorKind::Interrupted),
27358        ));
27359        let error = source_proof_failure(failed);
27360        assert!(refusal(&error).is_none(), "{error:#}");
27361        assert!(
27362            error
27363                .chain()
27364                .any(|cause| cause.is::<crate::retention::LockCallFailed>())
27365        );
27366
27367        let error = source_proof_failure(anyhow::anyhow!("Cargo residue changed"));
27368        assert!(matches!(
27369            refusal(&error),
27370            Some(FoldRefusal::ProofIncomplete(_))
27371        ));
27372    }
27373
27374    /// A run directory that is not there is `record gone` at the lock, not
27375    /// something to create for the lock's sake.
27376    #[test]
27377    fn a_missing_run_directory_at_the_lock_is_record_gone() {
27378        let dir = tempfile::tempdir().unwrap();
27379        let error = crate::pr_head::owner_lock(dir.path(), "20260801-000000-y103")
27380            .map(drop)
27381            .map_err(lock_refusal)
27382            .unwrap_err();
27383        assert_eq!(refusal(&error), Some(&FoldRefusal::RecordGone), "{error:#}");
27384        assert!(!dir.path().join("runs").exists());
27385    }
27386}