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};
61use crate::worktree_setup;
62
63/// Bytes of a failing command's output kept in an event, so the reason a run
64/// stopped is readable from the report without opening `run.json`.
65const EVENT_OUTPUT_TAIL: usize = 2_000;
66
67/// How often [`wait_for_timed_out_children_to_die`] re-checks a timed-out
68/// command's pid before releasing the build cache's lease.
69const LEASE_RELEASE_POLL: Duration = Duration::from_secs(1);
70
71/// The most [`wait_for_timed_out_children_to_die`] will wait for a timed-out
72/// command's pid to actually exit before giving up and releasing anyway.
73///
74/// A timeout means the process was asked to die (`kill_on_drop`,
75/// `start_kill`), not that it already has — on Windows in particular that can
76/// take a moment, the same reason `agent`'s own `PIPE_GRACE` exists. Releasing
77/// the instant the command returns would let the very next acquirer (this
78/// run's own next round, another run's verification, the janitor's prune)
79/// start touching the same directory while it might still be writing to it,
80/// so this polls the actual pid — real confirmation, not a fixed guess —
81/// until it is gone or this ceiling is reached. It is still not full
82/// process-tree reaping: a grandchild the timed-out process spawned and that
83/// outlives it independently is invisible to a pid check, and continuing to
84/// observe and collect *that* stays a different piece of work with its own
85/// owner. Set generously because the common case returns early the moment
86/// the pid is confirmed gone, not because every timeout pays this in full.
87const LEASE_RELEASE_MAX_WAIT: Duration = Duration::from_secs(30);
88
89/// Consecutive review rounds with no tree progress (see
90/// [`crate::run::ReviewRound::progressed`]) before `review_loop` hands off
91/// instead of spending the rest of the round budget.
92///
93/// Not 1: a single non-progressing round is not yet a pattern — a fixer that
94/// legitimately finds nothing left to change (its previous round's fix already
95/// covered it, and this round's reviewers re-raised only nits) looks the same
96/// as one that is spinning, for exactly one round. Two in a row is where the
97/// two stop being distinguishable, and a review round on this workload has
98/// been measured at 30-45 minutes of reviewer-plus-fixer agent time, so a
99/// third attempt at a tree that has not moved twice running is pure cost.
100/// This does not touch `review_rounds` itself, which stays the operator's
101/// call.
102pub(crate) const STAGNANT_LIMIT: usize = 2;
103
104/// How many times [`Runner::sync_to_base`] will re-land the winner's tree on
105/// a base that moved before giving up and leaving the run `Blocked` for a
106/// person.
107///
108/// Mirrors `land::Step::Rebase`'s budget and the reasoning behind it: a base
109/// that keeps moving faster than a run can catch it is not something more
110/// rebasing fixes, it is a person's call. Not the same *number as*
111/// `land_rounds` - this budget is spent before a pull request exists, land's
112/// after - but bounded for the identical reason, so it uses the same
113/// default. Counted across both call sites in [`Runner::finish_after_tally`]
114/// (once before review, once before the gate), because either one finding
115/// the base still moving is the same signal.
116pub(crate) const BASE_SYNC_ROUNDS: usize = 4;
117
118/// How many times [`Runner::continue_fix_report`] will resume the fixer's own
119/// seat when its CLI turn ended cleanly — usable, non-empty, exit 0 — but the
120/// reply held no [`FixReport`].
121///
122/// The shape this recovers: run 20260912-114326-d3b8's fix-2 came back
123/// `subtype=success`/`is_error=false`/`stop_reason=end_turn` with the reply
124/// "I'll pause here until the `cargo make check` background run reports
125/// back." — a CLI turn that ended cleanly while the fixer's own job had not.
126/// No `FixReport` was ever collected from that seat, and the run moved on to
127/// the next review round regardless.
128///
129/// Bounded independently of `review_rounds` and `graph.retries`: this
130/// recovers one seat's missing report mid-round, not a new round of review or
131/// an ordinary parse retry, and must not itself become the unbounded wait the
132/// rest of this module exists to avoid.
133const MAX_FIX_CONTINUATIONS: usize = 2;
134
135/// One queued agent invocation.
136///
137/// `Clone` so a node can keep the jobs it sent and re-send one: a seat whose
138/// CLI hung up on its own stream is asked again from the same job rather than
139/// rebuilt from scratch. See [`Runner::resume_undelivered`].
140#[derive(Clone)]
141struct SeatJob {
142    spec: AgentSpec,
143    seat: SeatState,
144    cwd: PathBuf,
145    prompt: String,
146    timeout: Duration,
147    allow_write: bool,
148    sessions: bool,
149    artifacts: PathBuf,
150    stem: String,
151    /// The prompt for a seat that has been handed to another roster agent
152    /// (a fresh session): everything the original seat would have
153    /// remembered. `None` when `prompt` already carries it, as the first
154    /// ranking and the implement prompt do. Never a resume-style prompt.
155    handover: Option<String>,
156}
157
158/// How the graph reads one agent invocation.
159///
160/// Quota is split out from an ordinary failure on purpose: a rate-limited call
161/// is known to fail again if retried now, so the retry loop must not spend an
162/// attempt on it. `Dropped` is split out for the opposite reason: unlike
163/// `Failed`, it is worth re-asking, and unlike `Ok`, its text is the CLI's raw
164/// error JSON, never the agent's answer — a caller that matched only
165/// `Ok`/`Quota`/`Failed` before `Dropped` existed must be updated rather than
166/// left to read that JSON as if it were usable output. `resume_undelivered`
167/// is the only caller that acts on it; everywhere else it is reported like an
168/// ordinary failure.
169enum AgentOutcome {
170    /// A usable output.
171    Ok(AgentOutput),
172    /// The CLI ran out of quota / rate limit. Retrying now is pointless.
173    Quota(AgentOutput),
174    /// The CLI hung up on its own stream after billed work. See
175    /// [`agent::AgentOutput::work_undelivered`].
176    Dropped(AgentOutput),
177    /// Any other failure: a timeout, a bad exit code, an empty reply.
178    Failed(String),
179    /// A resource prevented admission or interrupted execution. Not an agent
180    /// failure: never advance a fallback chain or spend an attempt on it.
181    /// Post-spawn interruptions carry a typed error into wave, which records
182    /// implementation preservation before returning this outcome. This outcome
183    /// alone is not proof that no source changes were made.
184    /// [`RunState::resource_block`] says why.
185    ResourceBlocked(String),
186}
187
188/// A request to park the run at its next node boundary.
189///
190/// Cloning is how the request travels: the loop keeps one handle and hands a
191/// clone to each [`Runner`], and every clone points at the same flag. There
192/// is no channel because there is nothing to send - the only message is
193/// "park", it is idempotent, and a flag cannot be missed by a receiver that
194/// was not listening yet.
195///
196/// The boundary is what makes this cheap. Every node writes the run's state
197/// before the next one starts, and every node skips what is already recorded:
198/// `prep` returns early once candidates exist, `implement` asks only the seats
199/// with nothing on disk, `judge` returns early once judgements exist. So a
200/// parked run resumes into exactly the node it stopped before, and no agent
201/// work is thrown away. Killing the process mid-node, by contrast, loses
202/// whatever the seats in flight had not yet written - which for an implement
203/// wave is an hour of paid work.
204///
205/// A [`Runner`] watches two independent handles of this type - see
206/// [`Runner::on_pause`] and [`Runner::watch_interrupt`] - never one shared
207/// between them. `magi serve`'s own shutdown (`Stop::park`) hands out one
208/// clone covering the whole daemon's lifetime and is never asked to un-park,
209/// which is correct exactly because nothing is dispatched after it fires.
210/// `magi serve`'s interrupt scheduler needs the opposite lifetime - a run
211/// that parks for an interrupted task must go on to run other tasks
212/// afterward - so it mints a fresh, unshared [`Pause`] per run instead of
213/// reusing the daemon-wide one.
214#[derive(Debug, Clone, Default)]
215pub struct Pause(Arc<AtomicBool>, Arc<Mutex<Option<ParkCause>>>);
216
217impl Pause {
218    /// A pause nobody has asked for yet.
219    #[must_use]
220    pub fn new() -> Self {
221        Self::default()
222    }
223
224    /// Ask the run to park at its next node boundary. Idempotent.
225    pub fn park(&self) {
226        self.0.store(true, Ordering::SeqCst);
227    }
228
229    /// Same as [`Pause::park`], but records why, for [`Runner::park_here`] to
230    /// fold into the run's own `park` event - so an operator reading the run
231    /// later knows this was a deliberate interrupt rather than a shutdown or
232    /// a binary swap. The first reason recorded wins; a park already in
233    /// flight is not relabelled by a second, unrelated request.
234    pub fn park_because(&self, reason: impl Into<String>) {
235        self.park_for(ParkCause::Interrupt {
236            reason: reason.into(),
237        });
238    }
239
240    /// [`Pause::park`], recording the structured cause. The first cause
241    /// recorded wins, like [`Pause::park_because`].
242    pub fn park_for(&self, cause: ParkCause) {
243        let mut reason_guard = self
244            .1
245            .lock()
246            .unwrap_or_else(std::sync::PoisonError::into_inner);
247        if reason_guard.is_none() {
248            *reason_guard = Some(cause);
249        }
250        drop(reason_guard);
251        self.park();
252    }
253
254    /// Has a park been asked for?
255    #[must_use]
256    pub fn parked(&self) -> bool {
257        self.0.load(Ordering::SeqCst)
258    }
259
260    /// Why the park was asked for, when the caller used [`Pause::park_because`].
261    #[must_use]
262    pub fn reason(&self) -> Option<String> {
263        self.cause().map(|c| c.label())
264    }
265
266    /// The structured cause, when one was recorded.
267    #[must_use]
268    pub fn cause(&self) -> Option<ParkCause> {
269        self.1
270            .lock()
271            .unwrap_or_else(std::sync::PoisonError::into_inner)
272            .clone()
273    }
274}
275
276/// Drives one run.
277pub struct Runner {
278    /// Run state; public so the CLI can report on it.
279    pub state: RunState,
280    roles: ResolvedRoles,
281    sem: Arc<Semaphore>,
282    /// Set when the daemon's own shutdown (Ctrl-C, a binary swap) wants the
283    /// run parked at its next node boundary. See [`Pause`]'s own doc for why
284    /// this is never the same handle as `interrupt`.
285    pause: Pause,
286    /// Set when `magi serve`'s interrupt scheduler wants this specific run
287    /// parked at its next node boundary, to let a task marked
288    /// [`crate::queue::Task::interrupt`] run alone before this one carries
289    /// on. Unlike `pause`, a fresh, unshared handle per run - see
290    /// [`Runner::watch_interrupt`].
291    interrupt: Pause,
292}
293
294/// Where the branch's own commits start: its merge base with the base branch
295/// as the remote has it now, else with the recorded `base_commit`. A branch
296/// rebased onto a base that moved past `base_commit` would otherwise count
297/// the base's commits as its own under `base_commit..branch`.
298async fn review_base(
299    repo: &Path,
300    remote: &str,
301    base_branch: &str,
302    base_commit: &str,
303    branch: &str,
304) -> String {
305    review_base_checked(repo, remote, base_branch, base_commit, branch)
306        .await
307        .0
308}
309
310/// [`review_base`] plus whether the base was read from a freshly fetched
311/// tracking ref. A failed fetch still uses whatever tracking ref exists (it is
312/// never older than `base_commit`'s view of the base), but the answer is then
313/// not trusted to rewrite a pull request's title.
314async fn review_base_checked(
315    repo: &Path,
316    remote: &str,
317    base_branch: &str,
318    base_commit: &str,
319    branch: &str,
320) -> (String, bool) {
321    let tracking = format!("{remote}/{base_branch}");
322    let fresh = matches!(git::fetch(repo, remote, base_branch).await, Ok(o) if o.ok());
323    if git::rev_exists(repo, &tracking).await
324        && let Ok(mb) = git::merge_base(repo, &tracking, branch).await
325        && !mb.is_empty()
326    {
327        return (mb, fresh);
328    }
329    let mb = git::merge_base(repo, base_commit, branch)
330        .await
331        .ok()
332        .filter(|mb| !mb.is_empty())
333        .unwrap_or_else(|| base_commit.to_owned());
334    (mb, false)
335}
336
337/// Recompute `reviewed_commits` from the branch's own commits. Left as it was
338/// when git cannot say or finds nothing: a stale list is better than a wrong
339/// or empty one.
340pub(crate) async fn refresh_reviewed_commits(state: &mut RunState, branch: &str) {
341    if !is_review_run(state) {
342        return;
343    }
344    let base = review_base(
345        &state.repo,
346        &state.config.merge.remote,
347        &state.base_branch,
348        &state.base_commit,
349        branch,
350    )
351    .await;
352    if let Ok(subjects) = git::subjects(&state.repo, &base, branch).await
353        && !subjects.is_empty()
354        && state.reviewed_commits.as_ref() != Some(&subjects)
355    {
356        state.reviewed_commits = Some(subjects);
357        state.save().ok();
358    }
359}
360
361/// Subjects of the base's commits between the recorded start and the branch's
362/// merge base: what a stale `base_commit..branch` would have mistaken for the
363/// branch's own work.
364async fn leaked_subjects(state: &RunState, branch: &str) -> Option<Vec<String>> {
365    let (base, trusted) = review_base_checked(
366        &state.repo,
367        &state.config.merge.remote,
368        &state.base_branch,
369        &state.base_commit,
370        branch,
371    )
372    .await;
373    if !trusted {
374        return None;
375    }
376    git::subjects(&state.repo, &state.base_commit, &base)
377        .await
378        .ok()
379}
380
381/// May an adopted pull request's title be replaced with `computed`? Only when
382/// it is empty, magi's own shape, or a base commit's subject that leaked in;
383/// a title a person wrote stays. Never when `computed` is itself a leak.
384pub(crate) fn should_retitle(current: &str, computed: &str, leaked: &[String]) -> bool {
385    let is_leak = |t: &str| leaked.iter().any(|l| l.trim() == t.trim());
386    if is_leak(computed) {
387        return false;
388    }
389    let cur = current.trim();
390    cur.is_empty()
391        || cur.starts_with(REVIEW_PROMPT_OPENING)
392        || cur.starts_with("chore: land candidate")
393        || cur.starts_with("magi: candidate")
394        || is_leak(cur)
395}
396
397/// The commit a run branches from: the base branch as the remote has it.
398///
399/// Two failures this replaces. A run used to branch off `HEAD` and so refused
400/// to start on a dirty tree, which made `magi serve` decline every task for as
401/// long as the operator had work in progress - most of the time. Branching off
402/// the *local* base branch fixed that and introduced a worse one: `land` merges
403/// the winner on GitHub, nothing updates the local ref, and the next run
404/// branches off a base missing everything the previous runs landed. Two tasks
405/// in a row from a phone would have had the second silently re-implementing
406/// against stale code and opening a pull request that reverted the first.
407///
408/// Only refs move here - no checkout, no local branch, no merge - so it is safe
409/// with uncommitted work in the tree. A machine with no network still starts:
410/// the fetch may fail and the local tip is used with a warning, because
411/// refusing to run offline is a worse failure than running against a base the
412/// operator can see for themselves.
413///
414/// One function, called by both entry points. Two answers to "where does a run
415/// branch from" is the kind of drift nobody notices until a diff is wrong.
416/// Bring the local `branch` in line with `<remote>/<branch>` before a review
417/// checks it out.
418///
419/// `git worktree add <branch>` resolves the *local* ref, and a branch pushed by
420/// anything other than plain `git push` from this checkout (a jj colocated
421/// workspace, another clone) moves only the remote-tracking ref - so the local
422/// one can be a stale placeholder. It moves only when local is behind the remote or is an
423/// empty placeholder that diverged from it; unpushed local work is kept, and a real
424/// divergence is refused rather than guessed at.
425async fn sync_review_branch(repo: &Path, branch: &str, remote: &str, base: &str) -> Result<()> {
426    let tracking = format!("{remote}/{branch}");
427    let fetched = git::fetch(repo, remote, branch).await;
428    let fresh = matches!(&fetched, Ok(o) if o.ok()) && git::rev_exists(repo, &tracking).await;
429    let local_exists = git::branch_exists(repo, branch).await?;
430    if !fresh {
431        if !local_exists {
432            bail!("no branch `{branch}` in {} or on {remote}", repo.display());
433        }
434        tracing::warn!(
435            "could not read {tracking}; reviewing the local `{branch}`, which may be stale"
436        );
437        return Ok(());
438    }
439    let remote_sha = git::rev_parse(repo, &tracking).await?;
440    if !local_exists {
441        git::git(repo, &["branch", branch, &tracking]).await?;
442        return Ok(());
443    }
444    let local_sha = git::rev_parse(repo, &format!("refs/heads/{branch}")).await?;
445    if local_sha == remote_sha || git::is_ancestor(repo, &remote_sha, &local_sha).await {
446        return Ok(());
447    }
448    if !git::is_ancestor(repo, &local_sha, &remote_sha).await {
449        // Diverged. `reconcile` settles it only when it can prove nothing is
450        // lost: a local tip that is the remote's change rebased is pushed over
451        // it (lease pinned to the tip read here), a tip whose every extra
452        // commit is empty is a placeholder the remote's work replaced, and
453        // anything else is two different changes - a question for a person.
454        match crate::reconcile::reconcile(repo, remote, branch, &local_sha, &remote_sha, base)
455            .await?
456        {
457            crate::reconcile::Reconciliation::Pushed => {
458                tracing::warn!(
459                    "local `{branch}` ({}) is {tracking} ({}) rebased; pushed it over",
460                    short(&local_sha),
461                    short(&remote_sha)
462                );
463                return Ok(());
464            }
465            crate::reconcile::Reconciliation::Placeholder => {}
466            crate::reconcile::Reconciliation::Genuine(d) => return Err((*d).into()),
467        }
468    }
469    let out = git::git_raw(repo, &["branch", "-f", branch, &tracking]).await?;
470    if !out.ok() {
471        bail!(
472            "local `{branch}` ({}) is stale against {tracking} ({}) but git will not move it: {}",
473            short(&local_sha),
474            short(&remote_sha),
475            out.stderr
476        );
477    }
478    tracing::warn!(
479        "local `{branch}` was stale: fast-forwarded {} -> {}",
480        short(&local_sha),
481        short(&remote_sha)
482    );
483    Ok(())
484}
485
486async fn resolve_base(
487    repo: &Path,
488    base_branch: &str,
489    remote: &str,
490    coordination: Option<&crate::config::Coordination>,
491) -> Result<crate::run::FetchedBase> {
492    let _lease = crate::repo_lock::SeatLease::operation_with(
493        repo,
494        coordination,
495        &crate::repo_lock::WaitPolicy::current(),
496    )
497    .await?;
498    let tracking = format!("{remote}/{base_branch}");
499    let fetched = git::fetch(repo, remote, base_branch).await;
500    if let Ok(out) = &fetched
501        && out.ok()
502        && git::rev_exists(repo, &tracking).await
503    {
504        return Ok(crate::run::FetchedBase {
505            remote: remote.to_owned(),
506            branch: base_branch.to_owned(),
507            commit: git::rev_parse(repo, &tracking).await?,
508            fetched_at: jiff::Timestamp::now(),
509        });
510    }
511    let why = match &fetched {
512        Ok(out) if !out.ok() => out.stderr.trim().to_owned(),
513        Ok(_) => format!("{remote} has no {base_branch}"),
514        Err(e) => e.to_string(),
515    };
516    // No fallback to the local branch: it may be behind, and branching off an
517    // old commit is the stale-checkout bug this check exists to prevent.
518    bail!(
519        "cannot read {tracking} ({why}); refusing to branch off the local \
520         `{base_branch}`, which may be behind. Fix the remote, or set [merge] \
521         base / remote in magi.toml. This is launcher preparation: check the \
522         launcher's network, Git access and repository coordination before \
523         retrying"
524    )
525}
526
527/// Outcome of the shared fixer chain, before caller-owned stop policy.
528enum FixStep {
529    Resource,
530    Recorded { report_lost: bool },
531}
532
533/// Exclusive claim shared by targeted repairs and repository reassignment.
534/// Held before asynchronous fix preflight and released on every return or panic.
535///
536/// `daemon::is_working_on` only sees a heartbeat-publishing daemon; two
537/// manual `magi fix` invocations against the same run are otherwise
538/// invisible to each other and would race to remove and recreate the same
539/// worktree (see [`Runner::fix_selected`]). The lock file itself is the same
540/// `create_new` shape as `queue::Claim`, but unlike a queued task's lock —
541/// which is only ever reclaimed later, out of band, by
542/// `daemon::sweep_stale_claims` running inside `magi serve`/`magi web` — a
543/// `magi fix` invocation is not necessarily running under either of those, so
544/// nothing would ever sweep a lock a killed or crashed process left behind.
545/// [`Self::acquire`] therefore reclaims a stale lock itself, on the same
546/// conservative PID-liveness policy `sweep_stale_claims` and `cache`'s own
547/// lease use: an unreadable or unparsable pid, or a liveness query the
548/// platform cannot answer, reads as alive and the lock is left in place.
549pub(crate) struct FixClaim {
550    path: PathBuf,
551}
552
553impl FixClaim {
554    pub(crate) fn acquire(dir: &Path) -> Result<Self> {
555        std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
556        let path = dir.join("fix.lock");
557        let retry = crate::lock_file::Retry::new(None);
558        match Self::create(&path, retry) {
559            Ok(claim) => Ok(claim),
560            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
561                if Self::reclaim_if_dead(&path) {
562                    Self::create(&path, retry).with_context(|| format!("lock {}", path.display()))
563                } else {
564                    bail!(
565                        "another repair or `magi fix` is already running for this run ({} exists)",
566                        path.display()
567                    )
568                }
569            }
570            Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
571        }
572    }
573
574    fn create(path: &Path, retry: crate::lock_file::Retry) -> std::io::Result<Self> {
575        let mut f = retry.create(path)?;
576        use std::io::Write as _;
577        // Read back by `reclaim_if_dead` on a later, stuck invocation.
578        writeln!(f, "{}", std::process::id())?;
579        Ok(Self {
580            path: path.to_owned(),
581        })
582    }
583
584    /// True if the lock named a process confirmed dead, in which case it was
585    /// also removed. Never true on an unreadable file, an unparsable pid, or
586    /// a liveness query the platform cannot answer — see this type's own doc.
587    fn reclaim_if_dead(path: &Path) -> bool {
588        let dead = std::fs::read_to_string(path)
589            .ok()
590            .and_then(|body| body.trim().parse::<u32>().ok())
591            .is_some_and(|pid| !crate::proc::pid_alive(pid));
592        dead && std::fs::remove_file(path).is_ok()
593    }
594}
595
596impl Drop for FixClaim {
597    fn drop(&mut self) {
598        let _ = std::fs::remove_file(&self.path);
599    }
600}
601
602/// Holds the mutable runner as well as its durable lease: cancellation must
603/// clear both copies of ownership, including state a caller may save later.
604struct DriverExecution<'a> {
605    runner: &'a mut Runner,
606    driver: crate::driver::DriverGuard,
607}
608
609impl Drop for DriverExecution<'_> {
610    fn drop(&mut self) {
611        self.driver.release_local(&mut self.runner.state);
612    }
613}
614
615fn startup_stage(state: &mut RunState, stage: &str) -> Result<()> {
616    if let Some(startup) = &mut state.startup {
617        startup.stage = stage.to_owned();
618    }
619    state.save()
620}
621
622/// Keep a reservation visible as blocked until startup finishes. A killed process
623/// leaves the same explicit incomplete marker; dropping a cancelled future records it.
624struct StartupGuard {
625    id: String,
626    armed: bool,
627}
628
629impl StartupGuard {
630    fn reserve(state: &mut RunState, kind: &str, branch: Option<&str>) -> Result<Self> {
631        state.startup = Some(crate::run::Startup {
632            kind: kind.to_owned(),
633            branch: branch.map(str::to_owned),
634            stage: "reserved".to_owned(),
635            complete: false,
636            failure: None,
637        });
638        state.status = RunStatus::Blocked;
639        state.reserve()?;
640        Ok(Self {
641            id: state.id.clone(),
642            armed: true,
643        })
644    }
645
646    fn stage(&self, state: &mut RunState, stage: &str) -> Result<()> {
647        startup_stage(state, stage)
648    }
649
650    fn finish(mut self, state: &mut RunState, result: Result<()>) -> Result<()> {
651        let result = result.and_then(|()| {
652            state.startup.as_mut().expect("reserved startup").complete = true;
653            state.save()
654        });
655        self.armed = false;
656        match result {
657            Ok(()) => Ok(()),
658            Err(error) => {
659                let startup = state.startup.as_mut().expect("reserved startup");
660                startup.complete = false;
661                startup.failure = Some(format!("{error:#}"));
662                let context = crate::run::StartupFailure {
663                    run: state.id.clone(),
664                    stage: startup.stage.clone(),
665                };
666                // Repository assets may remain. Never infer that a failed startup
667                // is safe to resume or that an earlier owner has been restored.
668                state.status = RunStatus::Failed;
669                state.driver_exited = true;
670                state.event(
671                    "startup-failed",
672                    format!("{context}: {error:#}; retained assets require inspection"),
673                );
674                if let Err(save) = state.save() {
675                    tracing::warn!(
676                        "run {}: could not save terminal startup record: {save:#}; reservation requires reconciliation",
677                        state.id
678                    );
679                }
680                Err(error.context(context))
681            }
682        }
683    }
684}
685
686impl Drop for StartupGuard {
687    fn drop(&mut self) {
688        if self.armed
689            && let Ok(mut state) = RunState::load(&self.id)
690        {
691            state.status = RunStatus::Blocked;
692            state.driver_exited = true;
693            if let Some(startup) = &mut state.startup {
694                startup.failure = Some("startup interrupted; reconciliation required".to_owned());
695            }
696            state.event(
697                "startup-interrupted",
698                "startup did not finish; inspect retained assets before recovery",
699            );
700            if let Err(error) = state.save() {
701                tracing::error!(
702                    "could not record interrupted startup {}: {error:#}",
703                    self.id
704                );
705            }
706        }
707    }
708}
709
710impl Runner {
711    /// A queue-side failure after construction must not strand an unexecuted run.
712    pub(crate) fn fail_startup(&mut self, stage: &str, error: anyhow::Error) -> anyhow::Error {
713        if !self.state.passes.is_empty() || self.state.driver_claimed != Some(false) {
714            return error;
715        }
716        if let Some(startup) = &mut self.state.startup {
717            startup.stage = stage.to_owned();
718        } else {
719            // A resumed run already has execution history: do not rewrite it.
720            return error;
721        }
722        StartupGuard {
723            id: self.state.id.clone(),
724            armed: true,
725        }
726        .finish(&mut self.state, Err(error))
727        .expect_err("startup failed")
728    }
729
730    /// Start a fresh run against `repo`.
731    pub async fn start(
732        repo: &Path,
733        instruction: String,
734        config: Config,
735        origin: Origin,
736    ) -> Result<Self> {
737        Self::start_naming(repo, instruction, "", config, origin).await
738    }
739
740    /// [`Runner::start`] for a queued task. Titles and instructions never
741    /// select implementation sources. The title argument is retained for callers.
742    pub async fn start_naming(
743        repo: &Path,
744        instruction: String,
745        _also_scan: &str,
746        config: Config,
747        origin: Origin,
748    ) -> Result<Self> {
749        let repo = git::toplevel(repo).await?;
750        let missing = agent::missing_programs(&config.agents);
751        if !missing.is_empty() {
752            bail!(
753                "these agent programs are not on PATH: {}. Fix the roster in \
754                 magi.toml or install them.",
755                missing.join(", ")
756            );
757        }
758        let base_branch =
759            git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
760                .await?;
761        let fetched_base = resolve_base(
762            &repo,
763            &base_branch,
764            &config.merge.remote,
765            config.coordination.as_ref(),
766        )
767        .await?;
768        let base_commit = fetched_base.commit.clone();
769        let roles = config.resolve_roles()?;
770        let max_parallel = config.graph.max_parallel.max(1);
771        let mut state = RunState::new(repo, base_branch, base_commit, instruction, config);
772        // Capture task identity and repository assignment before the first
773        // save, so publication scope survives crashes and later task moves.
774        state.fetched_base = Some(fetched_base);
775        state.set_origin(origin)?;
776        let startup = StartupGuard::reserve(&mut state, "implementation", None)?;
777        state.status = RunStatus::Prep;
778        state.event("start", format!("run {} created", state.id));
779        startup.finish(&mut state, Ok(()))?;
780        Ok(Self {
781            state,
782            roles,
783            sem: Arc::new(Semaphore::new(max_parallel)),
784            pause: Pause::new(),
785            interrupt: Pause::new(),
786        })
787    }
788
789    /// Open a review-only run against work that already exists on `branch`.
790    ///
791    /// The expensive half of the graph is the implement wave — measured at
792    /// 111 and 134 internal tool-loop turns on this repository, against a
793    /// handful for a judge or a reviewer. The cheap half is worth running on
794    /// hand-written work too, and there was no way to reach it.
795    ///
796    /// No new state and no schema change are needed: a run with **one** viable
797    /// candidate and a tally already decided degrades `execute` to exactly
798    /// review → gate → merge, because `judge` skips a single-candidate field,
799    /// `deliberate` has fewer than two first choices to reconcile, `vote`
800    /// returns early, `tally` is already present and `fold_losers` has no
801    /// losers. Resuming such a run therefore does the right thing as well.
802    pub async fn review(repo: &Path, branch: &str, config: Config, origin: Origin) -> Result<Self> {
803        Self::review_taking_over(repo, branch, config, None, origin).await
804    }
805
806    /// [`Runner::review`] for a queued task's retry: when an earlier attempt
807    /// at the same task still has `branch` checked out, its worktree is
808    /// released first if that is safe (see [`crate::handover`]), and the
809    /// review refuses with the reason if it is not. `None` is a hand-run
810    /// review: it has no earlier attempts, so only a worktree of a dead run
811    /// magi recorded itself can be released.
812    pub async fn review_taking_over(
813        repo: &Path,
814        branch: &str,
815        config: Config,
816        takeover: Option<crate::handover::Takeover>,
817        origin: Origin,
818    ) -> Result<Self> {
819        let repo = git::toplevel(repo).await?;
820        let missing = agent::missing_programs(&config.agents);
821        if !missing.is_empty() {
822            bail!(
823                "these agent programs are not on PATH: {}. Fix the roster in \
824                 magi.toml or install them.",
825                missing.join(", ")
826            );
827        }
828        let base_branch =
829            git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
830                .await?;
831        if base_branch == branch {
832            bail!("`{branch}` is the base branch; there is nothing to review against");
833        }
834        let fetched_base = resolve_base(
835            &repo,
836            &base_branch,
837            &config.merge.remote,
838            config.coordination.as_ref(),
839        )
840        .await?;
841        let base_commit = fetched_base.commit.clone();
842
843        let roles = config.resolve_roles()?;
844        let max_parallel = config.graph.max_parallel.max(1);
845        let mut state = RunState::new(
846            repo.clone(),
847            base_branch,
848            base_commit.clone(),
849            format!("Review the work already on branch `{branch}`."),
850            config,
851        );
852        state.fetched_base = Some(fetched_base);
853        state.set_origin(origin)?;
854        state.task_instruction = takeover.as_ref().and_then(|t| t.task_instruction.clone());
855        let startup = StartupGuard::reserve(&mut state, "review", Some(branch))?;
856        let opened = async {
857            startup.stage(&mut state, "handover")?;
858
859            // Released before anything else touches the branch: a stale local
860            // branch is moved with `git branch -f`, which git refuses while an
861            // earlier attempt's worktree still has it checked out. Everything
862            // after this point that can fail puts the old run back.
863            // A hand-run review has no task, hence no earlier attempts, but a
864            // worktree of a dead run magi made may still be released.
865            let takeover = takeover.unwrap_or_else(|| crate::handover::Takeover {
866                earlier: Vec::new(),
867                home: crate::run::home(),
868                choice: None,
869                task_instruction: None,
870            });
871            let wait = repository_wait(&state, None);
872            let coordination_config = state.config.coordination.clone();
873            let coordination =
874                crate::repo_lock::SeatLease::operation_with(&repo, coordination_config.as_ref(), &wait)
875                    .await?;
876            let released = crate::handover::release(&repo, branch, &state.id, &takeover).await?;
877            if let Some(released) = &released {
878                state.event(
879                    "release",
880                    format!(
881                        "took `{branch}` over from run {}: its worktree was released: {}",
882                        crate::run::short_of(&released.old_id),
883                        released.audit
884                    ),
885                );
886            }
887            let opened = async {
888                startup.stage(&mut state, "review-preflight")?;
889                // The owner's answer to an earlier divergence question is applied
890                // here: after the release (git will not move a checked-out branch)
891                // and before the sync that would otherwise ask again.
892                state.foreign_checkout = crate::handover::preflight_review(
893                    &repo,
894                    branch,
895                    &takeover.home,
896                    &state.config.merge.remote,
897                )
898                .await?;
899                if state.foreign_checkout.is_some() && takeover.choice.is_some() {
900                    bail!("cannot reconcile a foreign checkout automatically; resolve its branch first");
901                }
902                if let Some(choice) = takeover.choice.as_ref()
903                    && let Err(e) =
904                        crate::reconcile::apply_choice(&repo, &state.config.merge.remote, branch, choice)
905                            .await
906                {
907                    return Err(e.context("applying the owner's answer about the diverged branch"));
908                }
909                // An earlier attempt of this task that published the task head, and
910                // whose work is the branch under review, hands that head over: the
911                // review run updates the same pull request. Without one (a legacy
912                // `magi/<run>/<label>` PR, a hand-named branch) the branch keeps its
913                // own head and its own open pull request is adopted as before.
914                for id in takeover.earlier.iter().rev() {
915                    if let Ok(old) = RunState::load_under(id, &takeover.home)
916                        && let Some(head) = old.pr_head.clone()
917                        && (head == branch || old.winner().is_some_and(|w| w.branch == branch))
918                    {
919                        state.pr_head = Some(head);
920                        break;
921                    }
922                }
923                drop(coordination);
924                startup.stage(&mut state, "open-review")?;
925                Self::open_review(&repo, branch, &mut state, base_commit, &takeover).await
926            }
927            .await;
928            if opened.is_err()
929                && let Some(released) = &released
930            {
931                // Restoration is ownership checked and best effort. Keep the original
932                // startup cause even if reacquiring coordination is no longer possible.
933                match crate::repo_lock::SeatLease::operation_with(
934                    &repo,
935                    coordination_config.as_ref(),
936                    &wait,
937                )
938                .await
939                {
940                    Ok(_coordination) => {
941                        released.restore(&repo, branch).await;
942                        let outcome = RunState::load_under(&released.old_id, &takeover.home)
943                            .map(|old| {
944                                format!(
945                                    "predecessor released_to={:?}; candidate path exists={}",
946                                    old.released_to,
947                                    old.candidates.iter().any(|c| {
948                                        c.branch == branch && c.worktree.exists()
949                                    }),
950                                )
951                            })
952                            .unwrap_or_else(|error| format!("predecessor could not be inspected: {error:#}"));
953                        state.event("startup-restore", format!("ownership-checked restoration attempted: {outcome}; retained successor assets require inspection"));
954                    }
955                    Err(error) => {
956                        tracing::warn!(
957                            "run {}: could not take the repository lease to restore `{branch}`: {error:#}",
958                            state.id
959                        );
960                        state.event(
961                            "startup-restore",
962                            format!("restoration not attempted: {error:#}"),
963                        );
964                    }
965                }
966            }
967            opened
968        }
969        .await;
970        startup.finish(&mut state, opened)?;
971        Ok(Self {
972            state,
973            roles,
974            sem: Arc::new(Semaphore::new(max_parallel)),
975            pause: Pause::new(),
976            interrupt: Pause::new(),
977        })
978    }
979
980    /// Recover exactly the operator-selected public implementation, without touching old sources.
981    pub async fn recover_pr(
982        repo: &Path,
983        task: &str,
984        selection: crate::pr_recovery::Selection,
985        mut config: Config,
986    ) -> Result<Self> {
987        selection.configure(&mut config)?;
988        let assignment = crate::run::task_assignment_for(task)?;
989        selection.check_task_assignment(task, &selection.instruction, assignment)?;
990        let base_branch =
991            git::merge_base_branch(repo, &config.merge.remote, config.merge.base.as_deref())
992                .await?;
993        let fetched_base = resolve_base(
994            repo,
995            &base_branch,
996            &config.merge.remote,
997            config.coordination.as_ref(),
998        )
999        .await?;
1000        let base_commit = fetched_base.commit.clone();
1001        selection
1002            .verify(repo, &config.merge.remote, &base_branch, &selection.head)
1003            .await?;
1004        Box::pin(selection.verify_source(repo)).await?;
1005        if let Some(proof) = &selection.source_proof {
1006            anyhow::ensure!(
1007                git::is_ancestor(repo, &proof.new_base, &base_commit).await,
1008                "source rebase base is outside the fetched landing base"
1009            );
1010        }
1011        let roles = config.resolve_roles()?;
1012        let max_parallel = config.graph.max_parallel.max(1);
1013        let mut state = RunState::new(
1014            repo.to_path_buf(),
1015            base_branch,
1016            base_commit.clone(),
1017            selection.instruction.clone(),
1018            config,
1019        );
1020        state.fetched_base = Some(fetched_base);
1021        state.set_origin(crate::run::Origin::queue(task))?;
1022        state.pr_head = Some(selection.branch.clone());
1023        state.pr_recovery = Some(selection.clone());
1024        Self::open_selected(repo, state, roles, max_parallel, base_commit, selection).await
1025    }
1026
1027    async fn open_selected(
1028        repo: &Path,
1029        mut state: RunState,
1030        roles: ResolvedRoles,
1031        max_parallel: usize,
1032        base_commit: String,
1033        selection: crate::pr_recovery::Selection,
1034    ) -> Result<Self> {
1035        let startup = StartupGuard::reserve(&mut state, "pr-recovery", Some(&selection.branch))?;
1036        let opened = async {
1037            startup.stage(&mut state, "predecessors")?;
1038            crate::pr_head::check_predecessors(&state, &selection.branch).await?;
1039            startup.stage(&mut state, "open-selected")?;
1040            let branch = state.branch_for('A');
1041            let wait = repository_wait(&state, None);
1042            let prepared = async {
1043                let coordination = coordinate_operation(&mut state, repo, &wait).await?;
1044                git::git(repo, &["branch", &branch, selection.source()]).await?;
1045                drop(coordination);
1046                anyhow::Ok(())
1047            }
1048            .await;
1049            prepared?;
1050            state.event(
1051                "recovery",
1052                format!(
1053                    "selected implementation {} for {} (public lease {})",
1054                    selection.source(),
1055                    selection.url,
1056                    selection.head
1057                ),
1058            );
1059            let takeover = crate::handover::Takeover {
1060                earlier: Vec::new(),
1061                home: crate::run::home(),
1062                choice: None,
1063                task_instruction: Some(selection.instruction.clone()),
1064            };
1065            state.save()?;
1066            Self::open_review(repo, &branch, &mut state, base_commit, &takeover).await
1067        }
1068        .await;
1069        startup.finish(&mut state, opened)?;
1070        Ok(Self {
1071            state,
1072            roles,
1073            sem: Arc::new(Semaphore::new(max_parallel)),
1074            pause: Pause::new(),
1075            interrupt: Pause::new(),
1076        })
1077    }
1078
1079    /// What the newest earlier attempt that reviewed `branch` leaves for this
1080    /// run (see [`crate::recovery`]). `None` for a hand-run review, which has
1081    /// no earlier attempts. Reads the earlier record only: ownership of its
1082    /// worktree and branch is [`crate::handover`]'s business.
1083    async fn inherit(
1084        repo: &Path,
1085        branch: &str,
1086        base_commit: &str,
1087        takeover: &crate::handover::Takeover,
1088    ) -> Option<crate::recovery::RecoveryRecord> {
1089        use crate::recovery::{Relation, assess};
1090        let newest = takeover.earlier.last()?;
1091        let mut chosen = None;
1092        for id in takeover.earlier.iter().rev() {
1093            if let Ok(old) = RunState::load_under(id, &takeover.home)
1094                && !old.reviews.is_empty()
1095                && (old.winner().is_some_and(|w| w.branch == branch)
1096                    || old.pr_head.as_deref() == Some(branch))
1097            {
1098                chosen = Some(old);
1099                break;
1100            }
1101        }
1102        let tip = git::rev_parse(repo, &format!("refs/heads/{branch}"))
1103            .await
1104            .unwrap_or_default();
1105        let relation = match chosen.as_ref().and_then(|o| o.reviews.last()) {
1106            Some(last) if last.head == tip => Relation::Same,
1107            Some(last) if git::is_ancestor(repo, &last.head, &tip).await => Relation::Descendant,
1108            _ => Relation::Diverged,
1109        };
1110        let from = chosen.as_ref().map_or(newest.as_str(), |o| o.id.as_str());
1111        Some(assess(from, chosen.as_ref(), base_commit, relation))
1112    }
1113
1114    /// The half of [`Runner::review_taking_over`] that can fail after an
1115    /// earlier attempt's worktree was released.
1116    async fn open_review(
1117        repo: &Path,
1118        branch: &str,
1119        state: &mut RunState,
1120        base_commit: String,
1121        takeover: &crate::handover::Takeover,
1122    ) -> Result<()> {
1123        startup_stage(state, "review-sync")?;
1124        let wait = repository_wait(state, None);
1125        let _coordination = coordinate_operation(state, repo, &wait).await?;
1126        if state.foreign_checkout.is_some() {
1127            // Never reconcile or force-move a ref checked out by the operator.
1128            if state.pr_head.is_none() {
1129                state.pr_head = Some(branch.to_owned());
1130            }
1131        } else if state.pr_recovery.is_none() {
1132            sync_review_branch(repo, branch, &state.config.merge.remote, &base_commit).await?;
1133        }
1134        // The commit subjects are the closest thing to a task statement that
1135        // existing work carries, and the reviewers are told as much.
1136        let start = review_base(
1137            repo,
1138            &state.config.merge.remote,
1139            &state.base_branch,
1140            &base_commit,
1141            branch,
1142        )
1143        .await;
1144        let log = git::log_oneline(repo, &start, branch)
1145            .await
1146            .unwrap_or_default();
1147        let log_text = if log.trim().is_empty() {
1148            "(no commit messages)"
1149        } else {
1150            log.trim()
1151        };
1152        let mut instruction = format!(
1153            "Review the work already on branch `{branch}`. There is no task \
1154             statement: what the change claims to do is whatever its commits \
1155             say.\n\n{log_text}"
1156        );
1157        // A retry of a task whose earlier attempt left reviews behind carries
1158        // that attempt's evidence, and the task's own statement with it: the
1159        // completion criteria are the task's, not whatever the commits claim.
1160        if let Some(mut rec) = Self::inherit(repo, branch, &base_commit, takeover).await {
1161            if let Some(task) = takeover
1162                .task_instruction
1163                .as_deref()
1164                .filter(|t| !t.trim().is_empty())
1165                && rec.reviewed_head.is_some()
1166            {
1167                instruction = format!(
1168                    "{}\n\n# Work already on branch `{branch}` (commit subjects)\n\n{log_text}",
1169                    task.trim()
1170                );
1171                rec.criteria_inherited = true;
1172            }
1173            state.event("recovery", rec.summary());
1174            state.recovery = Some(rec);
1175        }
1176        if let Some(selected) = &state.pr_recovery {
1177            instruction = selected.instruction.clone();
1178        }
1179        state.task_instruction = takeover.task_instruction.clone();
1180        state.instruction = instruction;
1181        state.reviewed_commits = Some(
1182            git::subjects(repo, &start, branch)
1183                .await
1184                .unwrap_or_default(),
1185        );
1186
1187        // A takeover must not forget a hold that a previous review observed,
1188        // even if repairs have since removed it from the branch.
1189        for id in &takeover.earlier {
1190            if let Ok(old) = RunState::load_under(id, &takeover.home)
1191                && old.repo == state.repo
1192                && (old.pr_head.as_deref() == Some(branch)
1193                    || old.winner().is_some_and(|w| w.branch == branch))
1194            {
1195                for hold in old.branch_owner_holds {
1196                    if !state.branch_owner_holds.contains(&hold) {
1197                        state.event(
1198                            "approval-policy",
1199                            format!(
1200                                "inherited {}=true from the reviewed branch's {} at {} (run {id})",
1201                                hold.control.key(),
1202                                hold.file,
1203                                hold.head
1204                            ),
1205                        );
1206                        state.branch_owner_holds.push(hold);
1207                    }
1208                }
1209            }
1210        }
1211        // Select the actual review tip before observing owner policy. A foreign
1212        // checkout can lag its remote descendant, and repairs must not erase
1213        // holds introduced only on that selected commit.
1214        let reviewed_head = if let Some(checkout) = &state.foreign_checkout {
1215            let tracking = format!("{}/{branch}", state.config.merge.remote);
1216            // A surviving tracking ref is not evidence that the remote still
1217            // offers this tip. Adopt it only after a successful fetch here.
1218            let fetched = git::fetch(repo, &state.config.merge.remote, branch).await;
1219            let mut head = checkout.synced_head.clone();
1220            if matches!(fetched, Ok(out) if out.ok()) {
1221                let remote = git::rev_parse(repo, &tracking).await?;
1222                if git::is_ancestor(repo, &checkout.synced_head, &remote).await {
1223                    head = remote;
1224                }
1225            }
1226            head
1227        } else {
1228            git::rev_parse(repo, branch).await?
1229        };
1230        state.observe_branch_owner_holds(&reviewed_head).await;
1231
1232        // An attached worktree, so the fixer's commits land on the branch under
1233        // review rather than on a detached head nobody will look at again.
1234        let worktree = state.worktree_root().join("under-review");
1235        if let Some(parent) = worktree.parent() {
1236            tokio::fs::create_dir_all(parent).await.ok();
1237        }
1238        let path = worktree.to_string_lossy().to_string();
1239        let review_branch = if state.foreign_checkout.is_some() {
1240            let shadow = format!("magi/{}/review", state.short());
1241            git::git(repo, &["branch", &shadow, &reviewed_head]).await?;
1242            shadow
1243        } else {
1244            branch.to_owned()
1245        };
1246        startup_stage(state, "review-checkout")?;
1247        git::git(repo, &["worktree", "add", &path, &review_branch])
1248            .await
1249            .with_context(|| {
1250                format!("checking out `{branch}` at {path} (is it checked out elsewhere?)")
1251            })?;
1252
1253        startup_stage(state, "worktree-setup")?;
1254        let setup = match ensure_setup_config(state, repo).await {
1255            Ok(()) => {
1256                worktree_setup::prepare_with(
1257                    &state.config,
1258                    repo,
1259                    &worktree,
1260                    crate::build_target::Coordination::Held(_coordination.as_ref()),
1261                )
1262                .await
1263            }
1264            Err(e) => Err(e),
1265        };
1266        if let Err(e) = setup {
1267            git::worktree_remove_clean(repo, &worktree).await.ok();
1268            return Err(e);
1269        }
1270        let commits = git::commits_ahead(&worktree, &base_commit, "HEAD")
1271            .await
1272            .unwrap_or(0);
1273        if commits == 0 {
1274            git::worktree_remove_clean(repo, &worktree).await.ok();
1275            bail!("`{branch}` has no commits beyond {}", short(&base_commit));
1276        }
1277        let files = git::changed_files(&worktree, &base_commit, "HEAD")
1278            .await
1279            .map(|f| f.len())
1280            .unwrap_or(0);
1281        if files == 0
1282            && let (Ok(head_tree), Ok(base_tree)) = (
1283                git::tree_of(&worktree, "HEAD").await,
1284                git::tree_of(&worktree, &base_commit).await,
1285            )
1286            && head_tree == base_tree
1287        {
1288            let head = git::rev_parse(&worktree, "HEAD").await.unwrap_or_default();
1289            git::worktree_remove_clean(repo, &worktree).await.ok();
1290            bail!(
1291                "`{branch}` at {} has a tree identical to base {}; this usually means \
1292                 the branch ref is stale (check `git rev-parse refs/heads/{branch}` \
1293                 against `{}/{branch}`) rather than an empty change",
1294                short(&head),
1295                short(&base_commit),
1296                state.config.merge.remote
1297            );
1298        }
1299        let stat = git::diff_stat(&worktree, &base_commit, "HEAD")
1300            .await
1301            .unwrap_or_default();
1302
1303        state.candidates.push(Candidate {
1304            index: 0,
1305            label: 'A',
1306            // Not an agent id on purpose: nothing in the roster wrote this, and
1307            // the stats tables must not credit anyone with a win for it.
1308            agent: EXISTING_BRANCH.to_owned(),
1309            branch: review_branch,
1310            worktree,
1311            summary: String::new(),
1312            stat,
1313            files,
1314            commits,
1315            empty: false,
1316            failed: None,
1317            verified_noop: None,
1318            duration_ms: 0,
1319            folded: false,
1320        });
1321        state.tally = Some(Tally {
1322            first_choice: BTreeMap::from([('A', 0)]),
1323            borda: BTreeMap::new(),
1324            winner: 'A',
1325            rankings: 0,
1326            unanimous_initial: false,
1327            deliberated: false,
1328            changed_votes: 0,
1329            unanimous_final: false,
1330            tie_break: None,
1331            // No panel sat, so no quorum applies. Zero judges is the correct
1332            // number for work that never competed, and must not be reported as
1333            // a collapsed panel.
1334            judges: 0,
1335            present: 0,
1336            quorum: 0,
1337            met_quorum: true,
1338            uncontested: Some("review-only run: nothing competed".to_owned()),
1339        });
1340        state.status = RunStatus::Reviewing;
1341        state.prep_complete = Some(true);
1342        state.event(
1343            "start",
1344            format!(
1345                "review-only run {} on `{branch}` ({files} files, {commits} commits)",
1346                state.id
1347            ),
1348        );
1349        Ok(())
1350    }
1351
1352    /// Authorize one bounded synchronization interval, under the caller's queue task
1353    /// claim and the same owner/execution locks used by run maintenance.
1354    pub async fn authorize_base_recovery(home: &Path, id: &str, task: &str) -> Result<()> {
1355        Self::authorize_base_recovery_request(home, id, task, false, None).await
1356    }
1357
1358    /// Queue release uses its durable approval generation exactly once.
1359    pub(crate) async fn authorize_base_recovery_from_resumption(
1360        home: &Path,
1361        id: &str,
1362        task: &str,
1363    ) -> Result<()> {
1364        Self::authorize_base_recovery_request(home, id, task, true, None).await
1365    }
1366
1367    pub(crate) async fn authorize_base_recovery_control(
1368        home: &Path,
1369        task: &str,
1370        control: &mut crate::base_recovery_control::Transaction,
1371    ) -> Result<()> {
1372        let id = control.request.run.clone();
1373        Self::authorize_base_recovery_request(home, &id, task, false, Some(control)).await
1374    }
1375
1376    async fn authorize_base_recovery_request(
1377        home: &Path,
1378        id: &str,
1379        task: &str,
1380        resumption: bool,
1381        mut control: Option<&mut crate::base_recovery_control::Transaction>,
1382    ) -> Result<()> {
1383        let _owner = crate::pr_head::owner_lock(home, id)?;
1384        let mut state = RunState::load_under(id, home)?;
1385        crate::pr_head::ensure_owner(&state)?;
1386        let queued = crate::queue::Queue::at(home.join("queue")).get(task)?;
1387        anyhow::ensure!(
1388            queued.execution_runs().last().is_some_and(|run| run == id)
1389                && queued.status != crate::queue::TaskStatus::Done
1390                && !queued.fresh_start
1391                && queued.review_branch.is_none(),
1392            "run task ownership changed"
1393        );
1394        anyhow::ensure!(
1395            state
1396                .origin
1397                .as_ref()
1398                .and_then(|o| o.task.as_deref())
1399                .is_none_or(|owner| owner == task),
1400            "run belongs to another task"
1401        );
1402        let claimed = crate::daemon::is_working_on_other(home, id, Timestamp::now())?;
1403        anyhow::ensure!(
1404            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
1405            "run is live or its ownership is unknown"
1406        );
1407        // Judge the previous driver's lease before acquiring our maintenance
1408        // lease. The owner lock excludes new driver claims across both steps.
1409        let _execution = crate::driver::maintenance(home, id)?;
1410        anyhow::ensure!(
1411            state.status.resumable()
1412                && state.released_to.is_none()
1413                && state.retired_to.is_none()
1414                && state.pr_taken_over_by.is_none(),
1415            "run ownership is final"
1416        );
1417        anyhow::ensure!(state.base_sync_blocked(), "run has no base-sync stop");
1418        anyhow::ensure!(
1419            !state.pr_publication_pending
1420                && !crate::handover::landing_checkpoint(&state)
1421                && state.merge_decision.is_none(),
1422            "publication or landing has its own retained checkpoint; base recovery cannot replace it"
1423        );
1424        let winner = state.winner().context("run has no retained winner")?;
1425        anyhow::ensure!(
1426            git::is_clean(&winner.worktree).await?,
1427            "retained worktree has uncommitted changes"
1428        );
1429        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
1430        anyhow::ensure!(
1431            git::rev_parse(&state.repo, &format!("refs/heads/{}", winner.branch)).await? == head,
1432            "retained worktree does not match the winner branch"
1433        );
1434        if let Some(control) = control.as_ref() {
1435            anyhow::ensure!(
1436                head.starts_with(&control.request.head),
1437                "retained HEAD changed since the owner request"
1438            );
1439            anyhow::ensure!(
1440                state
1441                    .base_sync_recovery
1442                    .stop
1443                    .as_ref()
1444                    .is_none_or(|stop| stop.head == head),
1445                "retained HEAD differs from the recorded stop head; inspect it first"
1446            );
1447        }
1448        state.ensure_base_episode();
1449        state.record_base_sync_stop(&head);
1450        anyhow::ensure!(
1451            state
1452                .base_sync_recovery
1453                .stop
1454                .as_ref()
1455                .is_some_and(|s| s.kind == crate::base_sync_recovery::StopKind::Exhausted),
1456            "base recovery refused: missing eligible movement-exhaustion evidence; inspect with `magi task inspect-base-stop {task} --run {id}`. Textual stops require an evidence-bound base-conflict grant"
1457        );
1458        let fetched =
1459            git::fetch(&state.repo, &state.config.merge.remote, &state.base_branch).await?;
1460        anyhow::ensure!(
1461            fetched.ok(),
1462            "cannot authorize base recovery without a fetched base"
1463        );
1464        let approved_tip = git::rev_parse(
1465            &state.repo,
1466            &format!("{}/{}", state.config.merge.remote, state.base_branch),
1467        )
1468        .await?;
1469        if let Some(control) = control.as_deref_mut() {
1470            let queue = crate::queue::Queue::at(home.join("queue"));
1471            control.prepare(&queue, &state, &queued, &head, &approved_tip)?;
1472            if let Some(prior) = state
1473                .base_sync_recovery
1474                .authorizations
1475                .iter()
1476                .find(|a| a.request.as_deref() == Some(&control.key()))
1477            {
1478                anyhow::ensure!(
1479                    !prior.consumed && prior.invalidated.is_none() && state.base_recovery_pending(),
1480                    "recovery request was consumed or invalidated; it cannot queue again"
1481                );
1482                return control.enqueue(&queue);
1483            }
1484        }
1485        if resumption {
1486            anyhow::ensure!(
1487                crate::daemon::compatible_run_instruction(&state, &queued),
1488                "resumption instruction does not match the retained run"
1489            );
1490            let approval = queued
1491                .resumption
1492                .as_ref()
1493                .context("no operator resumption")?;
1494            anyhow::ensure!(
1495                approval.instruction == queued.instruction,
1496                "resumption approval does not match the current task instruction"
1497            );
1498            state.authorize_base_sync_resumption(task, approval)?;
1499        } else {
1500            state.authorize_base_sync(task)?;
1501        }
1502        let episode = state.base_sync_recovery.episodes.last().unwrap().id;
1503        state
1504            .base_sync_recovery
1505            .authorizations
1506            .last_mut()
1507            .unwrap()
1508            .scope = Some(crate::base_sync_recovery::Scope {
1509            tip: approved_tip,
1510            instruction: queued.instruction.clone(),
1511            episode,
1512        });
1513        if let Some(control) = control.as_deref_mut() {
1514            let authorization = state.base_sync_recovery.authorizations.last_mut().unwrap();
1515            authorization.request = Some(control.key());
1516            authorization.generation = control.generation();
1517            authorization.decision = control.decision();
1518            authorization.question = control
1519                .request
1520                .decision
1521                .as_ref()
1522                .map(|_| control.request.request.clone());
1523        }
1524        state.event(
1525            "base-recovery",
1526            "owner authorized a bounded base synchronization interval; fresh verification required",
1527        );
1528        state.save_under(home)?;
1529        if let Some(control) = control {
1530            control.enqueue(&crate::queue::Queue::at(home.join("queue")))?;
1531        }
1532        Ok(())
1533    }
1534
1535    /// Reopen an existing run.
1536    pub fn resume(id: &str) -> Result<Self> {
1537        let state = RunState::load(id)?;
1538        crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &state.id)?;
1539        if state.startup.as_ref().is_some_and(|s| !s.complete)
1540            || (state.status == RunStatus::Prep
1541                && state.instruction.trim().is_empty()
1542                && state.candidates.is_empty()
1543                && state.prep_complete == Some(false))
1544        {
1545            bail!(
1546                "run {id} did not finish startup; inspect its startup evidence and retained assets, then start an explicitly authorized review or recovery"
1547            );
1548        }
1549        crate::pr_head::ensure_owner(&state)?;
1550        if state.pr_recovery.is_some() && state.reviewed_commits.is_none() {
1551            bail!(
1552                "selected public-head recovery did not finish setup; use `magi task recover-pr` after correcting the cause"
1553            );
1554        }
1555        if let Some(to) = &state.released_to {
1556            bail!(
1557                "run {} cannot be resumed: its worktree was released to run {}",
1558                state.short(),
1559                crate::run::short_of(to)
1560            );
1561        }
1562        let roles = state.config.resolve_roles()?;
1563        if let Some(id) = &state.config.graph.selected_implementer
1564            && state.candidates.iter().any(|c| c.agent != *id)
1565        {
1566            bail!(
1567                "replacement implementer pin does not match the saved candidates; task must stay held"
1568            );
1569        }
1570        let max_parallel = state.config.graph.max_parallel.max(1);
1571        Ok(Self {
1572            state,
1573            roles,
1574            sem: Arc::new(Semaphore::new(max_parallel)),
1575            pause: Pause::new(),
1576            interrupt: Pause::new(),
1577        })
1578    }
1579
1580    /// Walk the graph to a terminal state, skipping nodes already recorded.
1581    ///
1582    /// Every way a run is driven - the queue loop, `magi run`, a resume from
1583    /// the phone - ends here, so this is the one place a run that ended
1584    /// Blocked / Stalled / Failed, or died with an error, is announced to the
1585    /// attention-report outbox. Best-effort: see [`crate::notices::raise`].
1586    pub fn execute(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
1587        // Allocate before polling: boxing inside an async wrapper would still
1588        // retain its construction frame while the nested graph is polled.
1589        Box::pin(self.execute_inner(None))
1590    }
1591
1592    pub(crate) async fn execute_sync_only(
1593        &mut self,
1594        request: crate::base_sync_only::Request,
1595    ) -> Result<()> {
1596        Box::pin(self.execute_inner(Some(request))).await
1597    }
1598
1599    async fn execute_inner(
1600        &mut self,
1601        sync_only: Option<crate::base_sync_only::Request>,
1602    ) -> Result<()> {
1603        anyhow::ensure!(
1604            self.state.startup.as_ref().is_none_or(|s| s.complete),
1605            "startup incomplete; inspect retained evidence before explicit recovery"
1606        );
1607        if let Some(selection) = &self.state.pr_recovery
1608            && (selection.source_proof.is_some() || selection.source_run.is_some())
1609        {
1610            Box::pin(selection.verify_source(&self.state.repo)).await?;
1611        }
1612        // Queue claims cover daemon work; this also serializes manual drivers
1613        // consuming a repair answer, including the new review and decision.
1614        let _repair_claim = if self.state.config.graph.selected_implementer.is_some()
1615            || self.state.land_approval.is_some()
1616            || self.state.merge_decision.is_some()
1617            || !self.state.merge_repairs.is_empty()
1618            || (self.state.status == RunStatus::Landing && land::repair_available(&self.state))
1619        {
1620            let claim = FixClaim::acquire(&self.state.dir())?;
1621            crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &self.state.id)?;
1622            let disk = RunState::load(&self.state.id)?;
1623            let checkpoint = |s: &RunState| {
1624                (
1625                    s.merge_repairs.len(),
1626                    s.merge_repairs
1627                        .last()
1628                        .map(|r| (r.question.clone(), r.phase)),
1629                    s.land_approval
1630                        .as_ref()
1631                        .map(|a| (a.question.clone(), a.head.clone())),
1632                )
1633            };
1634            if checkpoint(&disk) != checkpoint(&self.state) {
1635                bail!(
1636                    "repair decision changed since this run was loaded; reload and resume the existing run, never start a second repair"
1637                );
1638            }
1639            Some(claim)
1640        } else {
1641            None
1642        };
1643        let base_only = sync_only.is_some();
1644        let mut execution = self.claim_driver(sync_only).await?;
1645        let runner = &mut *execution.runner;
1646        let wait = runner.repository_wait();
1647        // Keep the graph's large future off the callers' stack, including
1648        // standalone task attempts running on a default-sized test thread.
1649        let result = if base_only {
1650            wait.scope(Box::pin(async {
1651                let repo = runner.state.repo.clone();
1652                let result = async {
1653                    let _coordination = runner.coordinate(&repo).await?;
1654                    anyhow::ensure!(
1655                        !runner.pause.parked() && !runner.interrupt.parked(),
1656                        "paused before base synchronization"
1657                    );
1658                    crate::base_sync_only::sync(&mut runner.state).await
1659                }
1660                .await;
1661                let pass = runner.state.sync_only_passes.last_mut().unwrap();
1662                pass.result = match result {
1663                    Ok(outcome) => outcome,
1664                    Err(error) => crate::base_sync_only::Outcome::Stopped(format!("{error:#}")),
1665                };
1666                let summary = pass.summary();
1667                runner.state.event("base-sync-only", summary);
1668                runner.state.save()
1669            }))
1670            .await
1671        } else {
1672            wait.scope(Box::pin(runner.execute_graph())).await
1673        };
1674        let result = match result {
1675            Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
1676                record_repository_block(&mut runner.state, &e);
1677                runner.park_here()?;
1678                Ok(())
1679            }
1680            other => other,
1681        };
1682        execution.driver.finish(&mut runner.state).await?;
1683        let ended = if result.is_err() {
1684            Some({
1685                let mut notice = crate::notices::run_stopped(&runner.state.id, &runner.state);
1686                if let Err(error) = &result {
1687                    notice.message = format!(
1688                        "Run {} stopped with an error: {}",
1689                        runner.state.id,
1690                        error.to_string().lines().next().unwrap_or("unknown error")
1691                    );
1692                }
1693                notice
1694            })
1695        } else {
1696            crate::notices::run_ended(&runner.state)
1697        };
1698        if let Some(notice) = ended {
1699            crate::notices::raise(notice);
1700        }
1701        result
1702    }
1703
1704    fn repository_wait(&self) -> crate::repo_lock::WaitPolicy {
1705        repository_wait(&self.state, Some((&self.pause, &self.interrupt)))
1706    }
1707
1708    async fn coordinate(&mut self, cwd: &Path) -> Result<Option<crate::repo_lock::SeatLease>> {
1709        let wait = self.repository_wait();
1710        coordinate_operation(&mut self.state, cwd, &wait).await
1711    }
1712
1713    /// Validate ownership and persist the driver claim in one critical section.
1714    async fn claim_driver(
1715        &mut self,
1716        sync_only: Option<crate::base_sync_only::Request>,
1717    ) -> Result<DriverExecution<'_>> {
1718        let owner = match crate::pr_head::owner_lock_wait(
1719            &crate::run::home(),
1720            &self.state.id,
1721            Duration::from_secs(self.state.config.graph.timeout_resource_wait),
1722        )
1723        .await
1724        {
1725            Ok(owner) => owner,
1726            Err(error) => {
1727                let detail = format!("worktree maintenance or ownership update: {error:#}");
1728                // Admission did not own run.json: retain this resource outcome
1729                // in memory for queue settlement without overwriting a concurrent
1730                // retirement or publication transaction.
1731                self.state.resource_block = Some(crate::run::ResourceBlock {
1732                    cause: crate::run::ResourceBlockCause::Other,
1733                    node: "start".into(),
1734                    kind: "worktree maintenance".into(),
1735                    detail: detail.clone(),
1736                    at: Timestamp::now(),
1737                });
1738                return Err(crate::repo_lock::ResourceBlocked(detail).into());
1739            }
1740        };
1741        let disk = RunState::load(&self.state.id)?;
1742        crate::pr_head::ensure_owner(&disk)?;
1743        let claimed =
1744            crate::daemon::is_working_on_other(&crate::run::home(), &disk.id, Timestamp::now())?;
1745        // Only proven-live ownership refuses here. Unknown records (legacy runs
1746        // with no claim marker or process identity) fall through to the
1747        // exclusive execution lease taken just below, which is what actually
1748        // keeps a second driver out.
1749        anyhow::ensure!(
1750            disk.liveness(claimed) != crate::run::Liveness::Live,
1751            "run already has a live driver; wait for its execution to end"
1752        );
1753        if let Some(to) = &disk.released_to {
1754            bail!(
1755                "run {} cannot continue: its worktree was released to run {}",
1756                self.state.short(),
1757                crate::run::short_of(to)
1758            );
1759        }
1760        anyhow::ensure!(
1761            serde_json::to_value(&disk.base_sync_recovery)?
1762                == serde_json::to_value(&self.state.base_sync_recovery)?,
1763            "base recovery changed since this run was loaded; reload the saved run"
1764        );
1765        anyhow::ensure!(
1766            disk.sync_only_passes == self.state.sync_only_passes,
1767            "base-only synchronization changed since this run was loaded; reload the saved run"
1768        );
1769        let driver = crate::driver::DriverGuard::acquire(&crate::run::home(), &disk)?;
1770        let mut execution = DriverExecution {
1771            runner: self,
1772            driver,
1773        };
1774        // Declare after the execution guard: on any claim error this short
1775        // lock must drop before that guard reloads and releases ownership.
1776        let _owner = owner;
1777        if let Some(request) = sync_only {
1778            crate::base_sync_only::validate_run(&disk, &crate::run::home())?;
1779            anyhow::ensure!(
1780                request.run == disk.id,
1781                "sync-base-only request targets a different run"
1782            );
1783            let state = &mut execution.runner.state;
1784            let task_entry = state.next_pass_task_entry;
1785            *state = disk;
1786            state.next_pass_task_entry = task_entry;
1787            if state.pending_sync_only().is_some() {
1788                let pass_index = state.passes.len();
1789                let pass = state.sync_only_passes.last_mut().unwrap();
1790                anyhow::ensure!(
1791                    pass.request == request,
1792                    "interrupted base-only synchronization belongs to a different request"
1793                );
1794                pass.pass_index = pass_index;
1795            } else {
1796                let pass = crate::base_sync_only::Pass::new(request, state);
1797                state.sync_only_passes.push(pass);
1798            }
1799            if state.status == RunStatus::Failed {
1800                state.status = RunStatus::Blocked;
1801            }
1802        } else {
1803            anyhow::ensure!(
1804                disk.pending_sync_only().is_none(),
1805                "base-only synchronization has not succeeded; resume with --sync-base-only before verifying"
1806            );
1807            crate::repair_budget::apply(&crate::run::home(), &mut execution.runner.state, &disk)
1808                .await?;
1809        }
1810        let state = &mut execution.runner.state;
1811        // Moving again, so it is no longer parked. Set before the walk rather
1812        // than in `resume`, so every way of re-entering the graph clears it
1813        // and a card cannot claim a run is waiting to be resumed while the
1814        // agents are already working.
1815        state.parked = false;
1816        state.resource_wait = None;
1817        state.resource_block = None;
1818        // Any seat this state still lists as answering belongs to whatever
1819        // process last drove this run — this one included, if it crashed
1820        // mid-wave. Cleared and flushed immediately, before anything else
1821        // runs, so a resume can never show a seat as live when nothing is
1822        // asking it anything yet; the node that actually dispatches the next
1823        // wave repopulates it.
1824        state.clear_active();
1825        // Recorded in the same spot, and flushed together with the clear
1826        // above: this is the pid a reader checks (`RunState::liveness`) when
1827        // no daemon claim exists to answer "is a process still driving this
1828        // run" — a plain `magi run` / `magi review` typed into a terminal
1829        // claims nothing there. Always overwritten, never only-if-absent, so
1830        // a resumed run's stale pid from a previous, possibly-dead process
1831        // can never survive into this one's own report. Unlike
1832        // `clear_active`, this changes on every single `execute()` call, so
1833        // the save below is now unconditional rather than only-if-cleared.
1834        //
1835        // `driver_started_at` is recorded in the same breath, from this same
1836        // pid, so `liveness` can tell a live pid that is genuinely still us
1837        // apart from one the OS has since handed to an unrelated process —
1838        // see that field's own doc for why the pid alone is not enough.
1839        let pid = std::process::id();
1840        state.driver_pid = Some(pid);
1841        state.driver_started_at = crate::proc::process_started_at(pid);
1842        state.driver_exited = false;
1843        state.driver_claimed = Some(true);
1844        state.begin_pass();
1845        execution.driver.bind(state);
1846        state.save()?;
1847        execution.driver.record(state)?;
1848        Ok(execution)
1849    }
1850
1851    /// No conflict checkpoint proves dispatch was never reached. End that
1852    /// consumed generation so an owner can explicitly authorize a fresh one.
1853    async fn repair_base_conflict(&mut self, dispatch: bool) -> Result<()> {
1854        let result = crate::base_conflict::repair(&mut self.state, dispatch).await;
1855        if let Err(error) = &result
1856            && !error.is::<crate::repo_lock::ResourceBlocked>()
1857            && self
1858                .state
1859                .repair_grants
1860                .last()
1861                .is_some_and(|g| g.conflict.is_none())
1862        {
1863            self.state.repair_grants.last_mut().unwrap().phase =
1864                crate::repair_budget::Phase::Complete;
1865            self.state.status = RunStatus::Blocked;
1866            self.state.save()?;
1867            bail!(
1868                "{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",
1869                self.state.passes.last().map_or(0, |p| p.index)
1870            );
1871        }
1872        result
1873    }
1874
1875    /// A grant owns only these repair attempts. Confirmation reviews cannot
1876    /// create another fixer allowance, and every operation is restart-checkpointed.
1877    async fn execute_granted_repair(&mut self) -> Result<()> {
1878        use crate::repair_budget::{Kind, Phase};
1879        let index = self.state.repair_grants.len() - 1;
1880        let winner = self
1881            .state
1882            .winner()
1883            .cloned()
1884            .context("repair winner missing")?;
1885        loop {
1886            let grant = self.state.repair_grants[index].clone();
1887            match grant.phase {
1888                Phase::Pending => {
1889                    if grant.spent >= grant.receipt.request.rounds {
1890                        self.state.repair_grants[index].phase = Phase::Complete;
1891                        self.state.status = RunStatus::Blocked;
1892                        self.state.save()?;
1893                        return Ok(());
1894                    }
1895                    // Reserve before dispatch. A crash can consume an attempt,
1896                    // but can never duplicate it or reset saved fixer history.
1897                    self.state.repair_grants[index].spent += 1;
1898                    self.state.repair_grants[index].phase = Phase::Fixing;
1899                    self.state.save()?;
1900                    match grant.receipt.request.kind {
1901                        Kind::BaseConflict => self.repair_base_conflict(true).await?,
1902                        Kind::Gate => {
1903                            let failed = self.state.gate.clone();
1904                            let _ = self.gate_fix_round(&winner, &failed).await?;
1905                        }
1906                        Kind::Review => {
1907                            let mut record = self
1908                                .state
1909                                .reviews
1910                                .last()
1911                                .cloned()
1912                                .context("review failure missing")?;
1913                            let round = record.round;
1914                            let step = self.run_fix_round(&winner, &mut record).await?;
1915                            self.state.reviews[round - 1] = record;
1916                            if matches!(step, FixStep::Recorded { report_lost: true }) {
1917                                self.state.repair_grants[index].phase = Phase::Complete;
1918                                self.state.status = RunStatus::Blocked;
1919                                self.state.event("repair-grant", "fixer continuation remains unresolved; repair grant cannot bypass its stop");
1920                                self.state.save()?;
1921                                return Ok(());
1922                            }
1923                            if matches!(step, FixStep::Resource) {
1924                                self.stop_for_resource()?;
1925                                return Ok(());
1926                            }
1927                            self.state.save()?;
1928                        }
1929                    }
1930                    if self.resource_halt()? {
1931                        return Ok(());
1932                    }
1933                }
1934                Phase::Fixing => {
1935                    if grant.receipt.request.kind == Kind::BaseConflict {
1936                        self.repair_base_conflict(false).await?;
1937                    }
1938                    // Interrupted fixers may have left source changes or an
1939                    // unpushed commit. Preserve them before fresh assessment.
1940                    let _coordination = self.coordinate(&winner.worktree).await?;
1941                    let rescued = git::rescue_commit(
1942                        &winner.worktree,
1943                        "magi: preserve interrupted granted repair",
1944                    )
1945                    .await?;
1946                    self.state.note_withheld("repair-grant", &rescued.withheld);
1947                    // Fresh checks must supersede even a same-head failure.
1948                    // Archive rather than erase failure evidence or counters.
1949                    self.state
1950                        .verification_history
1951                        .push(crate::run::VerificationEvidence {
1952                            superseded_by: None,
1953                            archived_at: Some(Timestamp::now()),
1954                            fixes_spent: Some(self.state.gate_fixes.len()),
1955                            gate_head: self.state.gate_head.take(),
1956                            gate_ran: std::mem::take(&mut self.state.gate_ran),
1957                            gate: std::mem::take(&mut self.state.gate),
1958                            e2e: self.state.head_e2e.take(),
1959                        });
1960                    if let Some(e2e) = self.state.gate_repair_e2e.take() {
1961                        self.state
1962                            .verification_history
1963                            .push(crate::run::VerificationEvidence {
1964                                superseded_by: None,
1965                                archived_at: Some(Timestamp::now()),
1966                                fixes_spent: Some(self.state.gate_fixes.len()),
1967                                gate_head: None,
1968                                gate_ran: false,
1969                                gate: Vec::new(),
1970                                e2e: Some(e2e),
1971                            });
1972                    }
1973                    self.state.repair_grants[index].review_start = self.state.reviews.len();
1974                    self.state.repair_grants[index].head =
1975                        git::rev_parse(&winner.worktree, "HEAD").await?;
1976                    self.state.repair_grants[index].phase = Phase::Reviewing;
1977                    if grant.receipt.request.kind == Kind::BaseConflict {
1978                        self.state.base_sync_recovery.stop = None;
1979                        if let Some(sync) = &mut self.state.base_sync {
1980                            sync.tip = grant
1981                                .receipt
1982                                .request
1983                                .tip
1984                                .clone()
1985                                .context("repair base tip missing")?;
1986                            sync.conflict = None;
1987                            sync.behind = 0;
1988                        }
1989                        refresh_reviewed_commits(&mut self.state, &winner.branch).await;
1990                    }
1991                    self.state.save()?;
1992                }
1993                Phase::Reviewing => {
1994                    self.review_loop_pass().await?;
1995                    if self.resource_halt()? {
1996                        return Ok(());
1997                    }
1998                    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
1999                    let clean = self.state.reviews.len() > grant.review_start
2000                        && self.state.reviews.last().is_some_and(|r| {
2001                            r.head == head
2002                                && r.clean
2003                                && r.expected > 0
2004                                && r.answered == r.expected
2005                                && matches!(
2006                                    r.e2e_status(),
2007                                    E2eStatus::Passed | E2eStatus::NotConfigured
2008                                )
2009                        });
2010                    if !clean {
2011                        // A confirmation review carries no additional fix budget.
2012                        self.state.repair_grants[index].phase = if grant.receipt.request.kind
2013                            == Kind::Review
2014                            && grant.spent < grant.receipt.request.rounds
2015                            && self.state.reviews.last().is_some_and(|r| {
2016                                r.fix.is_none()
2017                                    && (r.blocking > 0 || r.e2e_status() == E2eStatus::Failed)
2018                            }) {
2019                            Phase::Pending
2020                        } else {
2021                            Phase::Complete
2022                        };
2023                        self.state.status = RunStatus::Blocked;
2024                        self.state.event(
2025                            "repair-grant",
2026                            "fresh review did not clear the repaired head; no publication",
2027                        );
2028                        self.state.save()?;
2029                        if self.state.repair_grants[index].phase == Phase::Pending {
2030                            continue;
2031                        }
2032                        return Ok(());
2033                    }
2034                    self.state.repair_grants[index].phase = Phase::Gating;
2035                    self.state.save()?;
2036                }
2037                Phase::Gating => {
2038                    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
2039                    self.state.reconcile_verification_head(&head);
2040                    let wait = self.repository_wait();
2041                    if self
2042                        .state
2043                        .reviews
2044                        .last()
2045                        .is_none_or(|r| r.head != head || !r.clean)
2046                    {
2047                        self.state.status = RunStatus::Blocked;
2048                        self.state.repair_grants[index].phase = Phase::Complete;
2049                        self.state.event(
2050                            "repair-grant",
2051                            "head changed since fresh review; repair held",
2052                        );
2053                        self.state.save()?;
2054                        return Ok(());
2055                    }
2056                    if !verify_current_head(&mut self.state, &winner, &wait).await? {
2057                        return Ok(());
2058                    }
2059                    let outcomes = self.run_gate(&winner).await?;
2060                    if verify_inconclusive(&outcomes) {
2061                        return Ok(());
2062                    }
2063                    let after = git::rev_parse(&winner.worktree, "HEAD").await?;
2064                    if after != head {
2065                        self.state.repair_grants[index].review_start = self.state.reviews.len();
2066                        self.state.repair_grants[index].head = after;
2067                        self.state.repair_grants[index].phase = Phase::Reviewing;
2068                        self.state.status = RunStatus::Blocked;
2069                        self.state.event("repair-grant", "pre-gate changed the reviewed head; resume for fresh review before publication");
2070                        self.state.save()?;
2071                        return Ok(());
2072                    }
2073                    let passed = outcomes.iter().all(CommandOutcome::ok);
2074                    // Follow-up grants owe the same guarded checkout delivery
2075                    // as the conflict repair that introduced the new head.
2076                    if passed
2077                        && !crate::foreign_checkout::write_back(&mut self.state, &head).await?
2078                    {
2079                        return Ok(());
2080                    }
2081                    self.state.repair_grants[index].succeeded = passed;
2082                    self.state.gate = outcomes;
2083                    self.state.gate_ran = true;
2084                    self.state.status = if passed {
2085                        RunStatus::Gating
2086                    } else {
2087                        RunStatus::Blocked
2088                    };
2089                    self.state.repair_grants[index].phase = if !passed
2090                        && grant.receipt.request.kind == Kind::Gate
2091                        && grant.spent < grant.receipt.request.rounds
2092                    {
2093                        Phase::Pending
2094                    } else {
2095                        Phase::Complete
2096                    };
2097                    if passed && self.state.config.merge.mode == MergeMode::Pr {
2098                        // Persist publication debt with the successful checkpoint.
2099                        self.state.pr_publication_pending = true;
2100                    } else if passed {
2101                        self.state.status = RunStatus::Ready;
2102                    }
2103                    self.state.save()?;
2104                    if !passed {
2105                        continue;
2106                    }
2107                    // Existing PR ownership and push lease stay in place. The
2108                    // normal publisher owes the new reviewed/gated SHA, and
2109                    // land's fresh owner approval remains mandatory.
2110                    if self.state.config.merge.mode != MergeMode::Pr {
2111                        self.state.status = RunStatus::Ready;
2112                        self.state.event(
2113                            "repair-grant",
2114                            "repair verified locally; grant carries no merge authorization",
2115                        );
2116                        self.state.save()?;
2117                        return Ok(());
2118                    }
2119                    return self.merge().await;
2120                }
2121                Phase::Complete => return Ok(()),
2122            }
2123        }
2124    }
2125
2126    async fn execute_graph(&mut self) -> Result<()> {
2127        // Even a terminal run may reenter through an explicit recovery action.
2128        // Restore before prep shortcuts, saved conversations or graph nodes use
2129        // a disposable path; GC may already have removed its original objects.
2130        let archive_home = crate::run::home().canonicalize()?;
2131        if crate::retention::has_archived_seats(&archive_home, &self.state)? {
2132            let repo = self.state.repo.clone();
2133            let _coordination = self.coordinate(&repo).await?;
2134            ensure_setup_config(&mut self.state, &repo).await?;
2135            crate::retention::restore_execution_seats(
2136                &archive_home,
2137                &self.state,
2138                _coordination.as_ref(),
2139            )
2140            .await?;
2141        }
2142        self.state.configure_recovery_resume()?;
2143        if self
2144            .state
2145            .repair_grants
2146            .last()
2147            .is_some_and(|g| g.phase != crate::repair_budget::Phase::Complete)
2148        {
2149            return self.execute_granted_repair().await;
2150        }
2151        if self
2152            .state
2153            .repair_grants
2154            .last()
2155            .is_some_and(|g| !g.succeeded)
2156        {
2157            self.state.status = RunStatus::Blocked;
2158            self.state.save()?;
2159            return Ok(());
2160        }
2161        // Preservation may invalidate an old empty classification. Resolve it
2162        // before any resume shortcut can reuse a verdict or publish a branch.
2163        self.persist_candidates().await?;
2164        // A saved base stop outranks stage markers, including legacy Voting.
2165        // Recovery never reenters implementation, deliberation or voting.
2166        if self.state.base_sync_blocked() {
2167            self.sync_to_base().await?;
2168            if !self.state.base_sync_blocked()
2169                && self.state.status != RunStatus::AlreadyInBase
2170                && !self.resource_halt()?
2171            {
2172                self.finish_after_tally().await?;
2173            }
2174            return Ok(());
2175        }
2176        if self
2177            .state
2178            .merge_decision
2179            .as_ref()
2180            .is_some_and(|decision| !decision.closed)
2181            && self.state.status != RunStatus::Landing
2182        {
2183            if crate::merge_decision::resumable_hold(&self.state) {
2184                self.state.merge = Some(MergeOutcome {
2185                    mode: MergeMode::Pr,
2186                    ok: false,
2187                    detail: self
2188                        .state
2189                        .merge_decision
2190                        .as_ref()
2191                        .unwrap()
2192                        .target
2193                        .pr
2194                        .clone(),
2195                    empty: false,
2196                });
2197                self.run_land().await?;
2198                self.settle_questions();
2199                return Ok(());
2200            }
2201            bail!(
2202                "owner stop decision is held; inspect the existing PR and request an explicit fresh review/decision before further work"
2203            );
2204        }
2205        if self.state.config.graph.selected_implementer.is_some()
2206            && self.state.status == RunStatus::Blocked
2207            && self.state.tally.is_none()
2208            && self.state.candidate_preservation.is_empty()
2209            && self.state.interrupted_implementations.is_empty()
2210        {
2211            bail!(
2212                "selected implementation is held; explicitly release the owning task to retry it"
2213            );
2214        }
2215
2216        if self.state.merge_repairs.last().is_some_and(|r| {
2217            matches!(
2218                r.phase,
2219                crate::run::MergeRepairPhase::Requested
2220                    | crate::run::MergeRepairPhase::Fixing
2221                    | crate::run::MergeRepairPhase::Reviewing
2222            )
2223        }) {
2224            if self.repair_merge_review().await? {
2225                self.run_land().await?;
2226            }
2227            self.settle_questions();
2228            return Ok(());
2229        }
2230        // Publication already passed review and gate. Resume only that node:
2231        // syncing to a newer base here could change the verified commit.
2232        if self.state.pr_publication_pending {
2233            self.merge().await?;
2234            if self.resource_halt()? {
2235                return Ok(());
2236            }
2237            self.state.save()?;
2238            self.settle_questions();
2239            return Ok(());
2240        }
2241        // A run that already lost its quorum never resumes into the verdict
2242        // machinery: `deliberate` and `vote` would otherwise clobber the
2243        // stalled marker back to Voting and the run would keep going past a
2244        // verdict that is no longer trustworthy. Everything already recorded is
2245        // kept, so the run stays resumable (or foldable) for a human to pick up.
2246        //
2247        // On --resume the run gets one chance to repair itself: the seats a
2248        // rate limit took out are re-asked. If their quota has since reset and
2249        // the quorum is restored, the run picks up and finishes; otherwise it
2250        // stays stale and still-resumable for a later retry. If it does not
2251        // recover, the returned status stays `Stalled` and nothing was
2252        // clobbered (the recovery only mutates entries for the lost seats).
2253        if self.state.status == RunStatus::Stalled {
2254            if self.recover_stall().await? {
2255                self.finish_after_tally().await?;
2256            } else {
2257                // Still below quorum: persist the marker and stay resumable.
2258                self.state.save()?;
2259            }
2260            return Ok(());
2261        }
2262        // A run parked inside `land` - watching CI, mid fix-round, or
2263        // waiting on the owner's merge approval - resumes directly into it,
2264        // never back through `prep`. Everything before `merge` already
2265        // concluded; that is the only way `status` reaches `Landing` in the
2266        // first place. Re-walking `review_loop` first would also be actively
2267        // wrong: its own status recomputation (see its doc) treats any
2268        // clean round as reason to set `status` to `Gating`, which would
2269        // clobber this marker before `merge` ever ran, and this run would
2270        // never find its way back into `land` at all.
2271        if self.state.status == RunStatus::Landing
2272            || crate::handover::landing_checkpoint(&self.state)
2273        {
2274            self.state.land_sync_pending = true;
2275            self.state.save()?;
2276            self.run_land().await?;
2277            // `run_land` may have settled the run right here - CI came back
2278            // green and the PR merged, say - without ever passing back
2279            // through `merge`'s own trailing call. Whatever it left `status`
2280            // as is what this has to read.
2281            self.settle_questions();
2282            return Ok(());
2283        }
2284        // A run parked at `merge` on the owner's word about a withheld PR text
2285        // resumes straight into `merge`. Re-walking the tail would sync to the
2286        // base again (possibly rebasing, possibly spending the fixer) after the
2287        // gate had passed, and then push a tree nobody reviewed or gated.
2288        if self.state.github_text.is_some()
2289            && self.state.merge.is_none()
2290            && self.state.status == RunStatus::Gating
2291        {
2292            self.merge().await?;
2293            if self.resource_halt()? {
2294                return Ok(());
2295            }
2296            self.state.save()?;
2297            return Ok(());
2298        }
2299        if let Err(e) = self.prep().await {
2300            if e.is::<crate::repo_lock::ResourceBlocked>() {
2301                return Err(e);
2302            }
2303            self.state.status = RunStatus::Blocked;
2304            self.state
2305                .prep_failure
2306                .get_or_insert_with(|| format!("{e:#}"));
2307            self.state
2308                .event("prep", format!("preparation stopped: {e:#}"));
2309            self.state.save()?;
2310            return Err(e);
2311        }
2312        if self.park_here()? {
2313            return Ok(());
2314        }
2315        self.advise().await?;
2316        if self.park_here()? {
2317            return Ok(());
2318        }
2319        self.implement().await?;
2320        if self.park_here()? {
2321            return Ok(());
2322        }
2323        // `after_implement` already saved the state and settled any open
2324        // questions when it set this; nothing later in the graph has
2325        // anything to judge.
2326        if self.state.status == RunStatus::VerifiedNoop {
2327            return Ok(());
2328        }
2329        self.judge().await?;
2330        if self.park_here()? {
2331            return Ok(());
2332        }
2333        self.deliberate().await?;
2334        if self.park_here()? {
2335            return Ok(());
2336        }
2337        self.vote().await?;
2338        if self.park_here()? {
2339            return Ok(());
2340        }
2341        self.tally()?;
2342        // A verdict that lost its quorum is not trustworthy: do not review,
2343        // gate, or merge on it. Everything already done is kept, so the run
2344        // stays resumable (or foldable); the human can replace the agent that
2345        // ran out of quota and pick it up.
2346        if self.state.status == RunStatus::Stalled {
2347            // Persist the stalled marker now — the normal end-of-execute save
2348            // below is below this early return, and without it a resumed run
2349            // would reload a pre-tally status and keep going.
2350            self.state.save()?;
2351            return Ok(());
2352        }
2353        self.finish_after_tally().await?;
2354        Ok(())
2355    }
2356
2357    /// A wave could not start its agents because a shared resource stayed busy
2358    /// (see [`RunState::resource_block`]): leave the run `Blocked` and
2359    /// resumable. Unstarted seats have no result; completed peers retain
2360    /// their saved candidate state.
2361    fn stop_for_resource(&mut self) -> Result<()> {
2362        // Resource acquisition observes cancellation inside a node. Complete
2363        // the same durable park as every other node boundary before returning.
2364        if self.pause.parked() || self.interrupt.parked() {
2365            self.park_here()?;
2366            return Ok(());
2367        }
2368        if self.state.resource_block.is_some() {
2369            self.state.status = RunStatus::Blocked;
2370        }
2371        self.state.save()
2372    }
2373
2374    /// Stop walking the graph if a node ended on a resource block.
2375    fn resource_halt(&mut self) -> Result<bool> {
2376        if self.state.resource_block.is_none() {
2377            return Ok(false);
2378        }
2379        self.stop_for_resource()?;
2380        Ok(true)
2381    }
2382
2383    /// Park here if asked to, recording it in the run's own timeline.
2384    ///
2385    /// Returns whether the caller should stop walking the graph. The state is
2386    /// saved either way by the node that just finished; this adds the event so
2387    /// the operator's card says why a run that is neither finished nor moving
2388    /// is sitting where it is.
2389    fn park_here(&mut self) -> Result<bool> {
2390        let parking = self.pause.parked() || self.interrupt.parked();
2391        if !parking && self.state.resource_block.is_some() {
2392            self.stop_for_resource()?;
2393            return Ok(true);
2394        }
2395        // Either handle asking is enough - see `Pause`'s own doc for why
2396        // they are never the same one. `interrupt` is checked second so a
2397        // reason it carries is preferred in the message below over a plain
2398        // shutdown park racing it at the same boundary.
2399        if !self.pause.parked() && !self.interrupt.parked() {
2400            return Ok(false);
2401        }
2402        if self.state.parked {
2403            return Ok(true);
2404        }
2405        let cause = self.interrupt.cause().or_else(|| self.pause.cause());
2406        if let Some(block) = &mut self.state.resource_block
2407            && matches!(
2408                block.cause,
2409                crate::run::ResourceBlockCause::Cancelled { .. }
2410            )
2411        {
2412            block.cause = crate::run::ResourceBlockCause::Cancelled {
2413                park: cause.clone(),
2414            };
2415        }
2416        let why = match cause.as_ref().map(ParkCause::label) {
2417            Some(reason) => format!(
2418                "parked after `{}` ({reason}) — resume to carry on from here",
2419                self.state.status.as_str()
2420            ),
2421            None => format!(
2422                "parked after `{}` — resume to carry on from here",
2423                self.state.status.as_str()
2424            ),
2425        };
2426        self.state.event("park", why);
2427        self.state
2428            .end_pass_parked(cause.unwrap_or(ParkCause::Unspecified));
2429        self.state.parked = true;
2430        self.state.save()?;
2431        Ok(true)
2432    }
2433
2434    /// Only a new explicit operator approval may retry failed preparation.
2435    pub fn retry_preparation(&mut self, approval_at: jiff::Timestamp) -> Result<()> {
2436        if self.state.prep_failure.is_none() {
2437            return Ok(());
2438        }
2439        let failed_at = self
2440            .state
2441            .events
2442            .iter()
2443            .rev()
2444            .find(|event| event.node == "prep")
2445            .map_or(self.state.updated_at, |event| event.at);
2446        anyhow::ensure!(
2447            approval_at > failed_at,
2448            "preparation retry requires a new explicit release after the failure"
2449        );
2450        self.state.prep_failure = None;
2451        self.state.prep_complete = Some(false);
2452        self.state
2453            .event("prep-retry", "operator approved retry of preparation");
2454        Ok(())
2455    }
2456
2457    /// Hand the runner the pause `magi serve`'s own shutdown watches.
2458    pub fn on_pause(&mut self, pause: Pause) {
2459        self.pause = pause;
2460    }
2461
2462    /// Hand the runner a second, independent pause: `magi serve`'s interrupt
2463    /// scheduler asking this one run - and no other - to park so a task
2464    /// marked [`crate::queue::Task::interrupt`] can run alone. See
2465    /// [`Pause`]'s own doc for why this is never [`Runner::on_pause`]'s
2466    /// handle.
2467    pub fn watch_interrupt(&mut self, pause: Pause) {
2468        self.interrupt = pause;
2469    }
2470
2471    /// Abandon this run's own open questions, once `status` has actually
2472    /// settled rather than merely paused.
2473    ///
2474    /// `Blocked` and `Stalled` are `RunStatus::resumable` — a human can pick
2475    /// either back up with the candidates, the review round and the seat
2476    /// sessions already on disk, so a question an implementer asked mid-round
2477    /// may still get a real answer read by a real resume. Only the statuses
2478    /// `resumable` excludes are actually final: the run merged, it reached
2479    /// `Ready` with nothing left to do, it failed outright with no
2480    /// established point to continue from, or every candidate agreed, with
2481    /// evidence, that nothing belonged in the worktree (`VerifiedNoop`). In
2482    /// every one of those the seat that asked is gone for good, exactly like
2483    /// the run being deleted under `magi run rm` - so the same cleanup
2484    /// applies, worded for what actually happened instead of "the run was
2485    /// deleted".
2486    ///
2487    /// Best-effort and silent on success: called from every place `status`
2488    /// can land on one of those three, including ones a resumed run revisits,
2489    /// so it must cost nothing when there was nothing open to begin with.
2490    fn settle_questions(&mut self) {
2491        if let Err(e) = ask::Questions::open().settle_run(&self.state.id, self.state.status) {
2492            tracing::warn!("abandon questions for {}: {e:#}", self.state.id);
2493        }
2494    }
2495
2496    /// The tail of the graph after a trustworthy tally: fold losers, review,
2497    /// gate, merge, and persist.
2498    fn finish_after_tally(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
2499        Box::pin(self.finish_after_tally_inner())
2500    }
2501
2502    async fn finish_after_tally_inner(&mut self) -> Result<()> {
2503        // Before the losers are folded: their branches are what the graft
2504        // reads from.
2505        self.graft().await?;
2506        if self.resource_halt()? {
2507            return Ok(());
2508        }
2509        self.fold_losers().await?;
2510        // Before review starts, and again right before the gate: a run's
2511        // review rounds can themselves take long enough for the base to move
2512        // a second time, and the gate is the one node whose "green" gets
2513        // acted on.
2514        self.sync_to_base().await?;
2515        if self.hold_base_sync().await? || self.resource_halt()? {
2516            return Ok(());
2517        }
2518        if self.state.status == RunStatus::AlreadyInBase {
2519            return Ok(());
2520        }
2521        self.review_loop().await?;
2522        if self.resource_halt()? {
2523            return Ok(());
2524        }
2525        self.sync_to_base().await?;
2526        if self.hold_base_sync().await? || self.resource_halt()? {
2527            return Ok(());
2528        }
2529        if self.state.status == RunStatus::AlreadyInBase {
2530            return Ok(());
2531        }
2532        self.gate().await?;
2533        self.merge().await?;
2534        if self.resource_halt()? {
2535            return Ok(());
2536        }
2537        self.state.save()?;
2538        Ok(())
2539    }
2540
2541    // ---------------------------------------------------------------- prep
2542
2543    /// Run `[worktree] setup` in a seat's fresh worktree. A failure blocks the
2544    /// run with the step and its output in the event; it is never swallowed.
2545    /// During `prep` (`in_prep`) the whole preparation is rolled back, so a
2546    /// resume starts over instead of finding candidates and missing seats.
2547    async fn setup_seat_worktree(
2548        &mut self,
2549        repo: &Path,
2550        wt: &Path,
2551        in_prep: bool,
2552        coordination: Option<&crate::repo_lock::SeatLease>,
2553    ) -> Result<()> {
2554        let result = match ensure_setup_config(&mut self.state, repo).await {
2555            Ok(()) => {
2556                worktree_setup::prepare_with(
2557                    &self.state.config,
2558                    repo,
2559                    wt,
2560                    crate::build_target::Coordination::Held(coordination),
2561                )
2562                .await
2563            }
2564            Err(e) => Err(e),
2565        };
2566        if let Err(e) = result {
2567            git::worktree_remove_clean(repo, wt).await.ok();
2568            if in_prep {
2569                self.rollback_prep(repo).await;
2570            }
2571            self.state.status = RunStatus::Blocked;
2572            self.state.event(
2573                "setup",
2574                format!("worktree setup failed in {}: {e:#}", wt.display()),
2575            );
2576            self.state.save()?;
2577            return Err(e);
2578        }
2579        Ok(())
2580    }
2581
2582    /// Undo everything `prep` created, so a resume re-runs it whole.
2583    async fn rollback_prep(&mut self, repo: &Path) {
2584        let root = self.state.worktree_root();
2585        for c in std::mem::take(&mut self.state.candidates) {
2586            if matches!(
2587                git::worktree_remove_clean(repo, &c.worktree).await,
2588                Ok(true)
2589            ) {
2590                git::branch_delete(repo, &c.branch).await.ok();
2591            } else {
2592                self.state.candidates.push(c);
2593            }
2594        }
2595        let seats = self.roles.judges.len().max(self.state.config.graph.judges);
2596        for j in 1..=seats {
2597            remove_read_seat_worktree(&mut self.state, &root.join(format!("judge-{j}")))
2598                .await
2599                .ok();
2600        }
2601        for k in 1..=self.state.config.graph.advisors {
2602            remove_read_seat_worktree(&mut self.state, &root.join(format!("advisor-{k}")))
2603                .await
2604                .ok();
2605        }
2606    }
2607
2608    async fn prep(&mut self) -> Result<()> {
2609        if let Some(reason) = &self.state.prep_failure {
2610            bail!(
2611                "candidate preparation previously failed: {reason}; correct the source before retrying"
2612            );
2613        }
2614        if self
2615            .state
2616            .prep_complete
2617            .unwrap_or(!self.state.candidates.is_empty())
2618        {
2619            return Ok(());
2620        }
2621        let repo = self.state.repo.clone();
2622        // Includes rollback, config, refs, checkout creation and setup. No
2623        // repository mutation may precede the real shared lock acquisition.
2624        let _coordination = self.coordinate(&repo).await?;
2625        let base = self.state.base_commit.clone();
2626        let plan = self.state.sources.plan(&repo, &base).await?;
2627        self.rollback_prep(&repo).await;
2628        if !self.state.candidates.is_empty() {
2629            bail!(
2630                "preparation rollback retained worktrees; recover their uncommitted work before retrying"
2631            );
2632        }
2633        self.state.prep_complete = Some(false);
2634        self.state.status = RunStatus::Prep;
2635        self.state.save()?;
2636        let repo = self.state.repo.clone();
2637        let start = plan.start.clone().unwrap_or_else(|| base.clone());
2638        let root = self.state.worktree_root();
2639        let labels = blind::assign_labels(self.roles.implementers.len(), self.state.seed);
2640
2641        // The hook is the write-time half of the blindness contract; the
2642        // presentation filter in `blind` is the half that cannot be bypassed.
2643        let hooks_dir = self.state.dir().join("hooks");
2644        if self.state.config.blind.commit_msg_hook {
2645            std::fs::create_dir_all(&hooks_dir)
2646                .with_context(|| format!("create {}", hooks_dir.display()))?;
2647            let script = blind::commit_msg_hook(&self.state.config.blind.strip_lines);
2648            let path = hooks_dir.join("commit-msg");
2649            std::fs::write(&path, script).with_context(|| format!("write {}", path.display()))?;
2650            make_executable(&path)?;
2651            // Ref-counted rather than a plain idempotent set: with more than
2652            // one run able to be in flight in the same repository at once
2653            // (see `Config::daemon.max_concurrent_runs`), a bare "already
2654            // true?" check cannot tell "another run of mine still needs
2655            // this" from "nobody does", and the run that happens to finish
2656            // first would disable the hook out from under a sibling still
2657            // relying on it.
2658            git::acquire_worktree_config(&repo).await?;
2659            self.state.enabled_worktree_config = true;
2660        }
2661
2662        // `[worktree] setup` hides its products per worktree, which needs the
2663        // same per-worktree config the hook does. Held until fold, like it.
2664        ensure_setup_config(&mut self.state, &repo).await?;
2665
2666        for (index, (spec, label)) in self
2667            .roles
2668            .implementers
2669            .clone()
2670            .into_iter()
2671            .zip(labels)
2672            .enumerate()
2673        {
2674            let branch = self.state.branch_for(label);
2675            let worktree = root.join(format!("cand-{label}"));
2676            // Persist intent before Git can leave a partially created tree.
2677            // Candidate registration follows setup, so it cannot inventory
2678            // crashes or refusals during creation itself.
2679            self.state.event(
2680                "prep-intent",
2681                serde_json::json!({
2682                    "branch": branch,
2683                    "worktree": worktree,
2684                    "start": start,
2685                    "picks": plan.picks,
2686                })
2687                .to_string(),
2688            );
2689            self.state.save()?;
2690            git::worktree_add_branch(&repo, &worktree, &branch, &start).await?;
2691            if self.state.config.blind.commit_msg_hook {
2692                git::set_worktree_hooks_path(&worktree, &hooks_dir).await?;
2693            }
2694            git::local_exclude(&worktree, "/.magi/").await?;
2695            if let Err(e) = worktree_setup::prepare_with(
2696                &self.state.config,
2697                &repo,
2698                &worktree,
2699                crate::build_target::Coordination::Held(_coordination.as_ref()),
2700            )
2701            .await
2702            {
2703                // Nothing of this prep may survive: a resume must start over,
2704                // not find half the candidates and skip the rest.
2705                git::worktree_remove_clean(&repo, &worktree).await.ok();
2706                git::branch_delete(&repo, &branch).await.ok();
2707                self.rollback_prep(&repo).await;
2708                self.state.status = RunStatus::Blocked;
2709                self.state
2710                    .event("prep", format!("worktree setup failed: {e:#}"));
2711                if !e.is::<crate::repo_lock::ResourceBlocked>() {
2712                    self.state.prep_failure = Some(format!("worktree setup failed: {e:#}"));
2713                }
2714                self.state.save()?;
2715                return Err(e);
2716            }
2717            self.state.candidates.push(Candidate {
2718                index,
2719                label,
2720                agent: spec.id.clone(),
2721                branch,
2722                worktree,
2723                summary: String::new(),
2724                stat: String::new(),
2725                files: 0,
2726                commits: 0,
2727                empty: false,
2728                failed: None,
2729                verified_noop: None,
2730                duration_ms: 0,
2731                folded: false,
2732            });
2733            self.state.save()?;
2734            for pick in &plan.picks {
2735                if let Err(e) = git::cherry_pick(&self.state.candidates[index].worktree, pick).await
2736                {
2737                    self.state.status = RunStatus::Blocked;
2738                    self.state.prep_failure = Some(format!("cannot apply referenced commit: {e}"));
2739                    self.state
2740                        .event("prep", format!("cannot apply referenced commit: {e}"));
2741                    self.state.save()?;
2742                    return Err(e);
2743                }
2744            }
2745        }
2746
2747        for j in 1..=self.roles.judges.len() {
2748            let wt = root.join(format!("judge-{j}"));
2749            if !wt.exists() {
2750                git::worktree_add_detached(&repo, &wt, &base).await?;
2751                self.setup_seat_worktree(&repo, &wt, true, _coordination.as_ref())
2752                    .await?;
2753            }
2754        }
2755
2756        // Disposable, detached checkouts for the design-deliberation stage's
2757        // advisor seats — the same shape as the judges' above, at the same
2758        // base commit, since advisors also only ever read. Sized off the
2759        // configured count directly rather than a resolved roster: unlike
2760        // `implementers`/`judges`/`reviewers`, advisor seats are resolved
2761        // lazily inside `advise` itself (see `Config::advisors`'s doc), so
2762        // `prep` has no `ResolvedRoles` field to read a count from here.
2763        if self.state.config.graph.advise {
2764            for k in 1..=self.state.config.graph.advisors {
2765                let wt = root.join(format!("advisor-{k}"));
2766                if !wt.exists() {
2767                    git::worktree_add_detached(&repo, &wt, &base).await?;
2768                    self.setup_seat_worktree(&repo, &wt, true, _coordination.as_ref())
2769                        .await?;
2770                }
2771            }
2772        }
2773
2774        // A judge cannot tell it is looking at its own patch — the seats keep
2775        // separate conversations — but a panel that shares agents with the
2776        // field is less independent than it looks, and that is worth saying out
2777        // loud once per run rather than leaving it in the config.
2778        let authors: Vec<&str> = self
2779            .roles
2780            .implementers
2781            .iter()
2782            .map(|a| a.id.as_str())
2783            .collect();
2784        let overlap: Vec<String> = self
2785            .roles
2786            .judges
2787            .iter()
2788            .enumerate()
2789            .filter(|(_, j)| authors.contains(&j.id.as_str()))
2790            .map(|(i, j)| format!("judge {} = {}", i + 1, j.id))
2791            .collect();
2792        if !overlap.is_empty() {
2793            let note = format!(
2794                "{} also authored a candidate; blind, but the panel is less \
2795                 independent than {} distinct agents would be",
2796                overlap.join(", "),
2797                self.roles.judges.len()
2798            );
2799            self.state.event("prep", note);
2800        }
2801
2802        self.state.event(
2803            "prep",
2804            format!(
2805                "{} candidates, {} judges, base {} ({})",
2806                self.state.candidates.len(),
2807                self.roles.judges.len(),
2808                &self.state.base_commit[..7.min(self.state.base_commit.len())],
2809                self.state.base_branch
2810            ),
2811        );
2812        self.state.prep_complete = Some(true);
2813        self.state.status = RunStatus::Implementing;
2814        self.state.save()?;
2815        Ok(())
2816    }
2817
2818    // -------------------------------------------------------------- advise
2819
2820    /// The design-deliberation stage: independent, read-only advisor seats
2821    /// each sketch a design before any implementer touches the repository,
2822    /// and (when at least one produced a usable proposal) a synthesis seat
2823    /// blends them into a brief `implement` carries in every candidate's
2824    /// prompt.
2825    ///
2826    /// `[graph] advise` is the on/off switch, on by default; `[graph]
2827    /// advisors` is the proposal count. Everything here is best-effort and
2828    /// non-fatal to the run: a misconfigured `[roles] advisors`, a roster
2829    /// that cannot reach quota, or a synthesis seat that produced nothing
2830    /// usable all leave `implement` exactly as it was before this stage
2831    /// existed — the task instruction alone — rather than failing the whole
2832    /// competition over an enrichment stage. Every outcome is still recorded
2833    /// as an event, so a run that got nothing from this stage says why.
2834    ///
2835    /// [`RunState::advise_attempted`] is this node's idempotency marker, the
2836    /// same role [`RunState::judge_skipped`] plays for `judge`: without it a
2837    /// resumed run whose stage failed would re-run it, and re-spend the
2838    /// agent calls, on every reentry before `implement`.
2839    ///
2840    /// Also skipped once any candidate shows implementation progress — the
2841    /// exact predicate `implement` itself uses to decide a candidate is no
2842    /// longer "todo" (see its own `todo` filter). `advise_attempted` alone
2843    /// is not enough: a run created by an older binary that predates this
2844    /// field deserializes it as `false` (`#[serde(default)]`), so resuming
2845    /// an already-`Implementing`-or-later run under this build would
2846    /// otherwise walk straight back through `prep` (a no-op once candidates
2847    /// exist) into this node and spawn every advisor seat against worktrees
2848    /// `prep` never recreated — after implementation has already started,
2849    /// which is exactly the invariant this stage exists to guarantee.
2850    async fn advise(&mut self) -> Result<()> {
2851        let implement_untouched = self
2852            .state
2853            .candidates
2854            .iter()
2855            .all(|c| c.commits == 0 && c.failed.is_none() && !c.empty);
2856        if !self.state.config.graph.advise || self.state.advise_attempted {
2857            return Ok(());
2858        }
2859        if !implement_untouched {
2860            self.state.event(
2861                "advise",
2862                "skipping the design-deliberation stage: at least one \
2863                 candidate already shows implementation progress, so this \
2864                 run is past the point the stage exists to run before"
2865                    .to_owned(),
2866            );
2867            self.state.advise_attempted = true;
2868            self.state.save()?;
2869            return Ok(());
2870        }
2871        let run_id = self.state.id.clone();
2872        let prompts = self.state.config.prompts.clone();
2873        let instruction = self.state.instruction.clone();
2874        let language = self.state.config.graph.language.clone();
2875        let root = self.state.worktree_root();
2876        let n = self.state.config.graph.advisors;
2877        let where_recorded = self.state.dir().join("run.json");
2878
2879        let seats = match self.state.config.advisors() {
2880            Ok(seats) if !seats.is_empty() => seats,
2881            Ok(_) => {
2882                self.state.event(
2883                    "advise",
2884                    format!(
2885                        "[graph] advisors is 0; skipping the design-deliberation \
2886                         stage and continuing without a synthesis brief (see {})",
2887                        where_recorded.display()
2888                    ),
2889                );
2890                self.state.advise_attempted = true;
2891                self.state.save()?;
2892                return Ok(());
2893            }
2894            Err(e) => {
2895                self.state.event(
2896                    "advise",
2897                    format!(
2898                        "could not resolve advisor seats ({e:#}); continuing \
2899                         without a design-deliberation brief (see {})",
2900                        where_recorded.display()
2901                    ),
2902                );
2903                self.state.advise_attempted = true;
2904                self.state.save()?;
2905                return Ok(());
2906            }
2907        };
2908
2909        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
2910        let artifacts = agent::artifacts_dir(&self.state.dir());
2911        let worktrees: Vec<PathBuf> = (1..=n).map(|k| root.join(format!("advisor-{k}"))).collect();
2912
2913        let mut jobs = Vec::new();
2914        for (i, spec) in seats.iter().cloned().enumerate() {
2915            let seat_key = format!("advisor-{}", i + 1);
2916            let seat = self.seat(&seat_key, &spec.id);
2917            jobs.push(SeatJob {
2918                prompt: prompt::advisor(&instruction, i + 1, seats.len(), &language),
2919                spec,
2920                seat,
2921                cwd: worktrees[i % worktrees.len()].clone(),
2922                timeout,
2923                allow_write: false,
2924                sessions: false,
2925                artifacts: artifacts.clone(),
2926                stem: seat_key,
2927                handover: None,
2928            });
2929        }
2930
2931        self.state.event(
2932            "advise",
2933            format!(
2934                "{} advisor seat(s) sketching a design in parallel",
2935                jobs.len()
2936            ),
2937        );
2938        let mut quota_losses = Vec::new();
2939        let cache = self.state.config.cache_dir();
2940        let ctx = WaveCtx {
2941            carry_seats: false,
2942            pauses: Some((&self.pause, &self.interrupt)),
2943            run: &run_id,
2944            node: "advise",
2945            prompts: &prompts,
2946            cache: cache.as_deref(),
2947            round: None,
2948        };
2949        let advisor_roster = self.state.config.advisor_roster().unwrap_or_default();
2950        let results = ask_json_wave::<Proposal>(
2951            jobs,
2952            Arc::clone(&self.sem),
2953            self.state.config.graph.retries,
2954            &advisor_roster,
2955            &ctx,
2956            &mut quota_losses,
2957            &mut self.state,
2958            &|p: &Proposal| p.validate(),
2959        )
2960        .await;
2961        if self.state.resource_block.is_some() {
2962            return self.stop_for_resource();
2963        }
2964        self.state.quota.extend(quota_losses);
2965
2966        let mut records = Vec::with_capacity(results.len());
2967        for (i, (seat, res, _attempts)) in results.into_iter().enumerate() {
2968            let agent_id = seat.agent.clone();
2969            self.state.seats.insert(seat.key.clone(), seat);
2970            match res {
2971                Ok((proposal, out)) => {
2972                    self.state
2973                        .event("advise", format!("advisor-{} proposed a design", i + 1));
2974                    records.push(advise::AdvisorRecord::proposed(
2975                        i + 1,
2976                        agent_id,
2977                        proposal,
2978                        out.duration_ms,
2979                    ));
2980                }
2981                Err(e) => {
2982                    self.state.event(
2983                        "advise",
2984                        format!("advisor-{} produced no usable proposal: {e:#}", i + 1),
2985                    );
2986                    records.push(advise::AdvisorRecord::failed(
2987                        i + 1,
2988                        agent_id,
2989                        e.to_string(),
2990                    ));
2991                }
2992            }
2993        }
2994
2995        let mut advice = advise::Advice {
2996            records,
2997            synthesis: None,
2998        };
2999        if advice.proposals().is_empty() {
3000            self.state.event(
3001                "advise",
3002                "no advisor produced a usable proposal; continuing without a \
3003                 synthesis brief"
3004                    .to_owned(),
3005            );
3006        } else {
3007            match self
3008                .synthesize_brief(
3009                    &advice,
3010                    &instruction,
3011                    &language,
3012                    &worktrees[0],
3013                    &artifacts,
3014                    &run_id,
3015                    &prompts,
3016                    cache.as_deref(),
3017                )
3018                .await
3019            {
3020                Ok(Some(text)) => {
3021                    self.state.event(
3022                        "advise",
3023                        "synthesized a design brief for the implementer".to_owned(),
3024                    );
3025                    advice.synthesis = Some(text);
3026                }
3027                Ok(None) => {
3028                    self.state.event(
3029                        "advise",
3030                        "the synthesis seat produced nothing usable; continuing \
3031                         without a design brief"
3032                            .to_owned(),
3033                    );
3034                }
3035                Err(e) => {
3036                    if e.is::<crate::repo_lock::ResourceBlocked>() {
3037                        return Err(e);
3038                    }
3039                    self.state.event(
3040                        "advise",
3041                        format!("could not synthesize a design brief: {e:#}"),
3042                    );
3043                }
3044            }
3045        }
3046        advise::apply_reflection(&mut advice);
3047
3048        self.state.advice = Some(advice);
3049        self.state.advise_attempted = true;
3050        self.state.save()?;
3051        Ok(())
3052    }
3053
3054    /// The synthesis seat: reads every advisor's proposal and blends them
3055    /// into the design brief `advise` stores on [`RunState::advice`]. Split
3056    /// out of [`Runner::advise`] only for readability — it is not called
3057    /// anywhere else.
3058    ///
3059    /// Picked the same way [`crate::talk`]'s standing conversation and
3060    /// [`crate::bump`]'s release-bump decision are: [`agent::pick`], with
3061    /// `[roles] synthesizer` checked first and [`agent::pick`]'s own default
3062    /// order (a claude seat, else the first runnable agent in roster order)
3063    /// used when that field is unset — see `[roles] synthesizer`'s own doc
3064    /// in [`crate::config`] for why a dedicated field exists here at all.
3065    #[allow(clippy::too_many_arguments)]
3066    async fn synthesize_brief(
3067        &mut self,
3068        advice: &advise::Advice,
3069        instruction: &str,
3070        language: &str,
3071        cwd: &Path,
3072        artifacts: &Path,
3073        run_id: &str,
3074        prompts: &Prompts,
3075        cache: Option<&Path>,
3076    ) -> Result<Option<String>> {
3077        let chain = agent::pick_chain(
3078            &self.state.config.agents,
3079            self.state.config.roles.synthesizer.as_ref(),
3080            &agent::installed,
3081            "synthesizer",
3082        )?;
3083        let proposals = advice.proposals();
3084        let mut prompt = prompt::with_overlay(
3085            prompt::synthesize_brief(instruction, &proposals, language),
3086            prompts.overlay("advise"),
3087        );
3088        if cache.is_some() {
3089            // This seat never writes, so it is never handed `CARGO_TARGET_DIR`
3090            // below — see `prompt::build_cache_note`'s doc for why telling a
3091            // read-only seat to build through the shared cache is exactly how
3092            // a sandbox's write refusal gets misread as a defect.
3093            prompt.push('\n');
3094            prompt.push_str(&prompt::build_cache_note("advise", false));
3095        }
3096        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
3097        // Each id is tried once, in order; a quota hit, error or unusable
3098        // answer moves to the next. The seat is single-turn (`sessions:
3099        // false`) and the prompt is the whole context, so a fallback agent
3100        // needs nothing carried over.
3101        let mut last = None;
3102        for (n, spec) in chain.iter().enumerate() {
3103            if n > 0 {
3104                self.state
3105                    .event("advise", format!("synthesis falling back to {}", spec.id));
3106            }
3107            let mut seat = self.seat("advise-synthesis", &spec.id);
3108            let wait = self.repository_wait();
3109            let outcome = wait
3110                .scope(agent::invoke(
3111                    spec,
3112                    &mut seat,
3113                    &Invocation {
3114                        coordination: self.state.config.coordination.as_ref(),
3115                        fetched_base: None,
3116                        cwd,
3117                        prompt: &prompt,
3118                        timeout,
3119                        allow_write: false,
3120                        sessions: false,
3121                        artifacts,
3122                        stem: &if n == 0 {
3123                            "advise-synthesis".to_owned()
3124                        } else {
3125                            format!("advise-synthesis-{}", spec.id)
3126                        },
3127                        run: run_id,
3128                        node: "advise",
3129                        cache_dir: None,
3130                        attachments: &[],
3131                        writable: &[],
3132                    },
3133                ))
3134                .await;
3135            if outcome.is_ok() {
3136                self.state.seats.insert(seat.key.clone(), seat);
3137            }
3138            let advance = agent::chain_advances(&outcome);
3139            last = Some(outcome);
3140            if !advance {
3141                break;
3142            }
3143        }
3144        // Exhausted: the last attempt's result is what a single failed seat
3145        // would have produced.
3146        let out = last.expect("a chain holds at least one agent")?;
3147        if !out.usable() {
3148            return Ok(None);
3149        }
3150        let text =
3151            verdict::section(&out.text, "synthesis").unwrap_or_else(|| out.text.trim().to_owned());
3152        Ok((!text.trim().is_empty()).then_some(text))
3153    }
3154
3155    // ----------------------------------------------------------- implement
3156
3157    async fn implement(&mut self) -> Result<()> {
3158        self.persist_candidates().await?;
3159        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
3160        // agent files with `magi task add` name the run that paid for it. The
3161        // prompt overlay is cloned alongside it because the waves borrow it
3162        // while `self` is mutably borrowed by the node's own bookkeeping.
3163        let run_id = self.state.id.clone();
3164        let prompts = self.state.config.prompts.clone();
3165        let todo: Vec<usize> = self
3166            .state
3167            .candidates
3168            .iter()
3169            .enumerate()
3170            .filter(|(_, c)| {
3171                (c.commits == 0 || self.state.interrupted_implementations.contains(&c.label))
3172                    && c.failed.is_none()
3173                    && !c.empty
3174            })
3175            .map(|(i, _)| i)
3176            .collect();
3177        if todo.is_empty() {
3178            return self.after_implement();
3179        }
3180        self.state.status = RunStatus::Implementing;
3181
3182        let language = self.state.config.graph.language.clone();
3183        let github_language = self.state.config.graph.github_language.clone();
3184        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
3185        let sessions = self.state.config.graph.sessions;
3186        let artifacts = agent::artifacts_dir(&self.state.dir());
3187        // The design-deliberation stage's blended brief, when `advise` found
3188        // one — carried into every implementer's prompt the same way
3189        // regardless of which candidate it is.
3190        let brief = self
3191            .state
3192            .advice
3193            .as_ref()
3194            .and_then(|a| a.synthesis.as_deref())
3195            .map(str::to_owned);
3196        let attachments = self.state.attachments.clone();
3197
3198        let mut jobs = Vec::new();
3199        for &i in &todo {
3200            let (index, label, worktree) = {
3201                let c = &self.state.candidates[i];
3202                (c.index, c.label, c.worktree.clone())
3203            };
3204            let spec = self.roles.implementers[index].clone();
3205            let seat_key = format!("impl-{label}");
3206            let seat = self.seat(&seat_key, &spec.id);
3207            let instruction = seeded_instruction(&self.state);
3208            jobs.push(SeatJob {
3209                spec,
3210                seat,
3211                prompt: prompt::implement_in(
3212                    &instruction,
3213                    &worktree.to_string_lossy(),
3214                    &language,
3215                    &github_language,
3216                    brief.as_deref(),
3217                    &attachments,
3218                ),
3219                cwd: worktree,
3220                timeout,
3221                allow_write: true,
3222                sessions,
3223                artifacts: artifacts.clone(),
3224                stem: format!("impl-{label}"),
3225                handover: None,
3226            });
3227        }
3228
3229        self.state.event(
3230            "implement",
3231            format!("{} candidates in parallel", jobs.len()),
3232        );
3233        // Kept so a seat whose CLI hung up can be asked again from the same
3234        // job: `wave` consumes what it is given. Mutable so `resume_seat_handovers`
3235        // can update a seat's own entry once a fallback agent takes it over —
3236        // `resume_unconfirmed_commands`, which reads `sent` afterward, must see
3237        // whichever agent actually answered, not the one that quota'd out.
3238        let mut sent = jobs.clone();
3239        let cache = self.state.config.cache_dir();
3240        let ctx = WaveCtx {
3241            carry_seats: false,
3242            pauses: Some((&self.pause, &self.interrupt)),
3243            run: &run_id,
3244            node: "implement",
3245            prompts: &prompts,
3246            cache: cache.as_deref(),
3247            round: None,
3248        };
3249        let mut results = wave(jobs, Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
3250        if !wave_blocked(&results) {
3251            self.resume_undelivered(&mut results, &sent, &prompts, &run_id)
3252                .await;
3253            self.resume_seat_handovers(&mut results, &mut sent, &prompts, &run_id)
3254                .await?;
3255            self.resume_unconfirmed_commands(&mut results, &sent, &prompts, &run_id)
3256                .await;
3257        }
3258        // Do not finalize failed candidates when the entire wave needs machine
3259        // recovery: leaving them pending resumes this node with its work intact.
3260        if !results.is_empty()
3261            && results
3262                .iter()
3263                .all(|(_, _, out)| matches!(out, AgentOutcome::Quota(_)))
3264        {
3265            let losses: Vec<_> = results
3266                .iter()
3267                .map(|(_, seat, out)| {
3268                    let AgentOutcome::Quota(o) = out else {
3269                        unreachable!()
3270                    };
3271                    QuotaLoss::from_report(seat.key.clone(), "implement", o.quota.as_ref())
3272                })
3273                .collect();
3274            self.state.quota.extend(losses.clone());
3275            for (_, seat, _) in results {
3276                self.state.seats.insert(seat.key.clone(), seat);
3277            }
3278            for &i in &todo {
3279                let label = self.state.candidates[i].label;
3280                self.state.interrupted_implementations.insert(label);
3281                self.state
3282                    .candidate_preservation
3283                    .insert(label, "machine outage awaiting persistence".into());
3284            }
3285            // Preserve partial edits too, while keeping every interrupted seat
3286            // pending even when its tree already contains an inherited patch.
3287            block_machine_outage(&mut self.state, "implement", &losses);
3288            self.state.save()?;
3289            self.persist_candidates().await?;
3290            for &i in &todo {
3291                self.state
3292                    .interrupted_implementations
3293                    .insert(self.state.candidates[i].label);
3294            }
3295            return self.stop_for_resource();
3296        }
3297        let resource_blocked = self.state.resource_block.is_some() || wave_blocked(&results);
3298
3299        let selected_failed = self.state.config.graph.selected_implementer.is_some()
3300            && results
3301                .iter()
3302                .any(|(_, _, out)| FailClass::of(out).is_some());
3303        for (&i, (_wi, seat, out)) in todo.iter().zip(results) {
3304            if matches!(out, AgentOutcome::ResourceBlocked(_)) {
3305                // Executed turns interrupted by disk pressure already carry
3306                // a preservation barrier from wave. Admission-only waits do
3307                // not. Keep the interrupted seat's session for recovery too.
3308                if self
3309                    .state
3310                    .candidate_preservation
3311                    .contains_key(&self.state.candidates[i].label)
3312                {
3313                    self.state.seats.insert(seat.key.clone(), seat);
3314                }
3315                continue;
3316            }
3317            let seat_key = seat.key.clone();
3318            // A quota fallback (`resume_seat_handovers`) may have handed this
3319            // seat to a different agent than the one `prep` recorded on the
3320            // candidate; the stats tables and any later fixer-defaults-to-
3321            // winner's-author lookup must credit whoever actually answered —
3322            // unless every fallback also quota'd out, in which case nobody
3323            // actually answered and crediting the last agent tried would
3324            // erase every earlier agent's own quota loss from the stats
3325            // tables instead of just this one seat's.
3326            let agent = seat.agent.clone();
3327            let exhausted_the_fallback_chain = FailClass::of(&out).is_some();
3328            self.state.seats.insert(seat.key.clone(), seat);
3329            let label = self.state.candidates[i].label;
3330            self.state.interrupted_implementations.remove(&label);
3331
3332            let (summary, duration, failed, verified_claim) = match out {
3333                AgentOutcome::Ok(o) => {
3334                    let text = verdict::section(&o.text, "summary").unwrap_or(o.text.clone());
3335                    let failed = (!o.usable()).then(|| {
3336                        if o.timed_out {
3337                            "agent timed out".to_owned()
3338                        } else {
3339                            format!(
3340                                "agent exited with {}",
3341                                crate::notices::exit_status(o.exit_code)
3342                            )
3343                        }
3344                    });
3345                    let verified_claim = verified_noop_claim(failed.is_none(), &o.commands, &text);
3346                    (text, o.duration_ms, failed, verified_claim)
3347                }
3348                // Left un-resumed by `resume_undelivered` (a dirty tree
3349                // already rescues the work, or there was no session left to
3350                // resume into) — reported like the ordinary failure it is,
3351                // never as if `o.text` (the CLI's raw error JSON) were an
3352                // answer.
3353                AgentOutcome::Dropped(o) => {
3354                    let why = o
3355                        .dropped
3356                        .as_ref()
3357                        .map(|d| d.why.as_str())
3358                        .unwrap_or("the CLI ended the stream without delivering its answer");
3359                    (
3360                        String::new(),
3361                        o.duration_ms,
3362                        Some(format!("the CLI dropped the stream ({why})")),
3363                        None,
3364                    )
3365                }
3366                AgentOutcome::Quota(o) => {
3367                    self.state.quota.push(QuotaLoss::from_report(
3368                        seat_key,
3369                        "implement",
3370                        o.quota.as_ref(),
3371                    ));
3372                    (
3373                        String::new(),
3374                        o.duration_ms,
3375                        Some("rate limited (quota); produced no change".to_owned()),
3376                        None,
3377                    )
3378                }
3379                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
3380                    (String::new(), 0, Some(e), None)
3381                }
3382            };
3383
3384            // Save every completed turn before any fallible Git operation. A failed
3385            // rescue must not erase the reply or prevent collection of other seats.
3386            let c = &mut self.state.candidates[i];
3387            if !exhausted_the_fallback_chain {
3388                c.agent = agent;
3389            }
3390            c.summary = blind::sanitize_prose(&summary, &self.state.config.blind);
3391            c.duration_ms = duration;
3392            c.failed = failed;
3393            c.verified_noop = verified_claim;
3394            self.state
3395                .candidate_preservation
3396                .insert(label, "awaiting persistence".to_owned());
3397        }
3398        self.state.save()?;
3399        self.persist_candidates().await?;
3400
3401        if resource_blocked {
3402            return self.stop_for_resource();
3403        }
3404        if selected_failed {
3405            self.state.status = RunStatus::Blocked;
3406            self.state.event("implement", "selected implementer failed or hit quota; holding without fallback, review or publication");
3407            self.state.save()?;
3408            bail!(
3409                "selected implementer unavailable or quota-limited; restore availability and explicitly release the task"
3410            );
3411        }
3412        self.after_implement()
3413    }
3414
3415    /// Retry only persistence after a completed implementation turn.
3416    async fn persist_candidates(&mut self) -> Result<()> {
3417        let labels: Vec<_> = self.state.candidate_preservation.keys().copied().collect();
3418        for label in labels {
3419            let i = self
3420                .state
3421                .candidates
3422                .iter()
3423                .position(|c| c.label == label)
3424                .context("pending candidate is missing")?;
3425            let c = self.state.candidates[i].clone();
3426            let interrupted = self.state.interrupted_implementations.contains(&label);
3427            let result = async {
3428                let wait = crate::repo_lock::WaitPolicy::new(
3429                    Duration::from_secs(self.state.config.graph.timeout_resource_wait),
3430                    || false,
3431                );
3432                let _coordination =
3433                    coordinate_operation(&mut self.state, &c.worktree, &wait).await?;
3434                // Best effort evidence requires no index writes. A successful snapshot
3435                // never authorizes removal of a tree whose rescue failed.
3436                if let Err(e) = git::snapshot_uncommitted(
3437                    &c.worktree,
3438                    &self
3439                        .state
3440                        .dir()
3441                        .join("artifacts")
3442                        .join(format!("candidate-{label}-recovery")),
3443                )
3444                .await
3445                {
3446                    self.state.event(
3447                        "preserve",
3448                        format!("candidate {label} snapshot incomplete: {e:#}"),
3449                    );
3450                }
3451                let rescued = git::rescue_commit(
3452                    &c.worktree,
3453                    &format!("magi: candidate {label} (uncommitted work)"),
3454                )
3455                .await?;
3456                self.state.note_withheld("implement", &rescued.withheld);
3457                let base = &self.state.base_commit;
3458                let commits = git::commits_ahead(&c.worktree, base, "HEAD").await?;
3459                let patch = git::diff(&c.worktree, base, "HEAD").await?;
3460                let stat = git::diff_stat(&c.worktree, base, "HEAD").await?;
3461                let files = git::changed_files(&c.worktree, base, "HEAD").await?.len();
3462                write_artifact(&self.state, &format!("cand-{label}.patch"), &patch)?;
3463                if c.empty && commits > 0 && !patch.trim().is_empty()
3464                    && (self.state.judge_skipped || !self.state.judgements.is_empty()
3465                        || !self.state.deliberation.is_empty() || !self.state.votes.is_empty()
3466                        || self.state.tally.is_some())
3467                {
3468                    // Keep the old classification and pending marker so every
3469                    // retry stops too. Retain decisions as recovery evidence;
3470                    // only a supported recovery operation may replace them.
3471                    bail!("candidate {label} changes the judged candidate set; supported recovery and fresh judging are required before continuing");
3472                }
3473                let c = &mut self.state.candidates[i];
3474                c.commits = commits;
3475                c.stat = stat;
3476                c.files = files;
3477                let no_changes = commits == 0 || patch.trim().is_empty();
3478                c.empty = no_changes && !interrupted;
3479                if interrupted && no_changes {
3480                    c.failed = None;
3481                    c.verified_noop = None;
3482                }
3483                if !c.empty {
3484                    c.failed = None;
3485                    c.verified_noop = None;
3486                }
3487                self.state.event(
3488                    "preserve",
3489                    format!("candidate {label}: {files} files, {commits} commits"),
3490                );
3491                Ok::<_, anyhow::Error>(())
3492            }
3493            .await;
3494            match result {
3495                Ok(()) => {
3496                    self.state.candidate_preservation.remove(&label);
3497                    if !interrupted || self.state.candidates[i].files > 0 {
3498                        self.state.interrupted_implementations.remove(&label);
3499                    }
3500                }
3501                Err(e) => {
3502                    let reason = format!("candidate {label} preservation failed: {e:#}");
3503                    self.state.event("preserve", &reason);
3504                    self.state.candidate_preservation.insert(label, reason);
3505                }
3506            }
3507            if self.state.candidate_preservation.is_empty()
3508                && self.state.status == RunStatus::Blocked
3509                && self.state.candidates.iter().all(|c| c.failed.is_none())
3510            {
3511                // Persist the recovered phase with the cleared pending marker;
3512                // a crash between saves must not turn this into a selected-seat
3513                // failure hold on the next resume.
3514                self.state.status = RunStatus::Implementing;
3515                self.state.event(
3516                    "preserve",
3517                    "candidate persistence recovered; implementation can continue",
3518                );
3519            }
3520            self.state.save()?;
3521        }
3522        if !self.state.candidate_preservation.is_empty() {
3523            self.state.status = RunStatus::Blocked;
3524            self.state.save()?;
3525            bail!(
3526                "candidate preservation incomplete; retain worktrees and artifacts, repair persistence and resume this run"
3527            );
3528        }
3529        Ok(())
3530    }
3531
3532    /// Ask again, once, for work a CLI did and then failed to hand over.
3533    ///
3534    /// [`agent::dropped_stream`] recognises the one shape observed: an error
3535    /// status with an empty response and a usage report showing output tokens,
3536    /// i.e. **billed work with nothing delivered**. Run 26c7's candidate B was
3537    /// seven minutes and 14,267 output tokens that arrived as an empty
3538    /// candidate, because `agy`'s own subscriber fell behind and hung up.
3539    ///
3540    /// Two conditions, and both matter:
3541    ///
3542    /// - **Only when the tree is untouched.** Often the agent has already
3543    ///   written its files and only the closing message was lost; the rescue
3544    ///   commit below picks that up and there is nothing to ask for. Re-asking
3545    ///   then would pay for a second implementation of work already on disk.
3546    /// - **Once.** A CLI that drops one stream can drop the next, and this
3547    ///   node is the most expensive in the graph.
3548    ///
3549    /// The re-ask is a resume, not a re-run: `has_context` is true because the
3550    /// dropped reply still carried its `conversation_id`, so the seat is asked
3551    /// to finish what it was doing rather than sent the whole task again. It
3552    /// therefore gets a nudge's budget ([`retry_budget`]) - a quarter of the
3553    /// node's - for the same reason a re-ranked judge does: restating finished
3554    /// work is not the work.
3555    ///
3556    /// Unlike a quota this is worth retrying at all: a rate limit fails the
3557    /// same way until it resets, while an abandoned conversation is still
3558    /// there to be picked up.
3559    async fn resume_undelivered(
3560        &mut self,
3561        results: &mut [(usize, SeatState, AgentOutcome)],
3562        sent: &[SeatJob],
3563        prompts: &Prompts,
3564        run_id: &str,
3565    ) {
3566        for (wi, seat, out) in results.iter_mut() {
3567            let Some(dropped) = (match &*out {
3568                AgentOutcome::Dropped(o) => o.dropped.clone(),
3569                _ => None,
3570            }) else {
3571                continue;
3572            };
3573            let Some(job) = sent.get(*wi) else { continue };
3574            // Already on disk? Then only the closing message was lost.
3575            if !git::is_clean(&job.cwd).await.unwrap_or(true) {
3576                self.state.event(
3577                    "implement",
3578                    format!(
3579                        "{}: the CLI dropped the stream after {} output tokens ({}), but the \
3580                         work is in the tree",
3581                        seat.key, dropped.output_tokens, dropped.why
3582                    ),
3583                );
3584                continue;
3585            }
3586            // The re-ask only makes sense as a resume: `resume_after_drop`
3587            // says nothing about the task, trusting the seat to still hold it.
3588            // Without a session to resume — sessions disabled, or this CLI's
3589            // drop shape happened not to carry a session id — that prompt
3590            // would open a brand-new conversation with no context at all,
3591            // which is worse than leaving this as the ordinary failure it
3592            // already is.
3593            if !has_context(&job.spec, seat, job.sessions) {
3594                self.state.event(
3595                    "implement",
3596                    format!(
3597                        "{}: the CLI dropped the stream after {} output tokens ({}), but there \
3598                         is no session left to resume",
3599                        seat.key, dropped.output_tokens, dropped.why
3600                    ),
3601                );
3602                continue;
3603            }
3604            self.state.event(
3605                "implement",
3606                format!(
3607                    "{}: the CLI dropped the stream after {} output tokens ({}); resuming the \
3608                     conversation",
3609                    seat.key, dropped.output_tokens, dropped.why
3610                ),
3611            );
3612            let mut retry = job.clone();
3613            retry.seat = seat.clone();
3614            retry.prompt = prompt::resume_after_drop(&dropped.why);
3615            retry.timeout = retry_budget(job.timeout, true);
3616            retry.stem = format!("{}-resume", job.stem);
3617            let cache = self.state.config.cache_dir();
3618            let ctx = WaveCtx {
3619                carry_seats: false,
3620                pauses: Some((&self.pause, &self.interrupt)),
3621                run: run_id,
3622                node: "implement",
3623                prompts,
3624                cache: cache.as_deref(),
3625                round: None,
3626            };
3627            let (resumed_seat, resumed) =
3628                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
3629            *seat = resumed_seat;
3630            *out = resumed;
3631        }
3632    }
3633
3634    /// Fall an implement seat through to the next untried agent in the
3635    /// implementer roster when it lost to quota — or, since the handover was
3636    /// generalised, to a timeout or an ordinary failure (see [`FailClass`] and
3637    /// [`should_hand_over`] for when a non-quota failure stops the chain), the
3638    /// quota path itself being unchanged — instead of leaving the
3639    /// seat's loss final the moment one agent's account runs dry.
3640    ///
3641    /// Solo runs (`graph.implementers = 1`, `daemon::apply_solo`'s forced shape)
3642    /// are the motivating case: `Config::resolve_roles`'s `implementers`
3643    /// truncates to the single slot rotation picked, so a solo task whose one
3644    /// implementer hits quota mid-run used to have nothing else to try. This
3645    /// walks [`ResolvedRoles::implementer_roster`] instead — the untruncated,
3646    /// unrotated roster — which is the only place the *other* candidates in
3647    /// the machine's roster still exist once `implementers` has been cut down
3648    /// to size.
3649    ///
3650    /// Walks forward from just past the seat's own original position in the
3651    /// roster, never wrapping back to the front: a later candidate slot (say
3652    /// `beta`, the roster's second entry) must fall through to the *next*
3653    /// entry (`gamma`) on its own quota loss, not back to `alpha`, which is
3654    /// almost certainly a different candidate's own agent already — and once
3655    /// the roster's tail is exhausted there is nothing left to fall through
3656    /// to for *this* seat, wrapping or not. Tried by `spec.id`, never the
3657    /// whole [`AgentSpec`]: a roster with the same id named twice must not
3658    /// let this retry that id forever. The loop keeps falling through until
3659    /// an attempt lands something other than `Quota` or the roster's tail
3660    /// runs out of untried ids, at which point the seat is left exactly as
3661    /// `implement`'s own `AgentOutcome::Quota` arm already handles it: one
3662    /// `QuotaLoss` recorded, the candidate failed/empty.
3663    ///
3664    /// `sent` is taken mutably and updated with the fallback agent's spec:
3665    /// `resume_unconfirmed_commands`, which runs after this and also reads
3666    /// `sent`, must see whichever agent actually ended up answering the seat
3667    /// — reading the stale, original spec there would check session
3668    /// eligibility against the wrong CLI and could hand a fallback agent's
3669    /// session id to the agent that just lost the seat to quota.
3670    ///
3671    /// Every fallback gets a fresh [`SeatState`], never the quota'd seat's own
3672    /// — `self.seat` only reuses state when the agent id is unchanged, so
3673    /// handing it a different id already gets this for free. Reusing the old
3674    /// seat would resume a different CLI's session as if it were a
3675    /// continuation of this one.
3676    ///
3677    /// Unlike [`Runner::resume_undelivered`], not gated on a clean worktree:
3678    /// a quota loss cuts an agent off mid-turn, so anything already in the
3679    /// tree is unfinished work, not a completed candidate a re-ask would pay
3680    /// for twice. A dirty tree is rescued into a commit first (the same
3681    /// neutral-identity rescue `implement`'s own outcome loop gives every
3682    /// candidate) so the next agent starts clean.
3683    ///
3684    /// The new agent gets the implementer's full prompt and full
3685    /// `timeout_implement` budget, not `resume_after_drop`'s nudge-sized one:
3686    /// it has no session and no context, and is implementing the task from
3687    /// nothing, unlike a resumed drop which is only restating work already
3688    /// done.
3689    ///
3690    /// Every intermediate `Quota` this loop absorbs is folded into a plain
3691    /// `implement` event, never into `self.state.quota` — that is what
3692    /// `daemon.rs`'s own backoff reads to decide a run's task attempt should
3693    /// go unspent, and a seat that ultimately recovered on its second or
3694    /// third agent is not the stalled panel that check exists to catch. Only
3695    /// the final, unrecovered `Quota` (once the roster runs out) ever reaches
3696    /// `self.state.quota`, via the ordinary `AgentOutcome::Quota` arm the
3697    /// outcome loop already has — this helper never pushes to it itself.
3698    async fn resume_seat_handovers(
3699        &mut self,
3700        results: &mut [(usize, SeatState, AgentOutcome)],
3701        sent: &mut [SeatJob],
3702        prompts: &Prompts,
3703        run_id: &str,
3704    ) -> Result<()> {
3705        let instruction = seeded_instruction(&self.state);
3706        let language = self.state.config.graph.language.clone();
3707        let github_language = self.state.config.graph.github_language.clone();
3708        let brief = self
3709            .state
3710            .advice
3711            .as_ref()
3712            .and_then(|a| a.synthesis.as_deref())
3713            .map(str::to_owned);
3714        let attachments = self.state.attachments.clone();
3715        for (wi, seat, out) in results.iter_mut() {
3716            // Who holds the other candidate seats of this wave right now
3717            // (earlier handovers already written back to `sent`).
3718            let others: BTreeSet<String> = sent
3719                .iter()
3720                .enumerate()
3721                .filter(|(j, _)| j != wi)
3722                .map(|(_, j)| j.spec.id.clone())
3723                .collect();
3724            let Some(job) = sent.get_mut(*wi) else {
3725                continue;
3726            };
3727            // Where the seat's own original agent sits in the roster — the
3728            // fallback walk starts just past here, never at the front, so a
3729            // later candidate slot's quota loss does not fall back onto an
3730            // earlier slot's own agent.
3731            let start = self
3732                .roles
3733                .implementer_roster
3734                .iter()
3735                .position(|s| s.id == job.spec.id)
3736                .unwrap_or(0);
3737            let mut tried: BTreeSet<String> = BTreeSet::from([job.spec.id.clone()]);
3738            let mut fallback_attempt = 0usize;
3739            let mut prev: Option<FailClass> = None;
3740            while let Some(cur) = FailClass::of(&*out) {
3741                if !should_hand_over(prev.as_ref(), &cur) {
3742                    break;
3743                }
3744                let Some(next) =
3745                    pick_successor(&self.roles.implementer_roster, start, &tried, None, &others)
3746                        .cloned()
3747                else {
3748                    break;
3749                };
3750                tried.insert(next.id.clone());
3751                fallback_attempt += 1;
3752
3753                let coordination = self.coordinate(&job.cwd).await?;
3754                if let Ok(r) = git::rescue_commit(
3755                    &job.cwd,
3756                    &format!(
3757                        "magi: candidate {} (uncommitted work before {} fallback)",
3758                        seat.key,
3759                        if cur == FailClass::Quota {
3760                            "quota"
3761                        } else {
3762                            "handover"
3763                        }
3764                    ),
3765                )
3766                .await
3767                {
3768                    self.state.note_withheld("implement", &r.withheld);
3769                }
3770                drop(coordination);
3771
3772                record_handover(
3773                    &mut self.state,
3774                    "implement",
3775                    &seat.key,
3776                    &seat.agent,
3777                    &next.id,
3778                    &cur,
3779                    &fail_reason(&*out),
3780                );
3781                prev = Some(cur.clone());
3782
3783                let new_seat = handover_seat(&seat.key, &next.id, self.state.next_seat_seed());
3784                self.state.seats.insert(seat.key.clone(), new_seat.clone());
3785                // Kept in sync on `sent` itself, not just the local retry: a
3786                // later helper (`resume_unconfirmed_commands`) reads `sent`
3787                // after this one returns and must see whichever agent is now
3788                // occupying the seat, not the one that just quota'd out —
3789                // otherwise it would judge session/continuation eligibility
3790                // by the wrong CLI and could resend a fallback's session id
3791                // to the agent that lost it the seat in the first place.
3792                job.spec = next.clone();
3793                let mut retry = job.clone();
3794                retry.seat = new_seat;
3795                retry.prompt = prompt::implement_in(
3796                    &instruction,
3797                    &job.cwd.to_string_lossy(),
3798                    &language,
3799                    &github_language,
3800                    brief.as_deref(),
3801                    &attachments,
3802                );
3803                retry.stem = format!("{}-{}-{}", job.stem, cur.stem_word(), next.id);
3804                let cache = self.state.config.cache_dir();
3805                let ctx = WaveCtx {
3806                    carry_seats: false,
3807                    pauses: Some((&self.pause, &self.interrupt)),
3808                    run: run_id,
3809                    node: "implement",
3810                    prompts,
3811                    cache: cache.as_deref(),
3812                    round: None,
3813                };
3814                let (fallback_seat, fallback_out) = run_one(
3815                    retry,
3816                    Arc::clone(&self.sem),
3817                    &ctx,
3818                    &mut self.state,
3819                    fallback_attempt,
3820                )
3821                .await;
3822                *seat = fallback_seat;
3823                *out = fallback_out;
3824            }
3825        }
3826        Ok(())
3827    }
3828
3829    /// Ask an implement seat's own CLI to confirm what it started, once, when
3830    /// its reply reported a command whose completion status it never
3831    /// confirmed — see [`has_unconfirmed_command`]'s own doc for exactly what
3832    /// that does and does not mean.
3833    ///
3834    /// The completion contract this task asks for, extended to `implement`
3835    /// with the same signal `continue_fix_report` reads for the fixer,
3836    /// rather than a keyword search over the reply or a hard requirement on
3837    /// `## SUMMARY`'s presence — the shape behind fb35, 9566 and e185, where
3838    /// a candidate's CLI turn ended cleanly while a test run it had started
3839    /// had not. A short, ordinary reply with no `## SUMMARY` and no commands
3840    /// named in it at all is untouched by this: `commands` is empty, so
3841    /// there is nothing to be unconfirmed.
3842    ///
3843    /// Unlike `resume_undelivered`, not gated on the tree being untouched:
3844    /// this is not about recovering edits that might already be on disk, it
3845    /// is about a result the seat itself never vouched for, which resuming
3846    /// asks for regardless of what the tree already holds. Bounded to one
3847    /// attempt for the same reason `resume_undelivered` is — this is the
3848    /// most expensive node in the graph — and a seat that still cannot
3849    /// confirm on that attempt is left as whatever its (possibly still
3850    /// unconfirmed) reply says; this does not invent a new "failed" reason
3851    /// for a candidate that otherwise produced a real, committed change.
3852    async fn resume_unconfirmed_commands(
3853        &mut self,
3854        results: &mut [(usize, SeatState, AgentOutcome)],
3855        sent: &[SeatJob],
3856        prompts: &Prompts,
3857        run_id: &str,
3858    ) {
3859        for (wi, seat, out) in results.iter_mut() {
3860            let AgentOutcome::Ok(o) = &*out else {
3861                continue;
3862            };
3863            if !has_unconfirmed_command(&o.commands) {
3864                continue;
3865            }
3866            let Some(job) = sent.get(*wi) else { continue };
3867            if !has_context(&job.spec, seat, job.sessions) {
3868                self.state.event(
3869                    "implement",
3870                    format!(
3871                        "{}: the reply named a command whose own CLI never confirmed the exit \
3872                         status of, but there is no session left to resume",
3873                        seat.key
3874                    ),
3875                );
3876                continue;
3877            }
3878            self.state.event(
3879                "implement",
3880                format!(
3881                    "{}: the reply named a command whose own CLI never confirmed the exit \
3882                     status of; resuming the conversation",
3883                    seat.key
3884                ),
3885            );
3886            let mut retry = job.clone();
3887            retry.seat = seat.clone();
3888            retry.prompt = prompt::resume_incomplete(
3889                "a command in your last reply had no confirmed exit status",
3890            );
3891            retry.timeout = retry_budget(job.timeout, true);
3892            retry.stem = format!("{}-confirm", job.stem);
3893            let cache = self.state.config.cache_dir();
3894            let ctx = WaveCtx {
3895                carry_seats: false,
3896                pauses: Some((&self.pause, &self.interrupt)),
3897                run: run_id,
3898                node: "implement",
3899                prompts,
3900                cache: cache.as_deref(),
3901                round: None,
3902            };
3903            let (resumed_seat, resumed) =
3904                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
3905            *seat = resumed_seat;
3906            *out = resumed;
3907        }
3908    }
3909
3910    /// Ask the fixer's own seat again, up to [`MAX_FIX_CONTINUATIONS`] times,
3911    /// when its CLI turn ended cleanly (`AgentOutcome::Ok`) but the reply held
3912    /// no [`FixReport`] — see [`MAX_FIX_CONTINUATIONS`]'s own doc for the run
3913    /// that motivated this.
3914    ///
3915    /// Not the same gap as an unparsable *shape*, which [`ask_json_wave`]'s
3916    /// own nudge loop already covers for judge/review/vote seats, and not a
3917    /// dropped stream, which [`Runner::resume_undelivered`] covers for
3918    /// implement seats: here the CLI turn genuinely finished while the node's
3919    /// own work — the fixer's account of what it did — had not. Gated purely
3920    /// on `extract_json::<FixReport>` having failed on an otherwise-usable
3921    /// reply, never on any wording in it, so a fixer whose valid, first-try
3922    /// `FixReport` happens to mention having waited on a background test is
3923    /// never resumed — the `Ok(report)` branch at the call site returns
3924    /// before this is ever invoked.
3925    ///
3926    /// Same discipline as `resume_undelivered`: a nudge-sized timeout per
3927    /// attempt ([`retry_budget`]), nothing attempted once the session is
3928    /// gone, and a quota hit ends the loop immediately rather than retrying a
3929    /// rate limit that fails the same way again.
3930    async fn continue_fix_report(
3931        &mut self,
3932        mut seat: SeatState,
3933        parse_err: String,
3934        job: &SeatJob,
3935        prompts: &Prompts,
3936        run_id: &str,
3937        round: usize,
3938    ) -> (
3939        SeatState,
3940        Option<FixReport>,
3941        Option<String>,
3942        ContinuationRecord,
3943    ) {
3944        let mut last_err = parse_err;
3945        let mut cumulative_wait_ms = 0u64;
3946        let mut attempts = 0usize;
3947        loop {
3948            if !has_context(&job.spec, &seat, job.sessions) {
3949                self.state.event(
3950                    "fix",
3951                    format!(
3952                        "round {round}: fixer's reply had no adoption report ({last_err}); no \
3953                         session left to resume into"
3954                    ),
3955                );
3956                let outcome = if attempts == 0 {
3957                    ContinuationOutcome::NoSession
3958                } else {
3959                    ContinuationOutcome::Exhausted
3960                };
3961                return (
3962                    seat,
3963                    None,
3964                    Some(format!("unparsable fix report: {last_err}")),
3965                    ContinuationRecord {
3966                        attempts,
3967                        cumulative_wait_ms,
3968                        outcome,
3969                    },
3970                );
3971            }
3972            if attempts >= MAX_FIX_CONTINUATIONS {
3973                self.state.event(
3974                    "fix",
3975                    format!(
3976                        "round {round}: fixer's reply still had no adoption report after \
3977                         {attempts} continuation(s) ({last_err}); giving up"
3978                    ),
3979                );
3980                return (
3981                    seat,
3982                    None,
3983                    Some(format!(
3984                        "unparsable fix report after {attempts} continuation(s): {last_err}"
3985                    )),
3986                    ContinuationRecord {
3987                        attempts,
3988                        cumulative_wait_ms,
3989                        outcome: ContinuationOutcome::Exhausted,
3990                    },
3991                );
3992            }
3993            attempts += 1;
3994            self.state.event(
3995                "fix",
3996                format!(
3997                    "round {round}: fixer's reply had no adoption report ({last_err}); resuming \
3998                     the conversation (attempt {attempts}/{MAX_FIX_CONTINUATIONS})"
3999                ),
4000            );
4001            let mut retry = job.clone();
4002            retry.seat = seat.clone();
4003            retry.prompt = prompt::resume_incomplete(&last_err);
4004            retry.timeout = retry_budget(job.timeout, true);
4005            retry.stem = format!("{}-continue{attempts}", job.stem);
4006            let cache = self.state.config.cache_dir();
4007            let ctx = WaveCtx {
4008                carry_seats: false,
4009                pauses: Some((&self.pause, &self.interrupt)),
4010                run: run_id,
4011                node: "fix",
4012                prompts,
4013                cache: cache.as_deref(),
4014                round: Some(round),
4015            };
4016            let (resumed_seat, resumed_out) = run_one(
4017                retry,
4018                Arc::clone(&self.sem),
4019                &ctx,
4020                &mut self.state,
4021                attempts,
4022            )
4023            .await;
4024            seat = resumed_seat;
4025            match resumed_out {
4026                AgentOutcome::Ok(o) => {
4027                    cumulative_wait_ms += o.duration_ms;
4028                    match verdict::extract_json::<FixReport>(&o.text) {
4029                        Ok(report) if !has_unconfirmed_command(&o.commands) => {
4030                            self.state.event(
4031                                "fix",
4032                                format!(
4033                                    "round {round}: fixer's adoption report recovered after \
4034                                     {attempts} continuation(s)"
4035                                ),
4036                            );
4037                            return (
4038                                seat,
4039                                Some(report),
4040                                None,
4041                                ContinuationRecord {
4042                                    attempts,
4043                                    cumulative_wait_ms,
4044                                    outcome: ContinuationOutcome::Resumed,
4045                                },
4046                            );
4047                        }
4048                        // The report parsed, but this same reply's own
4049                        // CommandEvidence — the identical record `state.jobs`
4050                        // renders — names a command whose CLI never
4051                        // confirmed an exit status. Read together, that is
4052                        // not a resolved answer: keep nudging rather than
4053                        // accept a report standing next to a command the
4054                        // seat's own CLI cannot vouch for.
4055                        Ok(_) => {
4056                            last_err = "the reply parsed, but it reported a command whose own CLI \
4057                                 never confirmed an exit status"
4058                                .to_owned();
4059                        }
4060                        Err(e) => last_err = e.to_string(),
4061                    }
4062                }
4063                AgentOutcome::Quota(o) => {
4064                    cumulative_wait_ms += o.duration_ms;
4065                    let loss = QuotaLoss::from_report(seat.key.clone(), "fix", o.quota.as_ref());
4066                    block_machine_outage(&mut self.state, "fix", std::slice::from_ref(&loss));
4067                    self.state.quota.push(loss);
4068                    self.state.event(
4069                        "fix",
4070                        format!(
4071                            "round {round}: continuation rate limited (quota); not retrying now"
4072                        ),
4073                    );
4074                    return (
4075                        seat,
4076                        None,
4077                        Some("rate limited (quota) while recovering the fix report".to_owned()),
4078                        ContinuationRecord {
4079                            attempts,
4080                            cumulative_wait_ms,
4081                            outcome: ContinuationOutcome::QuotaLost,
4082                        },
4083                    );
4084                }
4085                AgentOutcome::Dropped(o) => {
4086                    cumulative_wait_ms += o.duration_ms;
4087                    let why = o
4088                        .dropped
4089                        .as_ref()
4090                        .map(|d| d.why.as_str())
4091                        .unwrap_or("the CLI ended the stream without delivering its answer");
4092                    last_err = format!("the CLI dropped the stream ({why})");
4093                }
4094                AgentOutcome::Failed(e) => last_err = e,
4095                // The continuation was never started; the report stays lost
4096                // and the caller records that, without any handover.
4097                AgentOutcome::ResourceBlocked(e) => {
4098                    return (
4099                        seat,
4100                        None,
4101                        Some(format!("the continuation was not started: {e}")),
4102                        ContinuationRecord {
4103                            attempts: attempts.saturating_sub(1),
4104                            cumulative_wait_ms,
4105                            outcome: ContinuationOutcome::NoSession,
4106                        },
4107                    );
4108                }
4109            }
4110        }
4111    }
4112
4113    fn after_implement(&mut self) -> Result<()> {
4114        if !self.state.candidate_preservation.is_empty() {
4115            bail!("candidate preservation incomplete; judging is unsafe");
4116        }
4117        // Scan every candidate patch once the set is complete.
4118        if self.state.leaks.is_empty() {
4119            let cfg = self.state.config.blind.clone();
4120            let mut leaks = Vec::new();
4121            for c in &self.state.candidates {
4122                let Some(patch) =
4123                    crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
4124                else {
4125                    continue;
4126                };
4127                leaks.extend(blind::scan(
4128                    &format!("candidate {} patch", c.label),
4129                    &patch,
4130                    &cfg.vendor_tokens,
4131                ));
4132            }
4133            if !leaks.is_empty() {
4134                let summary = leaks
4135                    .iter()
4136                    .map(|l| format!("{}×{} in {}", l.token, l.count, l.site))
4137                    .collect::<Vec<_>>()
4138                    .join(", ");
4139                match cfg.on_leak {
4140                    LeakPolicy::Fail => {
4141                        self.state.status = RunStatus::Failed;
4142                        self.state
4143                            .event("blind", format!("vendor text in a patch: {summary}"));
4144                        self.state.leaks = leaks;
4145                        self.state.save()?;
4146                        self.settle_questions();
4147                        bail!(
4148                            "blind.on_leak = \"fail\" and vendor text reached a \
4149                             judged patch: {summary}"
4150                        );
4151                    }
4152                    LeakPolicy::Redact => self.state.event(
4153                        "blind",
4154                        format!("redacting vendor text for judging: {summary}"),
4155                    ),
4156                    LeakPolicy::Warn => self.state.event(
4157                        "blind",
4158                        format!("vendor text present in a judged patch (shown as-is): {summary}"),
4159                    ),
4160                }
4161                self.state.leaks = leaks;
4162            }
4163        }
4164
4165        if self.state.viable().is_empty() {
4166            if self.state.all_candidates_verified_noop() {
4167                // Every candidate agreed, with evidence the adoption guard
4168                // accepted, that nothing belongs in this worktree. That is
4169                // not the same fact as a candidate that simply failed to
4170                // write anything, and settling it as an ordinary `Failed`
4171                // (see `SCHEMA`'s doc for schema 10) is what let two of
4172                // task 391f's attempts burn a retry each re-discovering the
4173                // same already-landed fix. Terminal either way, so `judge`
4174                // must never run over an empty candidate set — unlike the
4175                // `Failed` branch below this returns `Ok`, not an error:
4176                // nothing here failed.
4177                self.state.status = RunStatus::VerifiedNoop;
4178                self.state.save()?;
4179                self.settle_questions();
4180                return Ok(());
4181            }
4182            self.state.status = RunStatus::Failed;
4183            self.state.save()?;
4184            self.settle_questions();
4185            bail!("no candidate produced a change; nothing to judge");
4186        }
4187        self.state.status = RunStatus::Judging;
4188        self.state.save()?;
4189        Ok(())
4190    }
4191
4192    // --------------------------------------------------------------- judge
4193
4194    async fn judge(&mut self) -> Result<()> {
4195        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4196        // agent files with `magi task add` name the run that paid for it. The
4197        // prompt overlay is cloned alongside it because the waves borrow it
4198        // while `self` is mutably borrowed by the node's own bookkeeping.
4199        let run_id = self.state.id.clone();
4200        let prompts = self.state.config.prompts.clone();
4201        if !self.state.judgements.is_empty() || self.state.judge_skipped {
4202            return Ok(());
4203        }
4204        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4205        if viable.len() == 1 {
4206            // Recorded so this is a one-time event: `judgements` stays empty
4207            // either way, which without this flag is indistinguishable from
4208            // "not yet judged" on the next reentry — and status is left
4209            // untouched, so a later node's conclusion (e.g. `Blocked` after
4210            // the review budget ran out) survives a resume instead of being
4211            // clobbered back to `Judging` by this node running again.
4212            self.state.judge_skipped = true;
4213            self.state.event(
4214                "judge",
4215                format!(
4216                    "only candidate {} produced a change; judging skipped",
4217                    viable[0].label
4218                ),
4219            );
4220            self.state.save()?;
4221            return Ok(());
4222        }
4223        self.state.status = RunStatus::Judging;
4224
4225        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
4226        let language = self.state.config.graph.language.clone();
4227        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4228        let sessions = self.state.config.graph.sessions;
4229        let artifacts = agent::artifacts_dir(&self.state.dir());
4230        let root = self.state.worktree_root();
4231        let base_short = short(&self.state.base_commit);
4232
4233        let mut jobs = Vec::new();
4234        let mut orders = Vec::new();
4235        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4236            let order = blind::presentation_order(viable.len(), j, self.state.seed);
4237            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
4238            orders.push(order.iter().map(|&k| viable[k].index).collect::<Vec<_>>());
4239            let seat_key = format!("judge-{}", j + 1);
4240            let seat = self.seat(&seat_key, &spec.id);
4241            jobs.push(SeatJob {
4242                prompt: prompt::judge(
4243                    &self.state.instruction,
4244                    &views,
4245                    self.roles.judges.len(),
4246                    &base_short,
4247                    &language,
4248                ),
4249                spec,
4250                seat,
4251                cwd: root.join(format!("judge-{}", j + 1)),
4252                timeout,
4253                allow_write: false,
4254                sessions,
4255                artifacts: artifacts.clone(),
4256                stem: format!("judge-{}", j + 1),
4257                handover: None,
4258            });
4259        }
4260
4261        self.state.event(
4262            "judge",
4263            format!(
4264                "{} judges ranking {} candidates blind",
4265                jobs.len(),
4266                viable.len()
4267            ),
4268        );
4269        let labels_for_check = labels.clone();
4270        let mut quota_losses = Vec::new();
4271        let cache = self.state.config.cache_dir();
4272        let ctx = WaveCtx {
4273            carry_seats: false,
4274            pauses: Some((&self.pause, &self.interrupt)),
4275            run: &run_id,
4276            node: "judge",
4277            prompts: &prompts,
4278            cache: cache.as_deref(),
4279            round: None,
4280        };
4281        let results = ask_json_wave::<Ranking>(
4282            jobs,
4283            Arc::clone(&self.sem),
4284            self.state.config.graph.retries,
4285            &self.roles.judge_roster,
4286            &ctx,
4287            &mut quota_losses,
4288            &mut self.state,
4289            &move |r: &Ranking| r.validate(&labels_for_check),
4290        )
4291        .await;
4292        if self.state.resource_block.is_some() {
4293            return self.stop_for_resource();
4294        }
4295        self.state.quota.extend(quota_losses);
4296
4297        for (j, (seat, res, _attempts)) in results.into_iter().enumerate() {
4298            let agent_id = seat.agent.clone();
4299            self.state.seats.insert(seat.key.clone(), seat);
4300            let mut record = Judgement {
4301                judge: j + 1,
4302                seat: format!("judge-{}", j + 1),
4303                agent: agent_id,
4304                ranking: Vec::new(),
4305                reasons: BTreeMap::new(),
4306                confidence: None,
4307                strengths: BTreeMap::new(),
4308                order: orders[j].clone(),
4309                failed: None,
4310                duration_ms: 0,
4311            };
4312            match res {
4313                Ok((ranking, out)) => {
4314                    record.ranking = ranking.normalized();
4315                    record.reasons = ranking.reasons;
4316                    record.strengths = ranking.strengths;
4317                    record.confidence = ranking.confidence;
4318                    record.duration_ms = out.duration_ms;
4319                    self.state.event(
4320                        "judge",
4321                        format!(
4322                            "judge {} ranked {}",
4323                            j + 1,
4324                            record.ranking.iter().collect::<String>()
4325                        ),
4326                    );
4327                }
4328                Err(e) => {
4329                    record.failed = Some(e.to_string());
4330                    self.state
4331                        .event("judge", format!("judge {} produced no ranking: {e}", j + 1));
4332                }
4333            }
4334            self.state.judgements.push(record);
4335            self.state.save()?;
4336        }
4337        Ok(())
4338    }
4339
4340    // ---------------------------------------------------------- deliberate
4341
4342    async fn deliberate(&mut self) -> Result<()> {
4343        if self.hold_base_sync().await? {
4344            return Ok(());
4345        }
4346        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4347        // agent files with `magi task add` name the run that paid for it. The
4348        // prompt overlay is cloned alongside it because the waves borrow it
4349        // while `self` is mutably borrowed by the node's own bookkeeping.
4350        let run_id = self.state.id.clone();
4351        let prompts = self.state.config.prompts.clone();
4352        let rounds = self.state.config.graph.deliberate_rounds;
4353        // Resume unfinished rounds after an outage, but never reopen a tally.
4354        if self.state.deliberation.len() >= rounds || self.state.tally.is_some() {
4355            return Ok(());
4356        }
4357        let tops: Vec<char> = self
4358            .state
4359            .judgements
4360            .iter()
4361            .filter_map(|j| j.ranking.first().copied())
4362            .collect();
4363        if tops.len() < 2 || tops.iter().all(|t| *t == tops[0]) || rounds == 0 {
4364            if tops.len() >= 2 && tops.iter().all(|t| *t == tops[0]) {
4365                self.state.event(
4366                    "deliberate",
4367                    format!("judges agreed on {} outright; no deliberation", tops[0]),
4368                );
4369            }
4370            self.state.status = RunStatus::Voting;
4371            self.state.save()?;
4372            return Ok(());
4373        }
4374
4375        self.state.status = RunStatus::Deliberating;
4376        self.state.event(
4377            "deliberate",
4378            format!(
4379                "split: first choices were {} — opening {rounds} round(s)",
4380                tops.iter().collect::<String>()
4381            ),
4382        );
4383
4384        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4385        let language = self.state.config.graph.language.clone();
4386        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4387        let sessions = self.state.config.graph.sessions;
4388        let artifacts = agent::artifacts_dir(&self.state.dir());
4389        let root = self.state.worktree_root();
4390        let base_short = short(&self.state.base_commit);
4391
4392        // Judges argue in sequence so that a turn can answer the one before it;
4393        // that is the difference between deliberation and three parallel
4394        // monologues.
4395        for round in self.state.deliberation.len() + 1..=rounds {
4396            let mut turns: Vec<DeliberationTurn> = Vec::new();
4397            let mut round_losses = Vec::new();
4398            let mut asked = 0;
4399            for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4400                if self.state.judgements[j].failed.is_some() {
4401                    continue;
4402                }
4403                let seat_key = format!("judge-{}", j + 1);
4404                let spec = self.occupant(&seat_key, spec);
4405                let mut seat = self.seat(&seat_key, &spec.id);
4406                let transcript = self.transcript(&turns, j);
4407                let build = |context: Option<&str>| {
4408                    prompt::deliberate(
4409                        &self.state.instruction,
4410                        context,
4411                        &transcript,
4412                        round,
4413                        rounds,
4414                        &language,
4415                    )
4416                };
4417                let block = self.candidate_block(&viable, &base_short);
4418                let full = build(Some(&block));
4419                let text = if has_context(&spec, &seat, sessions) {
4420                    build(None)
4421                } else {
4422                    full.clone()
4423                };
4424                let job = SeatJob {
4425                    spec,
4426                    seat: seat.clone(),
4427                    prompt: text,
4428                    cwd: root.join(format!("judge-{}", j + 1)),
4429                    timeout,
4430                    allow_write: false,
4431                    sessions,
4432                    artifacts: artifacts.clone(),
4433                    stem: format!("delib-{round}-judge-{}", j + 1),
4434                    handover: Some(full),
4435                };
4436                let cache = self.state.config.cache_dir();
4437                let ctx = WaveCtx {
4438                    carry_seats: false,
4439                    pauses: Some((&self.pause, &self.interrupt)),
4440                    run: &run_id,
4441                    node: "deliberate",
4442                    prompts: &prompts,
4443                    cache: cache.as_deref(),
4444                    round: None,
4445                };
4446                // A turn is never nudged (`retries` 0): a failed seat is
4447                // handed to the next roster agent, which gets the full
4448                // context. An empty answer is a turn, not a failure.
4449                let mut losses = Vec::new();
4450                asked += 1;
4451                let mut results = ask_wave_with::<String>(
4452                    vec![job],
4453                    Arc::clone(&self.sem),
4454                    0,
4455                    &self.roles.judge_roster,
4456                    &ctx,
4457                    &mut losses,
4458                    &mut self.state,
4459                    &|text: &str| {
4460                        Ok(verdict::section(text, "position").unwrap_or_else(|| text.to_owned()))
4461                    },
4462                )
4463                .await;
4464                if self.state.resource_block.is_some() {
4465                    return self.stop_for_resource();
4466                }
4467                round_losses.extend(losses.iter().cloned());
4468                self.state.quota.extend(losses);
4469                let (updated, res, _) = results.pop().expect("one job in, one result out");
4470                seat = updated;
4471                let agent_id = seat.agent.clone();
4472                self.state.seats.insert(seat.key.clone(), seat);
4473                let body = match res {
4474                    Ok((body, _)) => body,
4475                    // Skip the seat; a CLI's raw error JSON is never read as
4476                    // this judge's position.
4477                    Err(e) => {
4478                        self.state
4479                            .event("deliberate", format!("judge {} skipped: {e}", j + 1));
4480                        continue;
4481                    }
4482                };
4483                let tentative = verdict::extract_json::<Position>(&body)
4484                    .ok()
4485                    .and_then(|p| p.tentative)
4486                    .and_then(|s| s.trim().chars().next())
4487                    .map(|c| c.to_ascii_uppercase());
4488                self.state.event(
4489                    "deliberate",
4490                    format!(
4491                        "round {round}: judge {} now favours {}",
4492                        j + 1,
4493                        tentative.map_or("—".to_owned(), |c| c.to_string())
4494                    ),
4495                );
4496                turns.push(DeliberationTurn {
4497                    judge: j + 1,
4498                    agent: agent_id,
4499                    body: blind::sanitize_prose(&body, &self.state.config.blind),
4500                    tentative,
4501                });
4502            }
4503            if asked > 0 && turns.is_empty() && round_losses.len() == asked {
4504                block_machine_outage(&mut self.state, "deliberate", &round_losses);
4505                return self.stop_for_resource();
4506            }
4507            self.state
4508                .deliberation
4509                .push(DeliberationRound { round, turns });
4510            self.state.save()?;
4511        }
4512
4513        self.state.status = RunStatus::Voting;
4514        self.state.save()?;
4515        Ok(())
4516    }
4517
4518    // ---------------------------------------------------------------- vote
4519
4520    async fn vote(&mut self) -> Result<()> {
4521        if self.hold_base_sync().await? {
4522            return Ok(());
4523        }
4524        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4525        // agent files with `magi task add` name the run that paid for it. The
4526        // prompt overlay is cloned alongside it because the waves borrow it
4527        // while `self` is mutably borrowed by the node's own bookkeeping.
4528        let run_id = self.state.id.clone();
4529        let prompts = self.state.config.prompts.clone();
4530        if !self.state.votes.is_empty() || self.state.tally.is_some() {
4531            return Ok(());
4532        }
4533        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
4534        if viable.len() == 1 {
4535            return Ok(());
4536        }
4537        self.state.status = RunStatus::Voting;
4538
4539        let language = self.state.config.graph.language.clone();
4540        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4541        let sessions = self.state.config.graph.sessions;
4542        let artifacts = agent::artifacts_dir(&self.state.dir());
4543        let root = self.state.worktree_root();
4544        let base_short = short(&self.state.base_commit);
4545        let candidates: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4546
4547        let mut jobs = Vec::new();
4548        let mut seats_at = Vec::new();
4549        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4550            if self
4551                .state
4552                .judgements
4553                .get(j)
4554                .is_some_and(|r| r.failed.is_some())
4555            {
4556                continue;
4557            }
4558            let seat_key = format!("judge-{}", j + 1);
4559            let spec = self.occupant(&seat_key, spec);
4560            let seat = self.seat(&seat_key, &spec.id);
4561            let full = self.vote_prompt_full(j, &viable, &language, &candidates, &base_short);
4562            let text = if has_context(&spec, &seat, sessions) {
4563                prompt::final_vote(&viable, &language)
4564            } else {
4565                full.clone()
4566            };
4567            jobs.push(SeatJob {
4568                spec,
4569                seat,
4570                prompt: text,
4571                cwd: root.join(format!("judge-{}", j + 1)),
4572                timeout,
4573                allow_write: false,
4574                sessions,
4575                artifacts: artifacts.clone(),
4576                stem: format!("vote-judge-{}", j + 1),
4577                handover: Some(full),
4578            });
4579            seats_at.push(j);
4580        }
4581
4582        self.state.event(
4583            "vote",
4584            format!(
4585                "collecting {} final votes one by one, privately",
4586                jobs.len()
4587            ),
4588        );
4589        let allowed = viable.clone();
4590        let mut quota_losses = Vec::new();
4591        let cache = self.state.config.cache_dir();
4592        let ctx = WaveCtx {
4593            carry_seats: false,
4594            pauses: Some((&self.pause, &self.interrupt)),
4595            run: &run_id,
4596            node: "vote",
4597            prompts: &prompts,
4598            cache: cache.as_deref(),
4599            round: None,
4600        };
4601        let results = ask_json_wave::<FinalVote>(
4602            jobs,
4603            Arc::clone(&self.sem),
4604            self.state.config.graph.retries,
4605            &self.roles.judge_roster,
4606            &ctx,
4607            &mut quota_losses,
4608            &mut self.state,
4609            &move |v: &FinalVote| match v.label() {
4610                Some(c) if allowed.contains(&c) => Ok(()),
4611                other => bail!("vote {other:?} is not one of {allowed:?}"),
4612            },
4613        )
4614        .await;
4615        if self.state.resource_block.is_some() {
4616            return self.stop_for_resource();
4617        }
4618        self.state.quota.extend(quota_losses);
4619
4620        for (&j, (seat, res, _attempts)) in seats_at.iter().zip(results) {
4621            let agent_id = seat.agent.clone();
4622            self.state.seats.insert(seat.key.clone(), seat);
4623            let initial = self
4624                .state
4625                .judgements
4626                .get(j)
4627                .and_then(|r| r.ranking.first().copied());
4628            let mut record = VoteRecord {
4629                judge: j + 1,
4630                agent: agent_id,
4631                vote: None,
4632                reason: String::new(),
4633                changed: false,
4634            };
4635            match res {
4636                Ok((v, _)) => {
4637                    record.vote = v.label();
4638                    record.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
4639                    record.changed = matches!((record.vote, initial), (Some(a), Some(b)) if a != b);
4640                    self.state.event(
4641                        "vote",
4642                        format!(
4643                            "judge {} voted {}{}",
4644                            j + 1,
4645                            record.vote.unwrap_or('?'),
4646                            if record.changed { " (changed)" } else { "" }
4647                        ),
4648                    );
4649                }
4650                Err(e) => {
4651                    self.state
4652                        .event("vote", format!("judge {} cast no vote: {e}", j + 1));
4653                }
4654            }
4655            self.state.votes.push(record);
4656            self.state.save()?;
4657        }
4658        Ok(())
4659    }
4660
4661    // --------------------------------------------------------------- tally
4662
4663    fn tally(&mut self) -> Result<()> {
4664        if self.state.tally.is_some() {
4665            return Ok(());
4666        }
4667        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
4668        let tops: Vec<char> = self
4669            .state
4670            .judgements
4671            .iter()
4672            .filter_map(|j| j.ranking.first().copied())
4673            .collect();
4674        let unanimous_initial = tops.len() > 1 && tops.iter().all(|t| *t == tops[0]);
4675
4676        // A judge whose private vote failed still counted once, in the initial
4677        // ranking; using it beats discarding a whole seat.
4678        let mut first_choice: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
4679        let mut cast: Vec<char> = Vec::new();
4680        for (i, j) in self.state.judgements.iter().enumerate() {
4681            let vote = self
4682                .state
4683                .votes
4684                .iter()
4685                .find(|v| v.judge == i + 1)
4686                .and_then(|v| v.vote)
4687                .or_else(|| j.ranking.first().copied());
4688            if let Some(v) = vote {
4689                *first_choice.entry(v).or_insert(0) += 1;
4690                cast.push(v);
4691            }
4692        }
4693
4694        let mut borda: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
4695        for j in &self.state.judgements {
4696            let n = j.ranking.len();
4697            for (pos, label) in j.ranking.iter().enumerate() {
4698                *borda.entry(*label).or_insert(0) += n.saturating_sub(pos + 1);
4699            }
4700        }
4701
4702        let best = first_choice.values().copied().max().unwrap_or(0);
4703        let mut leaders: Vec<char> = first_choice
4704            .iter()
4705            .filter(|(_, v)| **v == best)
4706            .map(|(k, _)| *k)
4707            .collect();
4708        let mut tie_break = None;
4709        if leaders.len() > 1 {
4710            let top_borda = leaders.iter().map(|l| borda[l]).max().unwrap_or(0);
4711            let borda_leaders: Vec<char> = leaders
4712                .iter()
4713                .copied()
4714                .filter(|l| borda[l] == top_borda)
4715                .collect();
4716            tie_break = Some(if borda_leaders.len() == 1 {
4717                format!(
4718                    "{} way tie on first-choice votes, broken by Borda points from the initial rankings",
4719                    leaders.len()
4720                )
4721            } else {
4722                format!(
4723                    "{} way tie on both first-choice votes and Borda points, broken by label order",
4724                    leaders.len()
4725                )
4726            });
4727            leaders = borda_leaders;
4728            leaders.sort_unstable();
4729        }
4730        let winner = *leaders
4731            .first()
4732            .or(viable.first())
4733            .context("no candidate to declare a winner from")?;
4734
4735        let changed_votes = self.state.votes.iter().filter(|v| v.changed).count();
4736        let unanimous_final = !cast.is_empty() && cast.iter().all(|c| *c == cast[0]);
4737        let deliberated = !self.state.deliberation.is_empty();
4738
4739        // Whose verdict is this? A rate-limited seat is absent even if it
4740        // ranked before the limit hit, so presence is measured against the
4741        // recorded losses, not just "did a ranking ever appear".
4742        let quota_seats: std::collections::BTreeSet<&str> =
4743            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
4744        let mut present = 0usize;
4745        for (i, j) in self.state.judgements.iter().enumerate() {
4746            if quota_seats.contains(j.seat.as_str()) {
4747                continue;
4748            }
4749            let ranked = !j.ranking.is_empty() && j.failed.is_none();
4750            let voted = self
4751                .state
4752                .votes
4753                .iter()
4754                .any(|v| v.judge == i + 1 && v.vote.is_some());
4755            if ranked || voted {
4756                present += 1;
4757            }
4758        }
4759        // Strict majority of the configured panel. A bare majority is real
4760        // signal we can act on, while a minority verdict must never stand in
4761        // for a healthy one. A one-candidate run needs no panel at all, and
4762        // `judges` stays `0` rather than the roster size a panel that never
4763        // sat would otherwise be credited with.
4764        let needs_quorum = viable.len() > 1;
4765        let judges_total = if needs_quorum {
4766            self.roles.judges.len()
4767        } else {
4768            0
4769        };
4770        let quorum = if needs_quorum {
4771            judges_total / 2 + 1
4772        } else {
4773            0
4774        };
4775        let met_quorum = !needs_quorum || present >= quorum;
4776        let uncontested = (!needs_quorum).then(|| {
4777            format!("only one candidate ({winner}) produced a usable change; no panel was asked")
4778        });
4779
4780        self.state.event(
4781            "tally",
4782            match &uncontested {
4783                Some(reason) => format!("winner {winner} — {reason}"),
4784                None => format!(
4785                    "winner {winner} — votes {} | initial {} | {} changed | \
4786                     {present}/{judges_total} judges{}",
4787                    first_choice
4788                        .iter()
4789                        .map(|(k, v)| format!("{k}:{v}"))
4790                        .collect::<Vec<_>>()
4791                        .join(" "),
4792                    if unanimous_initial {
4793                        "unanimous"
4794                    } else {
4795                        "split"
4796                    },
4797                    changed_votes,
4798                    if met_quorum {
4799                        String::new()
4800                    } else {
4801                        format!(" — below quorum ({quorum} required)")
4802                    },
4803                ),
4804            },
4805        );
4806        if !met_quorum {
4807            self.state.event(
4808                "stall",
4809                format!(
4810                    "verdict rests on {present} of {judges_total} judges (quorum {quorum}); \
4811                     the run stops here, resumable"
4812                ),
4813            );
4814        }
4815        self.state.tally = Some(Tally {
4816            first_choice,
4817            borda,
4818            winner,
4819            rankings: tops.len(),
4820            unanimous_initial,
4821            deliberated,
4822            changed_votes,
4823            unanimous_final,
4824            tie_break,
4825            judges: judges_total,
4826            present,
4827            quorum,
4828            met_quorum,
4829            uncontested,
4830        });
4831        self.state.status = if met_quorum {
4832            RunStatus::Reviewing
4833        } else {
4834            RunStatus::Stalled
4835        };
4836        self.state.save()?;
4837        Ok(())
4838    }
4839
4840    // ------------------------------------------------------------- recover
4841
4842    /// Re-ask the judge seats `tally` counts as absent, so a `Stalled` run can be
4843    /// resumed toward completion once the transient cause clears.
4844    ///
4845    /// A seat is absent — and therefore re-asked — when `tally` refuses to count
4846    /// it toward the quorum, which is exactly the set of seats whose absence
4847    /// collapsed the panel: struck by a rate limit at *any* node (the quorum must
4848    /// not depend on which node happened to hit the limit), or an ordinary
4849    /// failure (`failed = Some`) that never produced a usable ranking. A healthy
4850    /// seat is never disturbed.
4851    ///
4852    /// A seat that now answers with a usable ranking is "recovered": its
4853    /// `Judgement` is refreshed, its `QuotaLoss`/`failed` state cleared (so
4854    /// `tally` counts it present again), and its vote re-collected. A seat that
4855    /// still fails keeps its loss and stays absent.
4856    ///
4857    /// Returns `true` when the re-tally restores the quorum (the run may proceed
4858    /// to review/gate/merge), `false` when it is still below quorum (the run
4859    /// stays `Stalled`, still resumable for a later retry).
4860    #[allow(clippy::too_many_lines)]
4861    async fn recover_stall(&mut self) -> Result<bool> {
4862        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4863        // agent files with `magi task add` name the run that paid for it. The
4864        // prompt overlay is cloned alongside it because the waves borrow it
4865        // while `self` is mutably borrowed by the node's own bookkeeping.
4866        let run_id = self.state.id.clone();
4867        let prompts = self.state.config.prompts.clone();
4868        // Absent seats = quota-lost at any node, or failed outright. Mirroring
4869        // `tally`'s presence test (rather than the old quota-judge/vote filter)
4870        // is what keeps a non-quota collapse — or a quota loss recorded at the
4871        // deliberate node — from being a permanent dead-end on `--resume`.
4872        let quota_seats: BTreeSet<&str> =
4873            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
4874        let absent: Vec<String> = self
4875            .state
4876            .judgements
4877            .iter()
4878            .filter(|j| quota_seats.contains(j.seat.as_str()) || j.failed.is_some())
4879            .map(|j| j.seat.clone())
4880            .collect();
4881        if absent.is_empty() {
4882            return Ok(false);
4883        }
4884        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4885        if viable.len() <= 1 {
4886            return Ok(false);
4887        }
4888        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
4889        let language = self.state.config.graph.language.clone();
4890        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4891        let sessions = self.state.config.graph.sessions;
4892        let artifacts = agent::artifacts_dir(&self.state.dir());
4893        let root = self.state.worktree_root();
4894        let base_short = short(&self.state.base_commit);
4895        let candidates: Vec<Candidate> = viable.clone();
4896
4897        // Map each absent seat key to its 0-based position in `roles.judges`.
4898        let mut positions: Vec<usize> = absent
4899            .iter()
4900            .filter_map(|k| self.state.judgements.iter().position(|r| &r.seat == k))
4901            .collect();
4902        if positions.is_empty() {
4903            return Ok(false);
4904        }
4905        positions.sort_unstable();
4906        positions.dedup();
4907
4908        // Re-rank the lost seats, one blind prompt each.
4909        let mut judge_jobs = Vec::new();
4910        for &j in &positions {
4911            let order = blind::presentation_order(viable.len(), j, self.state.seed);
4912            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
4913            let seat_key = format!("judge-{}", j + 1);
4914            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
4915            let seat = self.seat(&seat_key, &spec.id);
4916            judge_jobs.push(SeatJob {
4917                spec,
4918                seat,
4919                prompt: prompt::judge(
4920                    &self.state.instruction,
4921                    &views,
4922                    self.roles.judges.len(),
4923                    &base_short,
4924                    &language,
4925                ),
4926                cwd: root.join(seat_key),
4927                timeout,
4928                allow_write: false,
4929                sessions,
4930                artifacts: artifacts.clone(),
4931                stem: format!("judge-{}-recover", j + 1),
4932                handover: None,
4933            });
4934        }
4935
4936        let labels_for_check = labels.clone();
4937        let mut judge_losses = Vec::new();
4938        let retries = self.state.config.graph.retries;
4939        let cache = self.state.config.cache_dir();
4940        let ctx = WaveCtx {
4941            carry_seats: false,
4942            pauses: Some((&self.pause, &self.interrupt)),
4943            run: &run_id,
4944            node: "judge",
4945            prompts: &prompts,
4946            cache: cache.as_deref(),
4947            round: None,
4948        };
4949        let results = ask_json_wave::<Ranking>(
4950            judge_jobs,
4951            Arc::clone(&self.sem),
4952            retries,
4953            &self.roles.judge_roster,
4954            &ctx,
4955            &mut judge_losses,
4956            &mut self.state,
4957            &move |r: &Ranking| r.validate(&labels_for_check),
4958        )
4959        .await;
4960        if self.state.resource_block.is_some() {
4961            self.stop_for_resource()?;
4962            return Ok(false);
4963        }
4964
4965        // Refresh the judgement of every seat that ranked again.
4966        let mut recovered: BTreeSet<usize> = BTreeSet::new();
4967        for (&j, (seat, res, _attempts)) in positions.iter().zip(results) {
4968            let agent_id = seat.agent.clone();
4969            self.state.seats.insert(seat.key.clone(), seat);
4970            let record = &mut self.state.judgements[j];
4971            match res {
4972                Ok((ranking, out)) => {
4973                    record.agent = agent_id;
4974                    record.ranking = ranking.normalized();
4975                    record.reasons = ranking.reasons;
4976                    record.strengths = ranking.strengths;
4977                    record.confidence = ranking.confidence;
4978                    record.failed = None;
4979                    record.duration_ms = out.duration_ms;
4980                    recovered.insert(j);
4981                    self.state.event(
4982                        "recover",
4983                        format!("judge {} ranked again after the limit", j + 1),
4984                    );
4985                }
4986                Err(e) => {
4987                    self.state
4988                        .event("recover", format!("judge {} still cannot rank: {e}", j + 1));
4989                }
4990            }
4991        }
4992
4993        // Re-ask the votes of the seats that recovered a ranking.
4994        let mut vote_jobs = Vec::new();
4995        let mut vote_pos: Vec<usize> = Vec::new();
4996        for &j in &recovered {
4997            let seat_key = format!("judge-{}", j + 1);
4998            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
4999            let seat = self.seat(&seat_key, &spec.id);
5000            let full = self.vote_prompt_full(j, &labels, &language, &candidates, &base_short);
5001            let text = if has_context(&spec, &seat, sessions) {
5002                prompt::final_vote(&labels, &language)
5003            } else {
5004                full.clone()
5005            };
5006            vote_jobs.push(SeatJob {
5007                spec,
5008                seat,
5009                prompt: text,
5010                cwd: root.join(seat_key),
5011                timeout,
5012                allow_write: false,
5013                sessions,
5014                artifacts: artifacts.clone(),
5015                stem: format!("vote-judge-{}-recover", j + 1),
5016                handover: Some(full),
5017            });
5018            vote_pos.push(j);
5019        }
5020        let allowed = labels.clone();
5021        let mut vote_losses = Vec::new();
5022        let vote_retries = self.state.config.graph.retries;
5023        let vote_cache = self.state.config.cache_dir();
5024        let ctx = WaveCtx {
5025            carry_seats: false,
5026            pauses: Some((&self.pause, &self.interrupt)),
5027            run: &run_id,
5028            node: "vote",
5029            prompts: &prompts,
5030            cache: vote_cache.as_deref(),
5031            round: None,
5032        };
5033        let votes = ask_json_wave::<FinalVote>(
5034            vote_jobs,
5035            Arc::clone(&self.sem),
5036            vote_retries,
5037            &self.roles.judge_roster,
5038            &ctx,
5039            &mut vote_losses,
5040            &mut self.state,
5041            &move |v: &FinalVote| match v.label() {
5042                Some(c) if allowed.contains(&c) => Ok(()),
5043                other => bail!("vote {other:?} is not one of {allowed:?}"),
5044            },
5045        )
5046        .await;
5047        if self.state.resource_block.is_some() {
5048            self.stop_for_resource()?;
5049            return Ok(false);
5050        }
5051        for (&j, (seat, res, _attempts)) in vote_pos.iter().zip(votes) {
5052            let agent_id = seat.agent.clone();
5053            self.state.seats.insert(seat.key.clone(), seat);
5054            match res {
5055                Ok((v, _)) => {
5056                    if let Some(rec) = self.state.votes.iter_mut().find(|r| r.judge == j + 1) {
5057                        rec.vote = v.label();
5058                        rec.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
5059                    } else {
5060                        self.state.votes.push(VoteRecord {
5061                            judge: j + 1,
5062                            agent: agent_id,
5063                            vote: v.label(),
5064                            reason: blind::sanitize_prose(&v.reason, &self.state.config.blind),
5065                            changed: false,
5066                        });
5067                    }
5068                    self.state.event(
5069                        "recover",
5070                        format!("judge {} voted again after the limit", j + 1),
5071                    );
5072                }
5073                Err(e) => {
5074                    self.state
5075                        .event("recover", format!("judge {} still cannot vote: {e}", j + 1));
5076                }
5077            }
5078        }
5079
5080        // A seat that ranked again is present even if its re-vote failed —
5081        // `tally` falls back to the initial ranking's first choice — so clear
5082        // its quota loss. Seats that still fail keep theirs and stay absent.
5083        let recovered_keys: BTreeSet<String> = recovered
5084            .iter()
5085            .map(|&j| format!("judge-{}", j + 1))
5086            .collect();
5087        self.state
5088            .quota
5089            .retain(|q| !recovered_keys.contains(&q.seat));
5090        // A seat that hit the limit again is a fresh loss, not the old one:
5091        // replace the stale entry so the history stays one-per-seat and the
5092        // daemon can tell this attempt's loss from a previous session's.
5093        for loss in judge_losses.into_iter().chain(vote_losses) {
5094            if recovered_keys.contains(&loss.seat) {
5095                continue;
5096            }
5097            self.state.quota.retain(|q| q.seat != loss.seat);
5098            self.state.quota.push(loss);
5099        }
5100
5101        // Recompute the verdict from the refreshed panel.
5102        self.state.tally = None;
5103        self.tally()?;
5104        Ok(self
5105            .state
5106            .tally
5107            .as_ref()
5108            .map(|t| t.met_quorum)
5109            .unwrap_or(false))
5110    }
5111
5112    // ---------------------------------------------------------------- graft
5113
5114    /// Port the strengths the judges attributed to the losing candidates onto
5115    /// the winner, once, between the tally and the review loop.
5116    ///
5117    /// Best-effort by construction: it returns nothing and fails nothing. A
5118    /// skip, a fixer that failed or hit quota, or a round that changed nothing
5119    /// all leave the winner at its previous commit (`GraftRecord::pre`), and
5120    /// the run carries on as if the phase were off. See [`graft`] for the
5121    /// decisions and `AGENTS.md` for the invariants.
5122    ///
5123    /// The one exception is a rollback that could not be confirmed: the
5124    /// rejected commit may still be the winner's tip, so the run is blocked
5125    /// (resumable; the record stays `Running`, which makes a resume retry the
5126    /// restore) instead of reviewing, gating and merging it.
5127    async fn graft(&mut self) -> Result<()> {
5128        let Err(e) = self.graft_inner().await else {
5129            return Ok(());
5130        };
5131        if e.is::<crate::repo_lock::ResourceBlocked>() {
5132            return Err(e);
5133        }
5134        if e.downcast_ref::<GraftRestoreFailed>().is_some() {
5135            self.state.status = RunStatus::Blocked;
5136            self.state.event("graft", format!("blocked: {e:#}"));
5137            self.state.save()?;
5138            return Err(e);
5139        }
5140        // An error after the `Running` record was saved may have left the
5141        // fixer's work in the tree: the record must not stay unsettled
5142        // (a later resume would reset past the review fixes), so confirm the
5143        // restore now, or block.
5144        if let Some(rec) = self.state.graft.clone()
5145            && !rec.outcome.settled()
5146        {
5147            if let Some(winner) = self.state.winner().cloned() {
5148                if let Err(re) = self.graft_restore(&winner.worktree, &rec.pre).await {
5149                    if re.is::<crate::repo_lock::ResourceBlocked>() {
5150                        return Err(re);
5151                    }
5152                    self.state.status = RunStatus::Blocked;
5153                    self.state.event("graft", format!("blocked: {re:#}"));
5154                    self.state.save()?;
5155                    return Err(re);
5156                }
5157            }
5158            if let Some(g) = self.state.graft.as_mut() {
5159                g.outcome = GraftOutcome::RolledBack(format!("{e:#}"));
5160            }
5161        }
5162        self.state.event("graft", format!("skipped: {e:#}"));
5163        if let Err(e) = self.state.save() {
5164            tracing::warn!("save after graft: {e:#}");
5165        }
5166        Ok(())
5167    }
5168
5169    /// Put the winner back on `pre` and confirm it: a failed `reset` (a stale
5170    /// `index.lock`, say) or a tip that is not `pre` afterwards is an error.
5171    async fn graft_restore(&mut self, wt: &Path, pre: &str) -> Result<()> {
5172        let _coordination = self.coordinate(wt).await?;
5173        crate::recovery::restore_repair(wt, pre)
5174            .await
5175            .map_err(|e| GraftRestoreFailed(format!("{e:#}")).into())
5176    }
5177
5178    /// A skip is a run event, recorded once however often the node is re-entered.
5179    fn graft_skipped(&mut self, why: &str) {
5180        let message = format!("skipped: {why}");
5181        if !self
5182            .state
5183            .events
5184            .iter()
5185            .any(|e| e.node == "graft" && e.message == message)
5186        {
5187            self.state.event("graft", message);
5188        }
5189    }
5190
5191    async fn graft_inner(&mut self) -> Result<()> {
5192        // A round that was started and never finished (crash, kill): the
5193        // fixer may have left anything in the tree, so put the winner back.
5194        if let Some(rec) = self.state.graft.clone()
5195            && !rec.outcome.settled()
5196        {
5197            // Reviews exist only if the graft ended without its record being
5198            // settled (a swallowed error): the tree has moved on since, and
5199            // a reset to `pre` would discard the review fixes.
5200            if self.state.reviews.is_empty()
5201                && let Some(winner) = self.state.winner().cloned()
5202            {
5203                self.graft_restore(&winner.worktree, &rec.pre).await?;
5204            }
5205            if rec.outcome == GraftOutcome::WaitingForRestore {
5206                self.state.graft = None;
5207                self.state.save()?;
5208            } else {
5209                if let Some(g) = self.state.graft.as_mut() {
5210                    g.outcome = GraftOutcome::RolledBack(graft::INTERRUPTED.to_owned());
5211                }
5212                self.state.event(
5213                    "graft",
5214                    "rolled back: the previous round was interrupted; the winner is untouched",
5215                );
5216                self.state.save()?;
5217                return Ok(());
5218            }
5219        }
5220        let plan = match graft::plan(&self.state) {
5221            Ok(plan) => plan,
5222            Err(skip) => {
5223                if skip != graft::Skip::AlreadyDone {
5224                    self.graft_skipped(skip.reason());
5225                    self.state.save()?;
5226                }
5227                return Ok(());
5228            }
5229        };
5230        let Some(winner) = self.state.winner().cloned() else {
5231            return Ok(());
5232        };
5233        let wt = winner.worktree.clone();
5234        if !git::is_clean(&wt).await? {
5235            self.graft_skipped("the winner's worktree has uncommitted changes");
5236            self.state.save()?;
5237            return Ok(());
5238        }
5239        let pre = git::rev_parse(&wt, "HEAD").await?;
5240        // Saved before the fixer is called: a stop from here on is repaired
5241        // by the branch above on the next entry.
5242        self.state.graft = Some(GraftRecord {
5243            pre: pre.clone(),
5244            post: None,
5245            lines: None,
5246            limit: None,
5247            agent: None,
5248            outcome: GraftOutcome::Running,
5249            requested: graft::requested(&plan),
5250            adoption: None,
5251            adoption_error: None,
5252        });
5253        self.state.event(
5254            "graft",
5255            format!(
5256                "porting strengths of candidate(s) {} onto {}",
5257                plan.strengths
5258                    .iter()
5259                    .map(|(l, _, _)| l.to_string())
5260                    .collect::<Vec<_>>()
5261                    .join(", "),
5262                plan.winner
5263            ),
5264        );
5265        self.state.save()?;
5266
5267        let fix_prompt = prompt::graft(
5268            &self.state.instruction,
5269            plan.winner,
5270            &plan.strengths,
5271            &self.state.config.graph.language,
5272        );
5273        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
5274        let sessions = self.state.config.graph.sessions;
5275        let artifacts = agent::artifacts_dir(&self.state.dir());
5276        let attempts = fixer::graft_attempts(&self.state, &self.roles, &winner);
5277        let (_, seat, out) = self
5278            .ask_fixer_among(attempts, "graft", None, Some((&wt, &pre)), |spec, seat| {
5279                SeatJob {
5280                    prompt: fix_prompt.clone(),
5281                    spec,
5282                    seat,
5283                    cwd: wt.clone(),
5284                    timeout,
5285                    allow_write: true,
5286                    sessions,
5287                    artifacts: artifacts.clone(),
5288                    stem: "graft".to_owned(),
5289                    handover: None,
5290                }
5291            })
5292            .await;
5293        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
5294            // Preserve the need to restore earlier fallback edits without
5295            // confusing an unstarted seat with an interrupted invocation.
5296            self.state.graft.as_mut().expect("graft record").outcome =
5297                GraftOutcome::WaitingForRestore;
5298            return self.stop_for_resource();
5299        }
5300        let mut why: Option<String> = None;
5301        match &out {
5302            AgentOutcome::Ok(o) if agent::output_advances(o) => {
5303                why = Some("the fixer produced nothing usable".to_owned());
5304            }
5305            AgentOutcome::Ok(_) => {}
5306            AgentOutcome::Dropped(_) => why = Some("the CLI dropped the stream".to_owned()),
5307            AgentOutcome::Quota(o) => {
5308                self.state.quota.push(QuotaLoss::from_report(
5309                    seat.key.clone(),
5310                    "graft",
5311                    o.quota.as_ref(),
5312                ));
5313                why = Some("rate limited (quota)".to_owned());
5314            }
5315            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
5316                why = Some(format!(
5317                    "the fixer failed: {}",
5318                    e.lines()
5319                        .next()
5320                        .unwrap_or("")
5321                        .chars()
5322                        .take(160)
5323                        .collect::<String>()
5324                ));
5325            }
5326        }
5327        let agent_id = seat.agent.clone();
5328        self.state.seats.insert(seat.key.clone(), seat);
5329
5330        let mut post = None;
5331        let mut lines = None;
5332        let _coordination = self.coordinate(&wt).await?;
5333        if why.is_none() {
5334            let rescued = git::rescue_commit(&wt, "magi: graft (uncommitted work)").await;
5335            if let Ok(r) = &rescued {
5336                self.state.note_withheld("graft", &r.withheld);
5337            }
5338            let head = git::rev_parse(&wt, "HEAD").await?;
5339            // What is measured must be what gets reviewed and gated: a failed
5340            // rescue, or anything still uncommitted (withheld lockfiles
5341            // aside, which are never part of the tree), rejects the graft.
5342            let dirty = match &rescued {
5343                Ok(r) => git::status_porcelain(&wt)
5344                    .await
5345                    .map(|st| {
5346                        st.lines().any(|l| {
5347                            !r.withheld
5348                                .iter()
5349                                .any(|w| l.trim_end().ends_with(w.path.as_str()))
5350                        })
5351                    })
5352                    .unwrap_or(true),
5353                Err(_) => true,
5354            };
5355            if dirty {
5356                why = Some("the fixer left changes that could not be committed".to_owned());
5357            } else if head == pre {
5358                why = Some("the fixer changed nothing".to_owned());
5359            } else {
5360                lines = git::changed_lines(&wt, &pre, &head).await;
5361                post = Some(head);
5362            }
5363        }
5364        let (adoption, adoption_error) = match &out {
5365            AgentOutcome::Ok(o) => crate::graft_report::adoption_of(&o.text),
5366            _ => (None, None),
5367        };
5368        let requested = graft::requested(&plan);
5369        let outcome = match why {
5370            None => {
5371                self.state.event(
5372                    "graft",
5373                    format!(
5374                        "applied: {}",
5375                        lines.map_or_else(
5376                            || "changed lines unavailable".to_owned(),
5377                            |n| format!("{n} changed lines")
5378                        )
5379                    ),
5380                );
5381                GraftOutcome::Applied
5382            }
5383            Some(why) => {
5384                // Not settled until the restore is confirmed: the record
5385                // stays `Running`, so a resume retries it.
5386                crate::recovery::restore_repair(&wt, &pre)
5387                    .await
5388                    .map_err(|e| GraftRestoreFailed(format!("{e:#}")))?;
5389                self.state.event(
5390                    "graft",
5391                    format!("rolled back: {why}; the winner is untouched"),
5392                );
5393                GraftOutcome::RolledBack(why)
5394            }
5395        };
5396        self.state.graft = Some(GraftRecord {
5397            pre,
5398            post,
5399            lines,
5400            limit: None,
5401            agent: Some(agent_id),
5402            outcome,
5403            requested,
5404            adoption,
5405            adoption_error,
5406        });
5407        self.state.save()?;
5408        Ok(())
5409    }
5410
5411    // ----------------------------------------------------------------- fold
5412
5413    async fn fold_losers(&mut self) -> Result<()> {
5414        let Some(winner) = self.state.tally.as_ref().map(|t| t.winner) else {
5415            return Ok(());
5416        };
5417        if !self.state.candidate_preservation.is_empty() {
5418            bail!("candidate preservation incomplete; refusing cleanup");
5419        }
5420        let repo = self.state.repo.clone();
5421        let _coordination = self.coordinate(&repo).await?;
5422        let home = crate::run::home();
5423        let root = self.state.worktree_root();
5424        let isolated = crate::build_target::isolated(&self.state.config);
5425        let mut folded = Vec::new();
5426        for i in 0..self.state.candidates.len() {
5427            let c = &self.state.candidates[i];
5428            if c.label == winner || c.folded {
5429                continue;
5430            }
5431            let (wt, branch, label) = (c.worktree.clone(), c.branch.clone(), c.label);
5432            let target = fold_target(&home, &root, &wt, isolated);
5433            remove_preserved_worktree(&repo, &wt).await?;
5434            reclaim_fold_target(&home, target);
5435            if git::branch_exists(&repo, &branch).await?
5436                && !git::branch_delete(&repo, &branch).await?
5437            {
5438                bail!("candidate branch removal refused");
5439            }
5440            self.state.candidates[i].folded = true;
5441            self.state.save()?;
5442            folded.push(label.to_string());
5443        }
5444        // The judges are finished; their checkouts are pure cost from here.
5445        for j in 1..=self.roles.judges.len() {
5446            let wt = root.join(format!("judge-{j}"));
5447            if wt.exists() {
5448                let target = fold_target(&home, &root, &wt, isolated);
5449                remove_read_seat_worktree(&mut self.state, &wt).await?;
5450                reclaim_fold_target(&home, target);
5451                self.state.save()?;
5452            }
5453        }
5454        // The design-deliberation stage is finished by the time a tally
5455        // exists — same reasoning as the judges above.
5456        if self.state.config.graph.advise {
5457            for k in 1..=self.state.config.graph.advisors {
5458                let wt = root.join(format!("advisor-{k}"));
5459                if wt.exists() {
5460                    let target = fold_target(&home, &root, &wt, isolated);
5461                    remove_read_seat_worktree(&mut self.state, &wt).await?;
5462                    reclaim_fold_target(&home, target);
5463                    self.state.save()?;
5464                }
5465            }
5466        }
5467        if !folded.is_empty() {
5468            self.state
5469                .event("fold", format!("folded candidates {}", folded.join(", ")));
5470            self.state.save()?;
5471        }
5472        Ok(())
5473    }
5474
5475    // ------------------------------------------------------------ base sync
5476
5477    async fn hold_base_sync(&mut self) -> Result<bool> {
5478        self.hold_base_sync_as(None).await
5479    }
5480
5481    async fn hold_base_sync_kind(
5482        &mut self,
5483        kind: crate::base_sync_recovery::StopKind,
5484    ) -> Result<()> {
5485        self.hold_base_sync_as(Some(kind)).await?;
5486        Ok(())
5487    }
5488
5489    async fn hold_base_sync_as(
5490        &mut self,
5491        kind: Option<crate::base_sync_recovery::StopKind>,
5492    ) -> Result<bool> {
5493        if !self.state.base_sync_blocked() {
5494            self.state.base_sync_recovery.stop = None;
5495            return Ok(false);
5496        }
5497        let head = match self.state.winner() {
5498            Some(w) => git::rev_parse(&w.worktree, "HEAD")
5499                .await
5500                .unwrap_or_default(),
5501            None => String::new(),
5502        };
5503        if let Some(authorization) = self.state.base_sync_recovery.authorizations.last_mut()
5504            && !authorization.consumed
5505            && authorization.stop.head != head
5506        {
5507            authorization.refuse(format!(
5508                "retained HEAD changed from {} to {head}; inspect it and authorize again with --recover-base",
5509                authorization.stop.head
5510            ));
5511        }
5512        self.state.record_base_sync_stop(&head);
5513        if let Some(kind) = kind {
5514            self.state.base_sync_recovery.stop.as_mut().unwrap().kind = kind.clone();
5515            if let Some(stop) = self.state.base_sync_recovery.stops.last_mut() {
5516                stop.kind = kind;
5517            }
5518        }
5519        self.state.save()?;
5520        Ok(true)
5521    }
5522
5523    /// Land the winner's tree on the current tip of `<remote>/<base>` before
5524    /// anything verifies it.
5525    ///
5526    /// `verify.e2e`, `verify.gate` and every reviewer in [`Self::review_loop`]
5527    /// read whatever is checked out in the winner's worktree. Left alone that
5528    /// tree stays rooted at `base_commit` - the base as [`resolve_base`] saw
5529    /// it when the run *branched* - and a run takes long enough that the base
5530    /// has usually moved by the time it gets here. A gate that ran there
5531    /// answers "green on the commit this run started from", not "green on
5532    /// what is about to land", and the difference showed up three times in
5533    /// one day as a green run whose merge would have reverted a file another
5534    /// pull request had already landed.
5535    ///
5536    /// Reuses [`crate::rebase::rebase_with_fixer`], the same routine
5537    /// `land::Step::Rebase` calls, rather than a second implementation of the
5538    /// same idea: a throwaway worktree, nothing runs in the primary tree, and
5539    /// a second rebase path is exactly the kind of drift `resolve_base`'s own
5540    /// doc warns about ("two answers to a question nobody notices until a
5541    /// diff is wrong").
5542    ///
5543    /// Foreign-checkout reviews instead merge the base into the owned shadow
5544    /// worktree, preserving the ancestry required for fast-forward delivery.
5545    /// A conflicting merge is aborted and held for operator resolution.
5546    ///
5547    /// A conflict is not the end of the road: the standing rebase is handed
5548    /// to the fixer seat, at most `graph.review_rounds` times, counted in
5549    /// `state.rebase_fixes` (so it survives a park/resume and is shared with
5550    /// land). Once it finishes, review and the gate run as usual on the
5551    /// rebased tree, which is where a breakage the new base caused is caught
5552    /// by the ordinary gate-fix round. magi resolves nothing itself.
5553    ///
5554    /// Two different bounds, easy to confuse: [`BASE_SYNC_ROUNDS`], counted in
5555    /// the current durable recovery interval, bounds how often the base is
5556    /// synchronized during active recovery (lifetime attempts remain evidence).
5557    /// `rebase_fixes` is how many times a *conflict* was given to a fixer. When the fixer cannot finish the
5558    /// rebase the branch is restored, `state.base_sync.conflict` is set with
5559    /// what was tried (rounds spent, paths still conflicted) and the branch
5560    /// and worktree stay exactly as they were - untouched, for a person to
5561    /// look at - which is also what makes re-entering this function
5562    /// afterwards a no-op instead of a second attempt at the same wall. A
5563    /// push failure ends the same way.
5564    async fn sync_to_base(&mut self) -> Result<()> {
5565        if self.state.status == RunStatus::AlreadyInBase {
5566            return Ok(());
5567        }
5568        self.hold_base_sync().await?;
5569        let conflicted = self
5570            .state
5571            .base_sync
5572            .as_ref()
5573            .is_some_and(|s| s.conflict.is_some());
5574        let Some(winner) = self.state.winner().cloned() else {
5575            return Ok(());
5576        };
5577
5578        crate::worktree_clean::resume_pending(&mut self.state, &winner.worktree).await?;
5579
5580        let repo = self.state.repo.clone();
5581        let remote = self.state.config.merge.remote.clone();
5582        let base_branch = self.state.base_branch.clone();
5583        let tracking = format!("{remote}/{base_branch}");
5584
5585        let fetched_base =
5586            matches!(git::fetch(&repo, &remote, &base_branch).await, Ok(o) if o.ok());
5587        // No network, or the remote never had this branch: the run already
5588        // started from a fetched `<remote>/<base>` (`resolve_base` refuses
5589        // otherwise), and one that got this far is not blocked by a fetch
5590        // that fails now. It just has no newer tip to compare against.
5591        let Ok(mut tip) = git::rev_parse(&repo, &tracking).await else {
5592            return Ok(());
5593        };
5594
5595        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
5596        self.state.ensure_base_episode();
5597        let mut pending = self
5598            .state
5599            .base_sync_recovery
5600            .operations
5601            .last()
5602            .filter(|o| !o.finished)
5603            .cloned();
5604        let scratch = self.state.dir().join("base-sync");
5605        if git::rebase_in_progress(&scratch).await {
5606            // Older resource stops predate operation reservations. Import the
5607            // standing Git operation, never retarget it to today's main.
5608            if pending.is_none()
5609                && self.state.base_sync_recovery.operations.is_empty()
5610                && !conflicted
5611                && crate::rebase::saved_base_identity(&scratch, &winner.branch)
5612                    .await
5613                    .ok()
5614                    .as_deref()
5615                    == Some(head.as_str())
5616                && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
5617                && git::is_clean(&winner.worktree).await?
5618            {
5619                let saved_tip = crate::rebase::rebase_target(&scratch).await?;
5620                if self.state.base_sync.is_none() {
5621                    self.state.base_sync = Some(BaseSync {
5622                        tip: saved_tip.clone(),
5623                        behind: 0,
5624                        attempts: 0,
5625                        conflict: None,
5626                        already_in: None,
5627                    });
5628                }
5629                self.state.reserve_base_operation(&head, &saved_tip);
5630                self.state.event(
5631                    "base-recovery",
5632                    "imported standing legacy rebase as a spent synchronization reservation",
5633                );
5634                self.state.save()?;
5635                pending = self.state.base_sync_recovery.operations.last().cloned();
5636            }
5637            let expected = pending.as_ref().map(|op| op.tip.as_str());
5638            if expected.is_none()
5639                || crate::rebase::rebase_target(&scratch).await.as_deref().ok() != expected
5640            {
5641                let why = "saved scratch rebase targets a different base; inspect the retained rebase before resuming";
5642                if self.state.base_sync.is_none() {
5643                    self.state.base_sync = Some(BaseSync {
5644                        tip: tip.clone(),
5645                        behind: 0,
5646                        attempts: 0,
5647                        conflict: None,
5648                        already_in: None,
5649                    });
5650                }
5651                self.state.base_sync.as_mut().unwrap().conflict = Some(why.into());
5652                self.state.event("land", why);
5653                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Unknown)
5654                    .await?;
5655                return Ok(());
5656            }
5657        }
5658        if let Some(op) = &pending {
5659            // A replay may add the pinned base's commits, never foreign work.
5660            let mut replay_proven =
5661                head == op.head || op.validated_head.as_deref() == Some(head.as_str());
5662            if !replay_proven && scratch.exists() && !git::rebase_in_progress(&scratch).await {
5663                let wait = repository_wait(&self.state, None);
5664                let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
5665                match crate::rebase::recover_completed_base(&self.state, &scratch, &winner.branch, op, &head).await {
5666                    Ok(true) => {
5667                        self.state.base_sync_recovery.operations.last_mut().unwrap().validated_head = Some(head.clone());
5668                        self.state.save()?;
5669                        git::worktree_remove(&repo, &scratch).await.ok();
5670                        replay_proven = true;
5671                    }
5672                    Ok(false) => self.state.event("base-recovery", "completed scratch failed result validation; retained for inspection"),
5673                    Err(error) => self.state.event("base-recovery", format!("completed scratch could not be validated; retained for inspection: {error:#}")),
5674                }
5675            }
5676            if !replay_proven && git::is_ancestor(&repo, &op.tip, &head).await {
5677                if self.state.foreign_checkout.is_some() {
5678                    replay_proven = git::rev_parse(&repo, &format!("{head}^1"))
5679                        .await
5680                        .ok()
5681                        .as_deref()
5682                        == Some(op.head.as_str())
5683                        && git::rev_parse(&repo, &format!("{head}^2"))
5684                            .await
5685                            .ok()
5686                            .as_deref()
5687                            == Some(op.tip.as_str());
5688                } else if crate::reconcile::origin_missing(&repo, &head, &op.head)
5689                    .await
5690                    .is_ok_and(|m| m.is_empty())
5691                    && let Ok(added) =
5692                        crate::reconcile::origin_missing(&repo, &op.head, &head).await
5693                {
5694                    replay_proven = true;
5695                    for commit in added {
5696                        if !git::is_ancestor(&repo, &commit, &op.tip).await {
5697                            replay_proven = false;
5698                            break;
5699                        }
5700                    }
5701                    replay_proven &= git::commits_ahead(&repo, &op.tip, &head).await?
5702                        <= git::commits_ahead(&repo, &op.tip, &op.head).await?;
5703                }
5704            }
5705            // Never retarget an operation across a crash, even if main moved.
5706            // sync_to_head resets and cleans with -x, so even ignored untracked
5707            // files must stop recovery independently of the old tracked tree.
5708            if git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
5709                || (head != op.head
5710                    && !git::git(&winner.worktree, &["ls-files", "--others", "-z"])
5711                        .await?
5712                        .is_empty())
5713                || (!git::is_clean(&winner.worktree).await?
5714                    && !git::git_raw(&winner.worktree, &["diff", "--quiet", &op.head])
5715                        .await
5716                        .is_ok_and(|o| o.ok()))
5717                || !replay_proven
5718            {
5719                let why = format!(
5720                    "unfinished base synchronization {} has unrecognized branch/worktree state; inspect the retained branch and scratch rebase before resuming",
5721                    op.id
5722                );
5723                let sync = self
5724                    .state
5725                    .base_sync
5726                    .as_mut()
5727                    .context("reserved synchronization has no lifetime accounting")?;
5728                sync.conflict = Some(why.clone());
5729                self.state.event("land", why);
5730                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Unknown)
5731                    .await?;
5732                return Ok(());
5733            }
5734            if head != op.head {
5735                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
5736            }
5737            tip = op.tip.clone();
5738        }
5739        let behind = git::commits_ahead(&repo, &head, &tip).await.unwrap_or(0);
5740        let attempts = self.state.base_sync.as_ref().map_or(0, |s| s.attempts);
5741        if pending.is_none()
5742            && !conflicted
5743            && fetched_base
5744            && self
5745                .state
5746                .base_sync_recovery
5747                .episodes
5748                .last()
5749                .is_some_and(|e| e.boundary.is_some())
5750            && let Some(task) = self.state.origin.as_ref().and_then(|o| o.task.clone())
5751            && let Ok(owner) = crate::queue::Queue::open().get(&task)
5752            && owner.execution_runs().last() == Some(&self.state.id)
5753            && owner.status != crate::queue::TaskStatus::Done
5754            && !owner.fresh_start
5755            && owner.review_branch.is_none()
5756            && crate::daemon::compatible_run_instruction(&self.state, &owner)
5757            && let Some(approval) = owner.resumption.as_ref()
5758            && approval.instruction == owner.instruction
5759            && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
5760            && git::is_clean(&winner.worktree).await?
5761            && self.state.renew_base_episode(&task, approval, &head, &tip)
5762        {
5763            self.state.event("base-recovery", "opened bounded synchronization interval after owner-approved infrastructure recovery");
5764            self.state.save()?;
5765        }
5766
5767        // Before any rebase, and before a recorded conflict is honoured: a
5768        // branch whose change reached the base under other commit ids has
5769        // nothing to rebase and nothing to conflict with, and a run that
5770        // already stopped on that phantom conflict recovers here on resume.
5771        // `behind == 0` with head == tip is a branch the base has since taken
5772        // in whole, whether or not a conflict was ever recorded: the ancestry
5773        // proof must still run (`classify` ignores a head still on the start
5774        // commit).
5775        if (behind > 0 || conflicted || head == tip)
5776            && self
5777                .settle_already_in(&winner.branch, &tip, &head, attempts, behind)
5778                .await?
5779        {
5780            return Ok(());
5781        }
5782        if conflicted && self.state.base_recovery_pending() {
5783            let authorization = self.state.base_sync_recovery.authorizations.last().unwrap();
5784            let owner =
5785                crate::queue::Queue::at(crate::run::home().join("queue")).get(&authorization.task);
5786            let owner_valid = owner.as_ref().is_ok_and(|t| {
5787                t.execution_runs().last() == Some(&self.state.id)
5788                    && t.status != crate::queue::TaskStatus::Done
5789                    && !t.fresh_start
5790                    && t.review_branch.is_none()
5791            });
5792            let invalidation = if !owner_valid {
5793                Some("latest task ownership changed")
5794            } else if !owner.as_ref().is_ok_and(|t| {
5795                authorization
5796                    .generation
5797                    .is_none_or(|g| t.resumption.as_ref().is_some_and(|r| r.generation == g))
5798            }) {
5799                Some("owner approval generation changed")
5800            } else if authorization.question.as_ref().is_some_and(|question| {
5801                !crate::base_recovery_control::decision_current(
5802                    &crate::queue::Queue::at(crate::run::home().join("queue")),
5803                    &self.state,
5804                    &authorization.task,
5805                    question,
5806                )
5807            }) {
5808                Some("recovery decision ownership, routing or stop evidence changed")
5809            } else if authorization.request.is_some()
5810                && !owner
5811                    .as_ref()
5812                    .is_ok_and(|t| t.operator_decided_at == authorization.decision)
5813            {
5814                Some("owner decision changed")
5815            } else if let Some(scope) = &authorization.scope {
5816                if scope.tip != tip {
5817                    Some("fetched base changed")
5818                } else if !self
5819                    .state
5820                    .base_sync_recovery
5821                    .episodes
5822                    .last()
5823                    .is_some_and(|e| e.id == scope.episode)
5824                {
5825                    Some("active synchronization interval changed")
5826                } else if !owner
5827                    .as_ref()
5828                    .is_ok_and(|t| t.instruction == scope.instruction)
5829                {
5830                    Some("task instruction changed")
5831                } else {
5832                    None
5833                }
5834            } else {
5835                None
5836            };
5837            if let Some(reason) = invalidation {
5838                let authorization = self
5839                    .state
5840                    .base_sync_recovery
5841                    .authorizations
5842                    .last_mut()
5843                    .unwrap();
5844                authorization.refuse(format!("{reason}; authorize again with --recover-base"));
5845                self.state.save()?;
5846                return Ok(());
5847            }
5848            if !fetched_base
5849                || git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
5850                || !git::is_clean(&winner.worktree).await?
5851                || !owner.is_ok_and(|t| t.execution_runs().last() == Some(&self.state.id))
5852            {
5853                return Ok(());
5854            }
5855        }
5856        let recovery = conflicted && self.state.consume_base_recovery(&head);
5857        if conflicted {
5858            // Consumption (including a refused changed HEAD) is durable before Git.
5859            self.state.save()?;
5860            if !recovery {
5861                return Ok(());
5862            }
5863        }
5864
5865        if behind == 0 {
5866            // A fixer-finished rebase moves the branch ref before the
5867            // winner's worktree is told (`sync_to_head` below). A run that
5868            // died in between resumes here with `behind == 0` and a tree still
5869            // holding the pre-rebase files, which review and the gate would
5870            // then read. That state is exactly: HEAD moved off the tip the
5871            // rebase started from, yet the tree is still identical to that
5872            // tip. A tree with edits of its own differs from it, so nothing
5873            // is thrown away.
5874            if let Some(from) = self
5875                .state
5876                .rebase_fixes
5877                .iter()
5878                .rev()
5879                .find_map(|r| r.from.clone())
5880                && from != head
5881                && git::git_raw(&winner.worktree, &["diff", "--quiet", &from])
5882                    .await
5883                    .is_ok_and(|o| o.ok())
5884            {
5885                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
5886            }
5887            // An earlier attempt may have rebased the branch locally and died
5888            // before pushing it (only the fresh-rebase arm below pushes).
5889            // Publish it now, so the plain push at PR time is not refused as
5890            // a non-fast-forward. A run already holding a recorded conflict
5891            // never reaches here; that case is out of scope.
5892            let conflict = self.publish_resumed_rebase(&winner.branch, &head).await;
5893            if let Some(why) = &conflict {
5894                self.state.status = RunStatus::Blocked;
5895                self.state.event("land", why.clone());
5896            }
5897            self.state.base_sync = Some(BaseSync {
5898                tip,
5899                behind: 0,
5900                attempts,
5901                conflict,
5902                already_in: None,
5903            });
5904            if pending.is_some() {
5905                self.state.finish_base_operation(Some(&head));
5906            }
5907            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Publication)
5908                .await?;
5909            self.state.save()?;
5910            return Ok(());
5911        }
5912
5913        if self.state.base_episode_used() >= BASE_SYNC_ROUNDS && pending.is_none() && !recovery {
5914            let why = format!(
5915                "{base_branch} moved {behind} commit(s) ahead of {} after {BASE_SYNC_ROUNDS} \
5916                 synchronization(s); synchronizing again would only race it",
5917                winner.branch
5918            );
5919            self.state.status = RunStatus::Blocked;
5920            self.state.base_sync = Some(BaseSync {
5921                tip,
5922                behind,
5923                attempts,
5924                conflict: Some(why.clone()),
5925                already_in: None,
5926            });
5927            self.state.event("land", why);
5928            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Exhausted)
5929                .await?;
5930            self.state.save()?;
5931            return Ok(());
5932        }
5933
5934        if self.state.foreign_checkout.is_some() {
5935            // Delivery to the operator's checkout is fast-forward only. A
5936            // rebase here would discard its saved head from our ancestry.
5937            let wait = repository_wait(&self.state, None);
5938            let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
5939            if self.state.base_sync.is_none() {
5940                self.state.base_sync = Some(BaseSync {
5941                    tip: tip.clone(),
5942                    behind,
5943                    attempts: 0,
5944                    conflict: None,
5945                    already_in: None,
5946                });
5947            }
5948            self.state.reserve_base_operation(&head, &tip);
5949            self.state.save()?;
5950            let merged = git::git_raw(
5951                &winner.worktree,
5952                &[
5953                    "-c",
5954                    "core.hooksPath=/dev/null",
5955                    "merge",
5956                    "--no-ff",
5957                    "--no-autostash",
5958                    "--no-edit",
5959                    "-m",
5960                    &format!("Merge {tracking} before verifying"),
5961                    &tip,
5962                ],
5963            )
5964            .await?;
5965            let conflict = if merged.ok() {
5966                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
5967                self.state.event(
5968                    "land",
5969                    format!("merged {tracking} into {} before verifying", winner.branch),
5970                );
5971                None
5972            } else {
5973                if git::rev_exists(&winner.worktree, "MERGE_HEAD").await {
5974                    git::git(&winner.worktree, &["merge", "--abort"]).await?;
5975                }
5976                let why = format!(
5977                    "could not merge {tracking} into {} without rewriting foreign checkout history: {}",
5978                    winner.branch,
5979                    merged.stderr.chars().take(600).collect::<String>()
5980                );
5981                self.state.status = RunStatus::Blocked;
5982                self.state.event("land", &why);
5983                Some(why)
5984            };
5985            let synced = conflict.is_none();
5986            let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
5987            self.state
5988                .finish_base_operation(synced.then_some(fresh.as_str()));
5989            let attempts = self.state.base_sync.as_ref().unwrap().attempts;
5990            self.state.base_sync = Some(BaseSync {
5991                tip,
5992                behind: if synced { 0 } else { behind },
5993                attempts,
5994                conflict,
5995                already_in: None,
5996            });
5997            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Conflict)
5998                .await?;
5999            self.state.save()?;
6000            return Ok(());
6001        }
6002
6003        self.state.event(
6004            "land",
6005            format!(
6006                "{base_branch} moved {behind} commit(s) ahead of {}; rebasing before verifying",
6007                winner.branch
6008            ),
6009        );
6010        self.state.save()?;
6011
6012        // The remote's copy of the branch, read now and only if the fetch
6013        // really succeeded (a stale tracking ref must never pin a lease). It is
6014        // pushed over after a rebase only when it is a commit this branch
6015        // already contains, by ancestry or by patch (an earlier rebase of ours
6016        // that never reached the remote): anything else is somebody else's work.
6017        let branch_tracking = format!("{remote}/{}", winner.branch);
6018        let fetched_branch = git::fetch(&repo, &remote, &winner.branch).await;
6019        let remote_tip = if self.state.task_pr_branch().is_none()
6020            && matches!(&fetched_branch, Ok(o) if o.ok())
6021        {
6022            git::rev_parse(&repo, &branch_tracking).await.ok()
6023        } else {
6024            None
6025        };
6026        // A remote tip this branch does not contain is somebody else's work:
6027        // rebasing would leave a local tip that can never be pushed. Stop
6028        // before touching anything and say so.
6029        if let Some(theirs) = &remote_tip
6030            && !git::is_ancestor(&repo, theirs, &head).await
6031            && !crate::reconcile::origin_missing(&repo, &head, theirs)
6032                .await
6033                .is_ok_and(|missing| missing.is_empty())
6034        {
6035            let why = format!(
6036                "{branch_tracking} ({}) has commits {} does not contain; not rebasing over \
6037                 them",
6038                short(theirs),
6039                winner.branch
6040            );
6041            self.state.status = RunStatus::Blocked;
6042            self.state.base_sync = Some(BaseSync {
6043                tip,
6044                behind,
6045                attempts,
6046                conflict: Some(why.clone()),
6047                already_in: None,
6048            });
6049            self.state.event("land", why);
6050            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Divergence)
6051                .await?;
6052            self.state.save()?;
6053            return Ok(());
6054        }
6055
6056        if self.state.base_sync.is_none() {
6057            self.state.base_sync = Some(BaseSync {
6058                tip: tip.clone(),
6059                behind,
6060                attempts: 0,
6061                conflict: None,
6062                already_in: None,
6063            });
6064        }
6065        let scratch = self.state.dir().join("base-sync");
6066        if let Err(error) = crate::rebase::prepare(&mut self.state, &scratch, &winner.branch).await
6067        {
6068            if error.is::<crate::repo_lock::ResourceBlocked>() {
6069                return Ok(());
6070            }
6071            return Err(error);
6072        }
6073        self.state.reserve_base_operation(&head, &tip);
6074        self.state.save()?;
6075        let rebased =
6076            match crate::rebase::rebase_prepared(&mut self.state, &scratch, &winner.branch, &tip)
6077                .await
6078            {
6079                Ok(crate::rebase::Rebased::Applied) => Ok(None),
6080                Ok(crate::rebase::Rebased::Stopped(why)) => Ok(Some(why)),
6081                Err(e) => Err(e),
6082            };
6083        let attempts = self.state.base_sync.as_ref().unwrap().attempts;
6084        let stop_kind = match &rebased {
6085            Ok(None) => crate::base_sync_recovery::StopKind::Publication,
6086            Ok(Some(_)) => crate::base_sync_recovery::StopKind::Conflict,
6087            Err(_) => crate::base_sync_recovery::StopKind::Unknown,
6088        };
6089        match rebased {
6090            Ok(None) => {
6091                // The branch ref moved, but a worktree that already had it
6092                // checked out (the winner's) was not told; sync its index and
6093                // files before anything reads them.
6094                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6095                let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
6096                self.state.finish_base_operation(Some(&fresh));
6097                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
6098                let mut conflict = None;
6099                if let Some(pinned) = &remote_tip {
6100                    let pushed = git::push_pinned(&repo, &remote, &winner.branch, pinned).await;
6101                    match pushed {
6102                        Ok(o) if o.ok() => self.state.event(
6103                            "land",
6104                            format!("pushed rebased {} to {remote}", winner.branch),
6105                        ),
6106                        Ok(o) => {
6107                            conflict = Some(format!(
6108                                "rebased {} locally but {remote} refused the push (it moved                                  since {}; someone may have pushed): {}",
6109                                winner.branch,
6110                                short(pinned),
6111                                o.stderr.chars().take(600).collect::<String>()
6112                            ));
6113                        }
6114                        Err(e) => {
6115                            conflict = Some(format!(
6116                                "rebased {} locally but could not push it: {e:#}",
6117                                winner.branch
6118                            ));
6119                        }
6120                    }
6121                }
6122                if let Some(why) = &conflict {
6123                    self.state.status = RunStatus::Blocked;
6124                    self.state.event("land", why.clone());
6125                }
6126                self.state.base_sync = Some(BaseSync {
6127                    tip: tip.clone(),
6128                    behind: 0,
6129                    attempts,
6130                    conflict,
6131                    already_in: None,
6132                });
6133                self.state
6134                    .event("land", format!("rebased {} onto {tracking}", winner.branch));
6135            }
6136            Ok(Some(conflict)) => {
6137                self.state.finish_base_operation(None);
6138                let why = format!(
6139                    "{} conflicts with {tracking} and did not rebase: {}",
6140                    winner.branch,
6141                    conflict.chars().take(600).collect::<String>()
6142                );
6143                self.state.status = RunStatus::Blocked;
6144                self.state.base_sync = Some(BaseSync {
6145                    tip,
6146                    behind,
6147                    attempts,
6148                    conflict: Some(why.clone()),
6149                    already_in: None,
6150                });
6151                self.state.event("land", why);
6152            }
6153            // A refused Git write or a busy repository: nothing is wrong with
6154            // the branch. The scratch rebase stays standing and the run
6155            // resumes into it (`base_sync` must not claim a conflict).
6156            Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
6157                self.state.save()?;
6158                return Ok(());
6159            }
6160            Err(e) => {
6161                self.state.finish_base_operation(None);
6162                let why = format!("could not rebase {} onto {tracking}: {e:#}", winner.branch);
6163                self.state.status = RunStatus::Blocked;
6164                self.state.base_sync = Some(BaseSync {
6165                    tip,
6166                    behind,
6167                    attempts,
6168                    conflict: Some(why.clone()),
6169                    already_in: None,
6170                });
6171                self.state.event("land", why);
6172            }
6173        }
6174        if !self.state.base_sync_blocked() {
6175            self.state.base_sync_recovery.stop = None;
6176        }
6177        self.hold_base_sync_kind(stop_kind).await?;
6178        self.state.save()?;
6179        Ok(())
6180    }
6181
6182    /// Push a branch an earlier attempt rebased locally but never published,
6183    /// pinned to the remote tip read right after a successful fetch. Returns
6184    /// the reason when the run must stop; `None` when there was nothing to do
6185    /// (no remote copy, the same tip, or a remote copy this branch already
6186    /// contains, which the PR-time push fast-forwards) or the push succeeded.
6187    async fn publish_resumed_rebase(&mut self, branch: &str, head: &str) -> Option<String> {
6188        // Task competitions publish only after the PR text gate, to their
6189        // public head; never resurrect a candidate branch on the remote.
6190        if self.state.task_pr_branch().is_some() {
6191            return None;
6192        }
6193        let repo = self.state.repo.clone();
6194        let remote = self.state.config.merge.remote.clone();
6195        let fetched = git::fetch(&repo, &remote, branch).await;
6196        if !matches!(&fetched, Ok(o) if o.ok()) {
6197            return None;
6198        }
6199        let branch_tracking = format!("{remote}/{branch}");
6200        let theirs = git::rev_parse(&repo, &branch_tracking).await.ok()?;
6201        if theirs == head || git::is_ancestor(&repo, &theirs, head).await {
6202            return None;
6203        }
6204        if !crate::reconcile::origin_missing(&repo, head, &theirs)
6205            .await
6206            .is_ok_and(|missing| missing.is_empty())
6207        {
6208            return Some(format!(
6209                "{branch_tracking} ({}) has commits {branch} does not contain; not pushing over \
6210                 them",
6211                short(&theirs)
6212            ));
6213        }
6214        match git::push_pinned(&repo, &remote, branch, &theirs).await {
6215            Ok(o) if o.ok() => {
6216                self.state
6217                    .event("land", format!("pushed rebased {branch} to {remote}"));
6218                None
6219            }
6220            Ok(o) => Some(format!(
6221                "{branch} is rebased locally but {remote} refused the push (it moved since {}; \
6222                 someone may have pushed): {}",
6223                short(&theirs),
6224                o.stderr.chars().take(600).collect::<String>()
6225            )),
6226            Err(e) => Some(format!(
6227                "{branch} is rebased locally but could not be pushed: {e:#}"
6228            )),
6229        }
6230    }
6231
6232    /// End the run as [`RunStatus::AlreadyInBase`] when `head`'s whole change
6233    /// is already on `tip` under other commit ids ([`crate::already`]); returns
6234    /// whether it did.
6235    ///
6236    /// Checked only when the base is ahead of the branch. A failing check is
6237    /// "not proven" - the ordinary rebase path then decides - never a reason to
6238    /// stop the run.
6239    ///
6240    /// The remote copy of the branch is held to the same standard as the local
6241    /// one: if it carries a tip this worktree does not, that tip must itself be
6242    /// proven in the base, or nothing is settled (a pull request would
6243    /// otherwise be closed over commits nobody checked). The pull request is
6244    /// closed *before* the terminal status is saved; if that fails for a
6245    /// reason other than a refusal (no network, a `gh` error) the run is left
6246    /// `Blocked` with the reason as its conflict, which a resume retries -
6247    /// the same recovery a phantom conflict gets.
6248    async fn settle_already_in(
6249        &mut self,
6250        branch: &str,
6251        tip: &str,
6252        head: &str,
6253        attempts: usize,
6254        behind: usize,
6255    ) -> Result<bool> {
6256        let repo = self.state.repo.clone();
6257        let remote = self.state.config.merge.remote.clone();
6258        let start = self.state.base_commit.clone();
6259        let evidence = match crate::already::classify(&repo, tip, head, Some(&start)).await {
6260            Ok(Some(e)) => e,
6261            Ok(None) => return Ok(false),
6262            Err(e) => {
6263                tracing::warn!("already-in-base check for {branch}: {e:#}");
6264                return Ok(false);
6265            }
6266        };
6267        let mut verified = vec![head.to_owned()];
6268        let public_branch = self.state.pr_branch().unwrap_or(branch).to_owned();
6269        let fetched = git::fetch(&repo, &remote, &public_branch).await;
6270        if matches!(&fetched, Ok(o) if o.ok())
6271            && let Ok(theirs) = git::rev_parse(&repo, &format!("{remote}/{public_branch}")).await
6272            && theirs != head
6273        {
6274            match crate::already::classify(&repo, tip, &theirs, Some(&start)).await {
6275                Ok(Some(_)) => verified.push(theirs),
6276                _ => return Ok(false),
6277            }
6278        }
6279        let base_branch = self.state.base_branch.clone();
6280        let message = format!(
6281            "{branch} is already in {remote}/{base_branch} as {} ({} match); nothing left to \
6282             land",
6283            evidence.names(),
6284            evidence.proof.as_str()
6285        );
6286        let closed =
6287            crate::land::close_superseded_pr(&mut self.state, &public_branch, &evidence, &verified)
6288                .await;
6289        match closed {
6290            Ok(Ok(url)) => self
6291                .state
6292                .event("land", format!("closed {url}: superseded on {base_branch}")),
6293            Ok(Err(why)) => self
6294                .state
6295                .event("land", format!("did not close a pull request: {why}")),
6296            Err(e) => {
6297                let why = format!(
6298                    "{branch} is already in {remote}/{base_branch}, but its pull request could \
6299                     not be closed ({e:#}); resume to retry"
6300                );
6301                self.state.status = RunStatus::Blocked;
6302                self.state.base_sync = Some(BaseSync {
6303                    tip: tip.to_owned(),
6304                    behind,
6305                    attempts,
6306                    conflict: Some(why.clone()),
6307                    already_in: None,
6308                });
6309                self.state.event("land", why);
6310                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::ClosingIntegratedPr)
6311                    .await?;
6312                self.state.save()?;
6313                return Ok(true);
6314            }
6315        }
6316        self.state.status = RunStatus::AlreadyInBase;
6317        self.state.base_sync_recovery.stop = None;
6318        self.state.base_sync = Some(BaseSync {
6319            tip: tip.to_owned(),
6320            behind,
6321            attempts,
6322            conflict: None,
6323            already_in: Some(evidence),
6324        });
6325        self.state.event("land", message);
6326        self.state.save()?;
6327        self.settle_questions();
6328        Ok(true)
6329    }
6330
6331    /// The commit review and gate diff against: the tip [`Self::sync_to_base`]
6332    /// last landed the winner on, once it has run, else the commit the run
6333    /// branched from.
6334    ///
6335    /// Only [`Self::review_loop`] reads this. `prep`, `judge`, `deliberate`
6336    /// and `vote` all happen before there is a winner to rebase, so they
6337    /// compare every candidate against the branch point on purpose, and a
6338    /// base that moves after they are already done cannot change an answer
6339    /// they already gave.
6340    fn landing_base(&self) -> String {
6341        self.state
6342            .base_sync
6343            .as_ref()
6344            .map_or_else(|| self.state.base_commit.clone(), |s| s.tip.clone())
6345    }
6346
6347    // ------------------------------------------------------- operator fix
6348
6349    /// Route specific, already-recorded review findings to a fixer for a
6350    /// targeted, out-of-band fix on the winning branch — `magi fix`'s own
6351    /// entry point.
6352    ///
6353    /// Distinct from `review_loop`'s own fix step in three ways: it never
6354    /// runs a reviewer wave, it never spends review-round budget, and what
6355    /// happened is recorded as an [`OperatorFixRequest`] appended to
6356    /// [`RunState::operator_fixes`], never folded into a [`ReviewRound`] —
6357    /// see `run::SCHEMA`'s doc for schema 9 on why a reviewer's own severity
6358    /// and vote must never be rewritten to look like a manufactured blocking
6359    /// verdict.
6360    ///
6361    /// Only meaningful once review has actually concluded: `Ready` (handed
6362    /// off with findings still open, or simply concluded clean while minor
6363    /// findings sat unaddressed) or `Blocked` (round budget spent, or the
6364    /// gate failed). Everything else is refused: a run still in progress
6365    /// should simply be resumed, and a `Merged` run's branch has already
6366    /// landed — reopening *this* run's own record cannot change that, so the
6367    /// answer there is a fresh `magi review <branch>`.
6368    ///
6369    /// A real commit here re-verifies through a fresh, ordinary review-only
6370    /// run on the same branch ([`Self::review`]) rather than reopening this
6371    /// run's own `review_loop`: once any round in this run's history went
6372    /// clean, `review_conclusion` treats that as permanent by design (the
6373    /// same purity `gate`/`merge` rely on for safe reentry), so there is no
6374    /// way to force one more genuine reviewer wave out of *this* run without
6375    /// either rewriting history or weakening that guarantee for every other
6376    /// caller. A review-only run costs nothing extra — no implementation, no
6377    /// judging, no vote — and exercises the exact same review → verify →
6378    /// gate → (human) merge path, unmodified.
6379    pub async fn fix_selected(
6380        &mut self,
6381        ids: &[String],
6382        reason: &str,
6383        allow_stale: bool,
6384    ) -> Result<()> {
6385        let reason = reason.trim();
6386        if reason.is_empty() {
6387            bail!("a fix request needs a reason — that is the operator's own record of why");
6388        }
6389        if ids.is_empty() {
6390            bail!("no finding id given");
6391        }
6392        if !matches!(self.state.status, RunStatus::Ready | RunStatus::Blocked) {
6393            bail!(
6394                "run {} is `{}`; only a `ready` or `blocked` run — one whose review \
6395                 has already concluded — can be given a targeted fix. A run still \
6396                 in progress should simply be resumed; a `merged` run's branch has \
6397                 already landed, so its answer is a fresh `magi review <branch>`, \
6398                 not reopening this run's own record",
6399                self.state.id,
6400                self.state.status.as_str()
6401            );
6402        }
6403        // Reassignment shares this claim through its atomic task save. Check
6404        // the canonical run identity inside it, before preflight or any await.
6405        let _claim = FixClaim::acquire(&self.state.dir())?;
6406        crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &self.state.id)?;
6407        let Some(winner) = self.state.winner().cloned() else {
6408            bail!("run {} has no winning candidate to fix", self.state.id);
6409        };
6410        if !git::branch_exists(&self.state.repo, &winner.branch).await? {
6411            bail!(
6412                "branch `{}` no longer exists; this run cannot be extended",
6413                winner.branch
6414            );
6415        }
6416        let home = crate::run::home();
6417        if crate::daemon::is_working_on(&home, &self.state.id, Timestamp::now()) {
6418            bail!(
6419                "run {} is currently being worked on by another magi process",
6420                self.state.id
6421            );
6422        }
6423        // Resolve every id before spending anything — an unknown id refuses
6424        // the whole request rather than silently dropping it — and dedup
6425        // while keeping the operator's own order.
6426        let mut seen = BTreeSet::new();
6427        let mut findings = Vec::new();
6428        let mut missing = Vec::new();
6429        for id in ids {
6430            if !seen.insert(id.clone()) {
6431                continue;
6432            }
6433            match self.state.finding(id) {
6434                Some((round, rec, f)) => findings.push(OperatorFixFinding {
6435                    id: f.id.clone(),
6436                    severity: f.severity,
6437                    reviewer_vote: rec.vote,
6438                    round: round.round,
6439                    round_head: round.head.clone(),
6440                    reviewer: rec.reviewer,
6441                    agent: rec.agent.clone(),
6442                    file: f.file.clone(),
6443                    line: f.line,
6444                    title: f.title.clone(),
6445                    detail: f.detail.clone(),
6446                    outcome: OperatorFixOutcome::Pending,
6447                }),
6448                None => missing.push(id.clone()),
6449            }
6450        }
6451        if !missing.is_empty() {
6452            bail!(
6453                "unknown finding id(s): {}; nothing was changed",
6454                missing.join(", ")
6455            );
6456        }
6457
6458        let head_at_request = git::rev_parse(&self.state.repo, &winner.branch).await?;
6459        let stale_details: Vec<(String, String)> = findings
6460            .iter()
6461            .filter(|f| f.round_head != head_at_request)
6462            .map(|f| (f.id.clone(), f.round_head.clone()))
6463            .collect();
6464        let stale = !stale_details.is_empty();
6465        if stale && !allow_stale {
6466            bail!(
6467                "the branch has moved since some finding(s) were raised — {} — now \
6468                 at {}; pass --allow-stale to fix anyway, or re-run review first",
6469                stale_details
6470                    .iter()
6471                    .map(|(id, head)| format!("{id} (raised against {})", short(head)))
6472                    .collect::<Vec<_>>()
6473                    .join(", "),
6474                short(&head_at_request)
6475            );
6476        }
6477
6478        let request = OperatorFixRequest {
6479            requested_at: Timestamp::now(),
6480            reason: reason.to_owned(),
6481            findings,
6482            head_at_request: head_at_request.clone(),
6483            allow_stale,
6484            stale,
6485            fix: None,
6486            result_head: None,
6487            follow_up_review_run: None,
6488        };
6489        self.state.event(
6490            "fix",
6491            format!(
6492                "operator requested a targeted fix on {} finding(s) ({}): {reason}",
6493                request.findings.len(),
6494                request
6495                    .findings
6496                    .iter()
6497                    .map(|f| f.id.as_str())
6498                    .collect::<Vec<_>>()
6499                    .join(", "),
6500            ),
6501        );
6502        // Recorded now, before any worktree work or the fixer call itself —
6503        // and re-saved at each checkpoint below: a crash at any point after
6504        // this (mid fixer call, mid follow-up review) must not lose the fact
6505        // that this was requested, for which findings, and why. Everything
6506        // past this point reads and writes through `request_index` rather
6507        // than a local variable, since `request` itself is moved here.
6508        self.state.operator_fixes.push(request);
6509        self.state.save()?;
6510        let request_index = self.state.operator_fixes.len() - 1;
6511
6512        // A fresh, dedicated worktree for this one call, never the winner's
6513        // own worktree in place: that one may already be gone (folded away),
6514        // and reusing it in place would leave the branch checked out there
6515        // when the follow-up review below tries to check it out again. Freed
6516        // immediately after, either way — but only once confirmed clean:
6517        // `worktree_remove` is a `git worktree remove --force`, which would
6518        // otherwise discard uncommitted work left there by the operator or
6519        // another process before this had a chance to even look at it.
6520        let repo = self.state.repo.clone();
6521        let coordination = self.coordinate(&repo).await?;
6522        if winner.worktree.exists() {
6523            // Lockfiles a rescue commit withheld stay untracked on purpose and
6524            // are already recorded; they are not the operator's work to protect.
6525            let dirty = git::git(
6526                &winner.worktree,
6527                &["status", "--porcelain", "--untracked-files=all"],
6528            )
6529            .await?;
6530            let only_withheld = dirty.lines().all(|l| {
6531                l.strip_prefix("?? ")
6532                    .is_some_and(|p| self.state.withheld.iter().any(|w| w.path == p))
6533            });
6534            if !only_withheld {
6535                bail!(
6536                    "`{}` has uncommitted changes; refusing to touch it — commit or \
6537                     discard them first",
6538                    winner.worktree.display()
6539                );
6540            }
6541            git::worktree_remove(&self.state.repo, &winner.worktree)
6542                .await
6543                .ok();
6544        }
6545        let fix_worktree = self.state.worktree_root().join("operator-fix");
6546        let fix_worktree_s = fix_worktree.to_string_lossy().to_string();
6547        git::git(
6548            &self.state.repo,
6549            &["worktree", "add", &fix_worktree_s, winner.branch.as_str()],
6550        )
6551        .await
6552        .with_context(|| format!("checking out `{}` for the fix", winner.branch))?;
6553        if !git::is_clean(&fix_worktree).await? {
6554            git::worktree_remove(&self.state.repo, &fix_worktree)
6555                .await
6556                .ok();
6557            bail!(
6558                "`{}` has uncommitted changes; refusing to start a fix on a dirty tree",
6559                winner.branch
6560            );
6561        }
6562        let repo_for_setup = self.state.repo.clone();
6563        let setup = match ensure_setup_config(&mut self.state, &repo_for_setup).await {
6564            Ok(()) => {
6565                worktree_setup::prepare_with(
6566                    &self.state.config,
6567                    &repo_for_setup,
6568                    &fix_worktree,
6569                    crate::build_target::Coordination::Held(coordination.as_ref()),
6570                )
6571                .await
6572            }
6573            Err(e) => Err(e),
6574        };
6575        if let Err(e) = setup {
6576            git::worktree_remove(&self.state.repo, &fix_worktree)
6577                .await
6578                .ok();
6579            return Err(e);
6580        }
6581
6582        // This explicit operator request retries availability independently
6583        // of execute(); the previous call has already saved and cleaned up.
6584        self.state.resource_block = None;
6585
6586        let run_id = self.state.id.clone();
6587        let prompts = self.state.config.prompts.clone();
6588        let language = self.state.config.graph.language.clone();
6589        let sessions = self.state.config.graph.sessions;
6590        let artifacts = agent::artifacts_dir(&self.state.dir());
6591        let finding_list: Vec<Finding> = self.state.operator_fixes[request_index]
6592            .findings
6593            .iter()
6594            .map(|f| Finding {
6595                id: f.id.clone(),
6596                severity: f.severity,
6597                file: f.file.clone(),
6598                line: f.line,
6599                title: f.title.clone(),
6600                detail: f.detail.clone(),
6601            })
6602            .collect();
6603        let fix_prompt = prompt::operator_fix_in(
6604            &self.state.instruction,
6605            &finding_list,
6606            reason,
6607            &stale_details,
6608            &head_at_request,
6609            &language,
6610            &self.state.config.graph.github_language,
6611        );
6612        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
6613        drop(coordination);
6614        let (job, seat, out) = self
6615            .ask_fixer(&winner, "fix", None, |spec, seat| SeatJob {
6616                prompt: fix_prompt.clone(),
6617                spec,
6618                seat,
6619                cwd: fix_worktree.clone(),
6620                timeout,
6621                allow_write: true,
6622                sessions,
6623                artifacts: artifacts.clone(),
6624                stem: "operator-fix".to_owned(),
6625                handover: None,
6626            })
6627            .await;
6628        let agent_id = seat.agent.clone();
6629
6630        let mut fix = FixRecord {
6631            agent: agent_id,
6632            addressed: Vec::new(),
6633            rejected: Vec::new(),
6634            notes: String::new(),
6635            committed: false,
6636            failed: None,
6637            duration_ms: 0,
6638            continuation: None,
6639        };
6640        let mut final_seat = seat.clone();
6641        match out {
6642            AgentOutcome::Ok(o) => {
6643                fix.duration_ms = o.duration_ms;
6644                let parsed = verdict::extract_json::<FixReport>(&o.text);
6645                let incomplete_reason = match &parsed {
6646                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
6647                        "the reply parsed, but it reported a command whose own CLI \
6648                         never confirmed an exit status"
6649                            .to_owned(),
6650                    ),
6651                    Ok(_) => None,
6652                    Err(e) => Some(e.to_string()),
6653                };
6654                match incomplete_reason {
6655                    None => {
6656                        let report = parsed.expect("checked Ok above");
6657                        fix.addressed = report.addressed;
6658                        fix.rejected = report.rejected;
6659                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
6660                    }
6661                    Some(reason) => {
6662                        let (resumed_seat, resolved, failure, cont) = self
6663                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, 0)
6664                            .await;
6665                        fix.duration_ms += cont.cumulative_wait_ms;
6666                        fix.continuation = Some(cont);
6667                        final_seat = resumed_seat;
6668                        match resolved {
6669                            Some(report) => {
6670                                fix.addressed = report.addressed;
6671                                fix.rejected = report.rejected;
6672                                fix.notes =
6673                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
6674                            }
6675                            None => fix.failed = failure,
6676                        }
6677                    }
6678                }
6679            }
6680            AgentOutcome::Dropped(o) => {
6681                fix.duration_ms = o.duration_ms;
6682                let why = o
6683                    .dropped
6684                    .as_ref()
6685                    .map(|d| d.why.as_str())
6686                    .unwrap_or("the CLI ended the stream without delivering its answer");
6687                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
6688            }
6689            AgentOutcome::Quota(o) => {
6690                self.state.quota.push(QuotaLoss::from_report(
6691                    final_seat.key.clone(),
6692                    "fix",
6693                    o.quota.as_ref(),
6694                ));
6695                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
6696            }
6697            AgentOutcome::Failed(e) => fix.failed = Some(e),
6698            AgentOutcome::ResourceBlocked(e) => {
6699                fix.failed = Some(format!("the fixer was not started: {e}"));
6700            }
6701        }
6702        // Even a deferred call must rescue edits, release the worktree and
6703        // finalize its record below so an explicit `magi fix` can retry.
6704        if fix.continuation.is_none() {
6705            fix.continuation = Some(ContinuationRecord::not_needed());
6706        }
6707        self.state.seats.insert(final_seat.key.clone(), final_seat);
6708
6709        let rescue_message = format!(
6710            "magi: operator-selected fix ({}) (uncommitted work)",
6711            self.state.operator_fixes[request_index]
6712                .findings
6713                .iter()
6714                .map(|f| f.id.as_str())
6715                .collect::<Vec<_>>()
6716                .join(", ")
6717        );
6718        let repo = self.state.repo.clone();
6719        let coordination = self.coordinate(&repo).await?;
6720        if let Ok(r) = git::rescue_commit(&fix_worktree, &rescue_message).await {
6721            self.state.note_withheld("fix", &r.withheld);
6722        }
6723        let after = git::rev_parse(&fix_worktree, "HEAD").await?;
6724        fix.committed = after != head_at_request;
6725        git::worktree_remove(&self.state.repo, &fix_worktree)
6726            .await
6727            .ok();
6728        drop(coordination);
6729
6730        self.state.event(
6731            "fix",
6732            match &fix.failed {
6733                Some(reason) => format!(
6734                    "operator fix: adoption report was lost ({reason}); {}",
6735                    if fix.committed {
6736                        "committed"
6737                    } else {
6738                        "NO new commit"
6739                    }
6740                ),
6741                None => format!(
6742                    "operator fix: {} addressed, {} rejected, {}",
6743                    fix.addressed.len(),
6744                    fix.rejected.len(),
6745                    if fix.committed {
6746                        "committed"
6747                    } else {
6748                        "NO new commit"
6749                    }
6750                ),
6751            },
6752        );
6753
6754        // Every selected finding gets an outcome — never left `Pending` once
6755        // the fixer's own turn is over. A report that never came back at all
6756        // marks every one of them `Unreported`, not silently "not addressed":
6757        // quota, a dropped stream, or an exhausted continuation are gaps in
6758        // the report, not evidence about the finding itself (see [`SCHEMA`]'s
6759        // doc for schema 9 and [`OperatorFixOutcome::Unreported`]).
6760        for f in &mut self.state.operator_fixes[request_index].findings {
6761            f.outcome = if fix.failed.is_some() {
6762                OperatorFixOutcome::Unreported
6763            } else if fix.addressed.contains(&f.id) {
6764                OperatorFixOutcome::Addressed
6765            } else if let Some(r) = fix.rejected.iter().find(|r| r.id == f.id) {
6766                OperatorFixOutcome::Rejected { why: r.why.clone() }
6767            } else {
6768                OperatorFixOutcome::Unreported
6769            };
6770        }
6771
6772        let committed = fix.committed;
6773        if committed {
6774            self.state.operator_fixes[request_index].result_head = Some(after.clone());
6775        }
6776        self.state.operator_fixes[request_index].fix = Some(fix);
6777        // Saved again now that the fixer's own outcome is final, on top of
6778        // the save right after the request was first pushed above.
6779        self.state.save()?;
6780        if self.state.resource_block.is_some() {
6781            return self.stop_for_resource();
6782        }
6783
6784        if committed {
6785            self.state.event(
6786                "fix",
6787                format!(
6788                    "operator fix committed {}; opening a follow-up review-only run",
6789                    short(&after)
6790                ),
6791            );
6792            // The operator asked for the fix, and the follow-up serves whatever
6793            // task the run it follows served.
6794            let origin =
6795                Origin::operator().serving(self.state.origin.as_ref().and_then(|o| o.task.clone()));
6796            match Self::review(
6797                &self.state.repo,
6798                &winner.branch,
6799                self.state.config.clone(),
6800                origin,
6801            )
6802            .await
6803            {
6804                Ok(mut follow_up) => {
6805                    follow_up.state.event(
6806                        "start",
6807                        format!(
6808                            "requested by an operator fix on run {} for finding(s) {}",
6809                            self.state.id,
6810                            self.state.operator_fixes[request_index]
6811                                .findings
6812                                .iter()
6813                                .map(|f| f.id.as_str())
6814                                .collect::<Vec<_>>()
6815                                .join(", "),
6816                        ),
6817                    );
6818                    follow_up.state.save()?;
6819                    let follow_up_id = follow_up.state.id.clone();
6820                    // The follow-up is a run like any other: it belongs to the
6821                    // task of the run it follows, or to one filed for it.
6822                    let adopted = match crate::direct::adopt(
6823                        &follow_up.state,
6824                        self.state.origin.as_ref().and_then(|o| o.task.as_deref()),
6825                    ) {
6826                        Ok(a) => a,
6827                        Err(e) => {
6828                            // An ownerless run must not spend agent calls; it
6829                            // stays saved, and `magi run --resume` adopts it.
6830                            self.state.event(
6831                                "fix",
6832                                format!(
6833                                    "follow-up review {follow_up_id} got no owning task and was not executed: {e:#}"
6834                                ),
6835                            );
6836                            self.state.save()?;
6837                            return Ok(());
6838                        }
6839                    };
6840                    let executed = follow_up.execute().await;
6841                    let failure = executed.as_ref().err().map(|e| format!("{e:#}"));
6842                    if let Some(a) = adopted {
6843                        a.finish(&follow_up.state, executed);
6844                    }
6845                    if let Some(e) = failure {
6846                        self.state.event(
6847                            "fix",
6848                            format!(
6849                                "follow-up review {follow_up_id} did not complete cleanly: {e:#}"
6850                            ),
6851                        );
6852                    }
6853                    self.state.operator_fixes[request_index].follow_up_review_run =
6854                        Some(follow_up_id);
6855                }
6856                Err(e) => {
6857                    self.state.event(
6858                        "fix",
6859                        format!("committed the fix but could not open a follow-up review: {e:#}"),
6860                    );
6861                }
6862            }
6863            self.state.save()?;
6864        }
6865
6866        Ok(())
6867    }
6868
6869    // --------------------------------------------------------------- review
6870
6871    /// Ask the fixer chain once for one fix call: the agents [`fixer::attempts`]
6872    /// names, in order, each at most once, moving on only when the call
6873    /// advances (an error, a quota hit or nothing usable - the same decision
6874    /// point `agent::chain_advances` is for the other chained roles).
6875    ///
6876    /// Each agent gets its own seat from `Runner::seat`: the same agent
6877    /// continues its conversation (the winner's own implementer seat when it
6878    /// is the winner's author, now that the competition is over), another
6879    /// takes a fresh one so the full prompt is sent again. A handover is
6880    /// recorded under `node`, which is what makes the fallback stick for the
6881    /// rest of the run (see `crate::fixer`). Only the last attempt's outcome
6882    /// is returned, so an exhausted chain reads exactly like a single failed
6883    /// fixer: one quota loss, the same wording, the same refund. An earlier
6884    /// attempt's edits are left in the tree and judged, with the final
6885    /// attempt's, by what git says afterwards.
6886    ///
6887    /// Returns the job that produced the outcome, for `continue_fix_report`.
6888    async fn ask_fixer(
6889        &mut self,
6890        winner: &Candidate,
6891        node: &'static str,
6892        round: Option<usize>,
6893        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
6894    ) -> (SeatJob, SeatState, AgentOutcome) {
6895        let attempts = fixer::attempts(&self.state, &self.roles, winner);
6896        self.ask_fixer_among(attempts, node, round, None, build)
6897            .await
6898    }
6899
6900    /// [`Self::ask_fixer`] over an explicit attempt list. `restore` is a
6901    /// worktree and a commit: before the next agent is asked after one that
6902    /// did not satisfy the call, the worktree is put back on that commit, so
6903    /// a failed agent's partial edits are not carried into the next one.
6904    async fn ask_fixer_among(
6905        &mut self,
6906        attempts: Vec<(AgentSpec, String)>,
6907        node: &'static str,
6908        round: Option<usize>,
6909        restore: Option<(&Path, &str)>,
6910        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
6911    ) -> (SeatJob, SeatState, AgentOutcome) {
6912        let run_id = self.state.id.clone();
6913        let prompts = self.state.config.prompts.clone();
6914        let cache = self.state.config.cache_dir();
6915        let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
6916        let mut last = None;
6917        for (i, (spec, key)) in attempts.into_iter().enumerate() {
6918            let seat = self.seat(&key, &spec.id);
6919            let mut job = build(spec.clone(), seat);
6920            if i > 0 {
6921                job.stem = format!("{}-{}", job.stem, spec.id);
6922            }
6923            let ctx = WaveCtx {
6924                carry_seats: false,
6925                pauses: Some((&self.pause, &self.interrupt)),
6926                run: &run_id,
6927                node,
6928                prompts: &prompts,
6929                cache: cache.as_deref(),
6930                round,
6931            };
6932            let (seat, out) =
6933                run_one(job.clone(), Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
6934            // A resource block never advances the chain: the chosen agent
6935            // was not asked, so it must be the one asked again on resume.
6936            let advances = match &out {
6937                AgentOutcome::Ok(o) => agent::output_advances(o),
6938                AgentOutcome::ResourceBlocked(_) => false,
6939                _ => true,
6940            };
6941            if let Some(next) = ids.get(i + 1)
6942                && advances
6943            {
6944                self.state.seats.insert(seat.key.clone(), seat.clone());
6945                let class =
6946                    FailClass::of(&out).unwrap_or_else(|| FailClass::Other("unusable".to_owned()));
6947                let reason = match &out {
6948                    AgentOutcome::Ok(_) => "nothing usable".to_owned(),
6949                    other => fail_reason(other),
6950                };
6951                // A failed agent's edits must not reach the next one, and a
6952                // restore that did not work ends the chain: the call fails
6953                // and the caller's own (confirmed) restore decides.
6954                if let Some((wt, rev)) = restore
6955                    && let Err(e) = self.graft_restore(wt, rev).await
6956                {
6957                    let why =
6958                        format!("could not restore the worktree before the next fixer: {e:#}");
6959                    tracing::warn!("{why}");
6960                    let out = if e.is::<crate::repo_lock::ResourceBlocked>() {
6961                        AgentOutcome::ResourceBlocked(why)
6962                    } else {
6963                        AgentOutcome::Failed(why)
6964                    };
6965                    last = Some((job, seat, out));
6966                    break;
6967                }
6968                record_handover(
6969                    &mut self.state,
6970                    node,
6971                    &seat.key,
6972                    &spec.id,
6973                    next,
6974                    &class,
6975                    &reason,
6976                );
6977                continue;
6978            }
6979            last = Some((job, seat, out));
6980            break;
6981        }
6982        let (job, seat, out) = last.expect("the fixer chain always has an entry");
6983        if let AgentOutcome::Quota(output) = &out
6984            && node != "graft"
6985        {
6986            // Graft is best effort: its caller records the loss and restores
6987            // the pre-graft tree, then proceeds to review and gate.
6988            // Every fallback was tried. Machine outages cannot be repaired by
6989            // spending a fix round; use each caller's resumable resource path.
6990            let loss = QuotaLoss::from_report(seat.key.clone(), node, output.quota.as_ref());
6991            block_machine_outage(&mut self.state, node, std::slice::from_ref(&loss));
6992            self.state.quota.push(loss);
6993            self.state.seats.insert(seat.key.clone(), seat.clone());
6994            self.state.status = RunStatus::Blocked;
6995            return (
6996                job,
6997                seat,
6998                AgentOutcome::ResourceBlocked(
6999                    "fixer unavailable; restore agent availability and resume".into(),
7000                ),
7001            );
7002        }
7003        (job, seat, out)
7004    }
7005
7006    /// The one repair a verification-only failure earns (see
7007    /// [`crate::recovery`]), before the first review round of a run that took
7008    /// a branch over.
7009    ///
7010    /// Saved as started *before* the fixer is called, so a resume never
7011    /// repairs twice; a start found on re-entry is rolled back to the commit
7012    /// it began from. A failed or unusable fixer leaves the tree as it was and
7013    /// the review goes on over it, so the first round's own verification
7014    /// reports the failure again. The failure is never carried into a round as
7015    /// a result: verification is re-run on whatever commit this leaves.
7016    async fn recovery_repair(&mut self, winner: &Candidate) -> Result<()> {
7017        use crate::recovery::{Mode, Repair};
7018        if !self.state.reviews.is_empty() {
7019            return Ok(());
7020        }
7021        let Some(mut rec) = self.state.recovery.clone() else {
7022            return Ok(());
7023        };
7024        if rec.mode != Mode::VerifyRepair {
7025            return Ok(());
7026        }
7027        let wt = winner.worktree.clone();
7028        let mut head = git::rev_parse(&wt, "HEAD").await?;
7029        match rec.repair.clone() {
7030            Repair::Done { .. } => return Ok(()),
7031            Repair::WaitingForRestore { before } => {
7032                self.graft_restore(&wt, &before).await?;
7033                head = before;
7034                rec.repair = Repair::NotStarted;
7035                self.state.recovery = Some(rec.clone());
7036                self.state.save()?;
7037            }
7038            Repair::Started { before } => {
7039                // Interrupted: the unfinished edits are not trusted.
7040                // An unconfirmed rollback blocks the run with `Started` kept,
7041                // so a resume retries it; the tree is never reviewed as is.
7042                if let Err(e) = self.graft_restore(&wt, &before).await {
7043                    if e.is::<crate::repo_lock::ResourceBlocked>() {
7044                        return Err(e);
7045                    }
7046                    return self
7047                        .stop_recovery(rec, &before, format!("interrupted; rollback failed: {e:#}"))
7048                        .await;
7049                }
7050                rec.repair = Repair::Done {
7051                    before: before.clone(),
7052                    after: before,
7053                    committed: false,
7054                    failed: Some("interrupted; rolled back".to_owned()),
7055                };
7056                self.state
7057                    .event("recovery", "the repair was interrupted and rolled back");
7058                self.state.recovery = Some(rec);
7059                self.state.save()?;
7060                return Ok(());
7061            }
7062            Repair::NotStarted => {}
7063        }
7064        if crate::recovery::recheck(&mut rec, &head) {
7065            self.state.event("recovery", rec.summary());
7066            self.state.recovery = Some(rec);
7067            self.state.save()?;
7068            return Ok(());
7069        }
7070        rec.repair = Repair::Started {
7071            before: head.clone(),
7072        };
7073        self.state.recovery = Some(rec.clone());
7074        self.state.save()?;
7075
7076        let language = self.state.config.graph.language.clone();
7077        let sessions = self.state.config.graph.sessions;
7078        let artifacts = agent::artifacts_dir(&self.state.dir());
7079        let fix_prompt = prompt::recovery_fix(
7080            &self.state.instruction,
7081            &rec,
7082            self.state.config.graph.review_rounds,
7083            &language,
7084        );
7085        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
7086        self.state.event(
7087            "recovery",
7088            format!(
7089                "repair: the fixer starts from the failed verification on {}",
7090                short(&head)
7091            ),
7092        );
7093        let (_job, seat, out) = self
7094            .ask_fixer(winner, "fix", None, |spec, seat| SeatJob {
7095                prompt: fix_prompt.clone(),
7096                spec,
7097                seat,
7098                cwd: wt.clone(),
7099                timeout,
7100                allow_write: true,
7101                sessions,
7102                artifacts: artifacts.clone(),
7103                stem: "fix-recovery".to_owned(),
7104                handover: None,
7105            })
7106            .await;
7107        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
7108            rec.repair = Repair::WaitingForRestore { before: head };
7109            self.state.recovery = Some(rec);
7110            return self.stop_for_resource();
7111        }
7112        let failed = match &out {
7113            AgentOutcome::Ok(_) | AgentOutcome::ResourceBlocked(_) => None,
7114            AgentOutcome::Quota(o) => {
7115                self.state.quota.push(QuotaLoss::from_report(
7116                    seat.key.clone(),
7117                    "fix",
7118                    o.quota.as_ref(),
7119                ));
7120                Some("rate limited (quota); the fixer could not run".to_owned())
7121            }
7122            AgentOutcome::Dropped(_) => Some("the CLI dropped the stream".to_owned()),
7123            AgentOutcome::Failed(e) => Some(e.clone()),
7124        };
7125        self.state.seats.insert(seat.key.clone(), seat);
7126        let coordination = self.coordinate(&wt).await?;
7127        let failed = match failed {
7128            // The agent's partial edits are not kept.
7129            Some(why) => {
7130                if let Err(e) = git::restore_to(&wt, &head).await {
7131                    return self
7132                        .stop_recovery(rec, &head, format!("{why}; restore failed: {e:#}"))
7133                        .await;
7134                }
7135                Some(why)
7136            }
7137            None => {
7138                if let Ok(r) = git::rescue_commit(
7139                    &wt,
7140                    "magi: recovery repair of the failed verification (uncommitted work)",
7141                )
7142                .await
7143                {
7144                    self.state.note_withheld("fix", &r.withheld);
7145                }
7146                None
7147            }
7148        };
7149        let after = git::rev_parse(&wt, "HEAD").await?;
7150        drop(coordination);
7151        self.state.event(
7152            "recovery",
7153            match &failed {
7154                Some(why) => format!("repair: nothing kept ({why})"),
7155                None if after != head => {
7156                    format!("repair: committed {}", short(&after))
7157                }
7158                None => "repair: the fixer made no commit".to_owned(),
7159            },
7160        );
7161        rec.repair = Repair::Done {
7162            before: head.clone(),
7163            committed: after != head,
7164            after,
7165            failed,
7166        };
7167        self.state.recovery = Some(rec);
7168        self.state.save()?;
7169        Ok(())
7170    }
7171
7172    /// A repair whose rollback could not be confirmed: the run is blocked and
7173    /// resumable, and the unconfirmed state is never reviewed.
7174    async fn stop_recovery(
7175        &mut self,
7176        mut rec: crate::recovery::RecoveryRecord,
7177        head: &str,
7178        why: String,
7179    ) -> Result<()> {
7180        // `Started` stays recorded: a resume retries the restore.
7181        rec.repair = crate::recovery::Repair::Started {
7182            before: head.to_owned(),
7183        };
7184        self.state.recovery = Some(rec);
7185        self.state
7186            .event("recovery", format!("repair could not be undone: {why}"));
7187        self.state.status = RunStatus::Blocked;
7188        self.state.save()?;
7189        bail!("recovery repair could not be rolled back: {why}")
7190    }
7191
7192    async fn review_loop(&mut self) -> Result<()> {
7193        if self.hold_base_sync().await? {
7194            return Ok(());
7195        }
7196        loop {
7197            if self
7198                .state
7199                .base_sync
7200                .as_ref()
7201                .is_some_and(|s| s.conflict.is_some())
7202            {
7203                return Ok(());
7204            }
7205            if self.catchup_repairable() {
7206                let record = self.state.reviews.last().expect("repairable round").clone();
7207                let winner = self
7208                    .state
7209                    .winner()
7210                    .cloned()
7211                    .context("catch-up repair has no winner")?;
7212                if !self.fix_review_round(&winner, record).await? {
7213                    return Ok(());
7214                }
7215            }
7216            self.review_loop_pass().await?;
7217            if !self.catchup_repairable() {
7218                return Ok(());
7219            }
7220        }
7221    }
7222
7223    /// Derive an owed catch-up repair from durable round evidence, including
7224    /// reentry after a crash before the fixer was dispatched.
7225    fn catchup_repairable(&self) -> bool {
7226        self.state.reviews.len() < self.state.config.graph.review_rounds
7227            && self.state.reviews.last().is_some_and(|r| {
7228                !r.clean
7229                    && r.blocking == 0
7230                    && r.fix.is_none()
7231                    && r.e2e_status() == E2eStatus::Failed
7232            })
7233    }
7234
7235    async fn review_loop_pass(&mut self) -> Result<()> {
7236        // A base that would not rebase is a person's decision, not a review
7237        // round: nothing here would change the answer, and reviewers and a
7238        // fixer would be spending real budget on a tree that cannot land
7239        // regardless of what they find.
7240        if self
7241            .state
7242            .base_sync
7243            .as_ref()
7244            .is_some_and(|s| s.conflict.is_some())
7245        {
7246            return Ok(());
7247        }
7248        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
7249        // agent files with `magi task add` name the run that paid for it. The
7250        // prompt overlay is cloned alongside it because the waves borrow it
7251        // while `self` is mutably borrowed by the node's own bookkeeping.
7252        let run_id = self.state.id.clone();
7253        let prompts = self.state.config.prompts.clone();
7254        let Some(winner) = self.state.winner().cloned() else {
7255            return Ok(());
7256        };
7257        let granted_review = self
7258            .state
7259            .repair_grants
7260            .last()
7261            .filter(|g| g.phase == crate::repair_budget::Phase::Reviewing)
7262            .cloned();
7263        let fresh_review = granted_review
7264            .as_ref()
7265            .is_some_and(|g| self.state.reviews.len() == g.review_start);
7266        let max_rounds = granted_review
7267            .as_ref()
7268            .map_or(self.state.config.graph.review_rounds, |g| {
7269                g.review_start.saturating_add(1)
7270            });
7271        // A clean round, an exhausted round budget, or a stalled tree (see
7272        // `STAGNANT_LIMIT`) are all already-decided conclusions the moment
7273        // they are recorded — recomputed here, not read off `status`, so a
7274        // reentry into a run that already stopped restates the identical
7275        // verdict instead of silently handing back whatever an earlier node
7276        // in this same walk clobbered `status` to (a solo-candidate
7277        // `judge`/`deliberate` skip rewrites it on every reentry). The loop
7278        // below runs an empty range once the budget is spent, and would
7279        // otherwise fall through without touching `status` at all.
7280        if let Some(status) =
7281            review_conclusion(&self.state.reviews, max_rounds).filter(|_| !fresh_review)
7282        {
7283            // A reentry after a crash between the last round's save and
7284            // `stop_reviewing` reaches the hand-off here, not there.
7285            if status == RunStatus::Gating {
7286                self.record_contested_handoff();
7287            }
7288            self.state.status = status;
7289            self.state.save()?;
7290            return Ok(());
7291        }
7292        self.state.status = RunStatus::Reviewing;
7293        // A last recorded round whose own verification never resolved
7294        // (`ResourceBlocked` — the shared build cache, not the patch) is
7295        // never a concluded round, whatever the round budget says: starting
7296        // a fresh round on top of it would spend a whole new reviewer wave
7297        // re-reading an unchanged patch instead of just retrying the one
7298        // check that actually needs it, and once the budget is spent the
7299        // loop below has nothing left to do at all (its range is empty).
7300        // Retry that check directly instead, exactly the same retry
7301        // `stop_reviewing` already does for its own catch-up case.
7302        if !fresh_review
7303            && self.state.reviews.last().is_some_and(|r| {
7304                r.e2e_status() == E2eStatus::ResourceBlocked
7305                    || (r.e2e_status() == E2eStatus::Deferred && r.blocking == 0 && r.fix.is_none())
7306            })
7307        {
7308            let shell = self.state.config.shell();
7309            return self
7310                .stop_unresolved_review(
7311                    "the last round's own verification never resolved",
7312                    &shell,
7313                    &winner.worktree,
7314                )
7315                .await;
7316        }
7317
7318        if granted_review.is_none() {
7319            self.recovery_repair(&winner).await?;
7320        }
7321        if self.resource_halt()? {
7322            return Ok(());
7323        }
7324
7325        let repo = self.state.repo.clone();
7326        let root = self.state.worktree_root();
7327        let language = self.state.config.graph.language.clone();
7328        let sessions = self.state.config.graph.sessions;
7329        let artifacts = self.merge_repair_artifacts();
7330        let base = self.landing_base();
7331        let base_short = short(&base);
7332        let reviewers = self.roles.reviewers.clone();
7333        let shell = self.state.config.shell();
7334
7335        for round in (self.state.reviews.len() + 1)..=max_rounds {
7336            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
7337            let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
7338            let stat = git::diff_stat(&winner.worktree, &base, "HEAD").await?;
7339            // The prior round's own record, already persisted — never a
7340            // hand-carried variable of just its failing output: that is
7341            // exactly what let a round's e2e result drift out of sync with
7342            // which commit it was actually about (see `SCHEMA`'s doc for
7343            // schema 8). Judged against `head`, the commit reviewers are
7344            // about to look at now, so the summary always reads as "an
7345            // earlier head" here — this round's own patch has not been
7346            // checked yet.
7347            let prev_verification = self
7348                .state
7349                .reviews
7350                .last()
7351                .and_then(|r| r.verification_summary(&head));
7352            // Only the first round of a run that took a branch over: later
7353            // rounds have this run's own history.
7354            let prior_section = match (&self.state.recovery, round) {
7355                (Some(rec), 1) if self.state.reviews.is_empty() => {
7356                    let since = match (rec.mode, rec.reviewed_head.as_deref()) {
7357                        (crate::recovery::Mode::VerifyRepair, Some(reviewed)) => {
7358                            Some(crate::recovery::head_of(
7359                                &git::diff(&winner.worktree, reviewed, "HEAD")
7360                                    .await
7361                                    .unwrap_or_default(),
7362                                crate::recovery::SINCE_DIFF_MAX,
7363                            ))
7364                        }
7365                        _ => None,
7366                    };
7367                    Some(prompt::recovery_review(rec, since.as_deref()))
7368                }
7369                _ => None,
7370            };
7371
7372            // Each reviewer gets its own detached checkout of exactly this
7373            // commit: nobody can perturb the winner's tree, and the fixer can
7374            // keep working without racing a reviewer.
7375            let mut jobs = Vec::new();
7376            let coordination = if self.state.config.worktree.pre_clean.is_empty() {
7377                self.coordinate(&repo).await?
7378            } else {
7379                None
7380            };
7381            for (r, spec) in reviewers.iter().cloned().enumerate() {
7382                let wt = root.join(format!("review-{}", r + 1));
7383                // `clean -fdx` in a reset wipes setup's products, so every
7384                // round sets the seat up again.
7385                if wt.exists() {
7386                    crate::worktree_clean::reset(&mut self.state, &wt, Some(&head)).await?;
7387                } else {
7388                    let _lease = if self.state.config.worktree.pre_clean.is_empty() {
7389                        None
7390                    } else {
7391                        self.coordinate(&repo).await?
7392                    };
7393                    git::worktree_add_detached(&repo, &wt, &head).await?;
7394                }
7395                let _setup_lease = if self.state.config.worktree.pre_clean.is_empty() {
7396                    None
7397                } else {
7398                    self.coordinate(&repo).await?
7399                };
7400                self.setup_seat_worktree(
7401                    &repo,
7402                    &wt,
7403                    false,
7404                    coordination.as_ref().or(_setup_lease.as_ref()),
7405                )
7406                .await?;
7407                let seat_key = format!("review-{}", r + 1);
7408                // The seat starts the round on whoever answered it last, not
7409                // on the agent the spec names, so a failure is not re-paid.
7410                let spec = pick_start_spec(
7411                    &self.roles.reviewer_roster,
7412                    spec,
7413                    self.state.seat_history.get(&seat_key),
7414                );
7415                let seat = self.seat(&seat_key, &spec.id);
7416                jobs.push(SeatJob {
7417                    prompt: prompt::review(&prompt::ReviewCtx {
7418                        instruction: &self.state.instruction,
7419                        branch: &winner.branch,
7420                        base_short: &base_short,
7421                        stat: &stat,
7422                        patch: &patch,
7423                        verification: prev_verification.as_ref(),
7424                        prior: prior_section.as_deref(),
7425                        reviewers: reviewers.len(),
7426                        round,
7427                        rounds: max_rounds,
7428                        // A review-only run has no rankings, so nothing
7429                        // competed for this patch and the reviewer is told so.
7430                        competed: self.state.tally.as_ref().is_some_and(|t| t.rankings > 0),
7431                        lens: Lens::for_seat(r),
7432                        language: &language,
7433                        github_language: &self.state.config.graph.github_language,
7434                    }),
7435                    spec,
7436                    seat,
7437                    cwd: wt,
7438                    timeout: Duration::from_secs(self.state.config.graph.timeout_review),
7439                    allow_write: false,
7440                    sessions,
7441                    artifacts: artifacts.clone(),
7442                    stem: format!("review-{round}-{}", r + 1),
7443                    handover: None,
7444                });
7445            }
7446
7447            drop(coordination);
7448            self.state.event(
7449                "review",
7450                format!(
7451                    "round {round}: {} reviewers on {}",
7452                    jobs.len(),
7453                    short(&head)
7454                ),
7455            );
7456            let mut quota_losses = Vec::new();
7457            let review_retries = self.state.config.graph.retries;
7458            let review_cache = self.state.config.cache_dir();
7459            let ctx = WaveCtx {
7460                carry_seats: true,
7461                pauses: Some((&self.pause, &self.interrupt)),
7462                run: &run_id,
7463                node: "review",
7464                prompts: &prompts,
7465                cache: review_cache.as_deref(),
7466                round: Some(round),
7467            };
7468            let results = ask_json_wave::<Review>(
7469                jobs,
7470                Arc::clone(&self.sem),
7471                review_retries,
7472                &self.roles.reviewer_roster,
7473                &ctx,
7474                &mut quota_losses,
7475                &mut self.state,
7476                &|_: &Review| Ok(()),
7477            )
7478            .await;
7479            if self.state.resource_block.is_some() {
7480                return self.stop_for_resource();
7481            }
7482            // Counted before the move below: how many of *this* round's
7483            // reviewer seats were lost to their own rate limit, as opposed to
7484            // a crash, a timeout, or unparsable output — see `round_is_clean`.
7485            let round_quota_missing = quota_losses.len();
7486            self.state.quota.extend(quota_losses);
7487
7488            let mut records = Vec::new();
7489            let mut all_findings = Vec::new();
7490            for (r, (seat, res, attempts)) in results.into_iter().enumerate() {
7491                let agent_id = seat.agent.clone();
7492                self.state.seats.insert(seat.key.clone(), seat);
7493                let mut record = ReviewRecord {
7494                    reviewer: r + 1,
7495                    agent: agent_id,
7496                    summary: String::new(),
7497                    findings: Vec::new(),
7498                    vote: None,
7499                    failed: None,
7500                    duration_ms: 0,
7501                    // Set for both outcomes: `failed: Some(_)` with
7502                    // `attempts > 0` is a seat every retry still lost, not a
7503                    // recovered one — only `failed: None` with `attempts > 0`
7504                    // reads as "answered after a nudge" (see this field's own
7505                    // doc).
7506                    attempts,
7507                };
7508                match res {
7509                    Ok((review, out)) => {
7510                        // Sanitized here, at the point every other piece of
7511                        // agent prose in this file is (candidate summaries,
7512                        // deliberation turns, vote reasons): a reviewer's own
7513                        // words are the one thing about it that could name
7514                        // it, and reconsideration below broadcasts this same
7515                        // summary and these same findings to every other
7516                        // seat on the panel.
7517                        record.summary =
7518                            blind::sanitize_prose(&review.summary, &self.state.config.blind);
7519                        record.vote = Some(review.vote);
7520                        record.duration_ms = out.duration_ms;
7521                        for (n, mut f) in review.findings.into_iter().enumerate() {
7522                            // ids are magi's, never the agent's: the fixer's
7523                            // adoption report is keyed by them.
7524                            f.id = format!("R{round}-{}-{}", r + 1, n + 1);
7525                            f.title = blind::sanitize_prose(&f.title, &self.state.config.blind);
7526                            f.detail = blind::sanitize_prose(&f.detail, &self.state.config.blind);
7527                            // `file` is agent-supplied prose too, never
7528                            // checked against the real tree — the same
7529                            // exposure `title`/`detail` above have, just in
7530                            // a field easy to forget because it looks like a
7531                            // path rather than free text.
7532                            f.file = f
7533                                .file
7534                                .map(|file| blind::sanitize_prose(&file, &self.state.config.blind));
7535                            all_findings.push(f.clone());
7536                            record.findings.push(f);
7537                        }
7538                        self.state.event(
7539                            "review",
7540                            format!(
7541                                "round {round}: reviewer {} voted {} with {} finding(s)",
7542                                r + 1,
7543                                review.vote.label(),
7544                                record.findings.len()
7545                            ),
7546                        );
7547                    }
7548                    Err(e) => {
7549                        record.failed = Some(e.to_string());
7550                        self.state.event(
7551                            "review",
7552                            format!("round {round}: reviewer {} produced nothing: {e}", r + 1),
7553                        );
7554                    }
7555                }
7556                records.push(record);
7557            }
7558
7559            // Tally the round's votes and, if they split, spend the one
7560            // round of reconsideration the split -> deliberate -> revote
7561            // shape `judge`/`vote` use for the panel, sized down to what a
7562            // read-only review round can afford: one round, and a revote
7563            // rather than an argument, because the panel already wrote its
7564            // reasoning down as findings the first time around.
7565            let initial_votes: Vec<ReviewVote> = records.iter().filter_map(|r| r.vote).collect();
7566            let vote_split =
7567                initial_votes.len() > 1 && !initial_votes.iter().all(|v| *v == initial_votes[0]);
7568            let mut reconsideration: Vec<ReviewRevoteRecord> = Vec::new();
7569            if vote_split {
7570                self.state.event(
7571                    "review",
7572                    format!(
7573                        "round {round}: votes split ({}) — one round of reconsideration",
7574                        initial_votes
7575                            .iter()
7576                            .map(|v| v.label())
7577                            .collect::<Vec<_>>()
7578                            .join(", ")
7579                    ),
7580                );
7581                // Seats read every seat's findings and votes, still numbered
7582                // and never named — the same anonymity `review` itself keeps.
7583                let panel: Vec<ReviewSeatReport<'_>> = records
7584                    .iter()
7585                    .filter_map(|r| {
7586                        r.vote.map(|vote| ReviewSeatReport {
7587                            reviewer: r.reviewer,
7588                            vote,
7589                            summary: &r.summary,
7590                            findings: &r.findings,
7591                        })
7592                    })
7593                    .collect();
7594
7595                let mut jobs = Vec::new();
7596                let mut seats_at = Vec::new();
7597                for (r, spec) in reviewers.iter().cloned().enumerate() {
7598                    // A seat with no initial vote has nothing to reconsider
7599                    // from and stays absent, the same as it stayed absent
7600                    // from `panel` above.
7601                    if records[r].vote.is_none() {
7602                        continue;
7603                    }
7604                    let wt = root.join(format!("review-{}", r + 1));
7605                    let seat_key = format!("review-{}", r + 1);
7606                    let spec = self.occupant(&seat_key, spec);
7607                    let seat = self.seat(&seat_key, &spec.id);
7608                    // A seat with no live session has already forgotten the
7609                    // initial review's prompt — restate the patch it is
7610                    // voting on, the same as `deliberate`/`vote` do for a
7611                    // judge in the same position.
7612                    // The panel already carries this seat's own review and
7613                    // vote, so restating the patch makes the prompt whole for
7614                    // a seat handed to another agent.
7615                    let build = |with_patch: bool| {
7616                        prompt::review_reconsider(&ReviewReconsiderCtx {
7617                            instruction: &self.state.instruction,
7618                            reviewer: r + 1,
7619                            lens: Lens::for_seat(r),
7620                            panel: &panel,
7621                            patch: with_patch.then_some(ReviewPatch {
7622                                branch: &winner.branch,
7623                                base_short: &base_short,
7624                                stat: &stat,
7625                                patch: &patch,
7626                            }),
7627                            round,
7628                            rounds: max_rounds,
7629                            language: &language,
7630                        })
7631                    };
7632                    let full = build(true);
7633                    let prompt = if has_context(&spec, &seat, sessions) {
7634                        build(false)
7635                    } else {
7636                        full.clone()
7637                    };
7638                    jobs.push(SeatJob {
7639                        prompt,
7640                        spec,
7641                        seat,
7642                        cwd: wt,
7643                        timeout: Duration::from_secs(self.state.config.graph.timeout_review),
7644                        allow_write: false,
7645                        sessions,
7646                        artifacts: artifacts.clone(),
7647                        stem: format!("review-{round}-reconsider-{}", r + 1),
7648                        handover: Some(full),
7649                    });
7650                    seats_at.push(r);
7651                }
7652
7653                let mut recon_quota_losses = Vec::new();
7654                let recon_cache = self.state.config.cache_dir();
7655                let recon_ctx = WaveCtx {
7656                    carry_seats: true,
7657                    pauses: Some((&self.pause, &self.interrupt)),
7658                    run: &run_id,
7659                    node: "review",
7660                    prompts: &prompts,
7661                    cache: recon_cache.as_deref(),
7662                    round: Some(round),
7663                };
7664                let recon_results = ask_json_wave::<ReviewRevote>(
7665                    jobs,
7666                    Arc::clone(&self.sem),
7667                    review_retries,
7668                    &self.roles.reviewer_roster,
7669                    &recon_ctx,
7670                    &mut recon_quota_losses,
7671                    &mut self.state,
7672                    &|_: &ReviewRevote| Ok(()),
7673                )
7674                .await;
7675                if self.state.resource_block.is_some() {
7676                    return self.stop_for_resource();
7677                }
7678                self.state.quota.extend(recon_quota_losses);
7679
7680                for (&r, (seat, res, _attempts)) in seats_at.iter().zip(recon_results) {
7681                    let agent_id = seat.agent.clone();
7682                    self.state.seats.insert(seat.key.clone(), seat);
7683                    let mut rec = ReviewRevoteRecord {
7684                        reviewer: r + 1,
7685                        agent: agent_id,
7686                        vote: None,
7687                        reason: String::new(),
7688                        failed: None,
7689                    };
7690                    match res {
7691                        Ok((rv, _)) => {
7692                            rec.vote = Some(rv.vote);
7693                            rec.reason =
7694                                blind::sanitize_prose(&rv.reason, &self.state.config.blind);
7695                            self.state.event(
7696                                "review",
7697                                format!(
7698                                    "round {round}: reviewer {} revoted {}",
7699                                    r + 1,
7700                                    rv.vote.label()
7701                                ),
7702                            );
7703                        }
7704                        Err(e) => {
7705                            rec.failed = Some(e.to_string());
7706                            self.state.event(
7707                                "review",
7708                                format!("round {round}: reviewer {} did not revote: {e}", r + 1),
7709                            );
7710                        }
7711                    }
7712                    reconsideration.push(rec);
7713                }
7714            } else if initial_votes.len() > 1 {
7715                self.state.event(
7716                    "review",
7717                    format!(
7718                        "round {round}: votes agreed ({}) — no reconsideration",
7719                        initial_votes[0].label()
7720                    ),
7721                );
7722            }
7723
7724            let blocking = all_findings.iter().filter(|f| f.severity.blocks()).count();
7725            let verify_timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
7726            // A round that already has a blocking finding and a round left to
7727            // try is going back to the fixer no matter what `verify.e2e`
7728            // says, so running it first only spends the loop's slowest step
7729            // (minutes, for a Rust repo's full test suite) on a head about
7730            // to be rewritten. Deferred, never skipped: `verify.e2e` still
7731            // runs once a round has no blocking findings left (see
7732            // `round_is_clean`, which a deferred — empty — `e2e` can never
7733            // satisfy since `blocking` is nonzero whenever this branch is
7734            // taken), and `stop_reviewing` forces a real run before it will
7735            // ever read a deferred round as green.
7736            let defer_e2e =
7737                blocking > 0 && round < max_rounds && !self.state.config.graph.e2e_every_round;
7738            let (e2e, verify_retried, e2e_deferred, e2e_defer_reason) = if defer_e2e {
7739                let reason =
7740                    format!("{blocking} blocking finding(s) already required a fix this round");
7741                self.state.event(
7742                    "verify",
7743                    format!(
7744                        "round {round}: {reason} — e2e deferred to the fixer (reviewed head \
7745                         {}); it will run once a round has none left",
7746                        short(&head)
7747                    ),
7748                );
7749                (Vec::new(), false, true, Some(reason))
7750            } else {
7751                let e2e_commands = self.state.config.verify.e2e.clone();
7752                let cache_dir = self.state.config.cache_dir();
7753                let context = format!("round {round}");
7754                let wait = self.repository_wait();
7755                let (e2e, verify_retried) = with_cache_lease(
7756                    &mut self.state,
7757                    cache_dir.as_deref(),
7758                    "e2e",
7759                    "e2e",
7760                    &winner.worktree,
7761                    &head,
7762                    verify_timeout,
7763                    &context,
7764                    &wait,
7765                    |state, budget| {
7766                        let shell = shell.clone();
7767                        let e2e_commands = e2e_commands.clone();
7768                        let worktree = winner.worktree.clone();
7769                        let context = context.clone();
7770                        let winner = winner.clone();
7771                        async move {
7772                            if !e2e_commands.is_empty() {
7773                                // The suite certifies one SHA. Format before it
7774                                // runs, or the commit `pre_gate` makes at the
7775                                // gate owes the whole suite again.
7776                                Self::run_pre_gate(state, &winner).await;
7777                            }
7778                            run_e2e_with_retry(
7779                                state,
7780                                &shell,
7781                                &e2e_commands,
7782                                &worktree,
7783                                budget,
7784                                &context,
7785                                Some(round),
7786                            )
7787                            .await
7788                        }
7789                    },
7790                )
7791                .await?;
7792                (e2e, verify_retried, false, None)
7793            };
7794
7795            let expected = records.len();
7796            let answered = records.iter().filter(|r| r.failed.is_none()).count();
7797            let incomplete = answered < expected;
7798            let e2e_ok = e2e.iter().all(CommandOutcome::ok);
7799            let policy = self.state.config.graph.incomplete_review;
7800            let clean = round_is_clean(
7801                blocking,
7802                e2e_ok,
7803                answered,
7804                expected,
7805                round_quota_missing,
7806                policy,
7807            );
7808
7809            let mut round_record = ReviewRound {
7810                round,
7811                head: head.clone(),
7812                verified_head: None,
7813                verified_at: None,
7814                reviews: records,
7815                e2e,
7816                verify_retried,
7817                e2e_deferred,
7818                e2e_defer_reason,
7819                fix: None,
7820                blocking,
7821                answered,
7822                expected,
7823                clean,
7824                progressed: false,
7825                vote_split,
7826                reconsideration,
7827                verdict: None,
7828            };
7829            // The final vote per seat is its revote where reconsideration
7830            // ran and answered, its initial vote otherwise — the same
7831            // fallback `tally` uses for a judge whose private vote failed.
7832            round_record.verdict = ReviewVote::worst(
7833                round_record
7834                    .final_votes()
7835                    .into_iter()
7836                    .map(|(_, _, vote)| vote),
7837            );
7838            // Which commit and when magi actually attempted to check —
7839            // known the moment a command was dispatched against `head`,
7840            // whether or not it finished: a resource-blocked attempt still
7841            // targeted a specific commit at a specific time, and leaving
7842            // that unrecorded is exactly what made `verification_summary`
7843            // report a fresh attempt as "commit unknown ... recorded before
7844            // this was tracked", indistinguishable from a genuinely old,
7845            // untracked record. Only a deferred or unconfigured round never
7846            // ran at all and has nothing to record — see
7847            // `ReviewRound::verified_head`'s own doc.
7848            if !matches!(
7849                round_record.e2e_status(),
7850                E2eStatus::Deferred | E2eStatus::NotConfigured
7851            ) {
7852                // HEAD, not the reviewed `head`: `pre_gate` may have committed
7853                // mechanical fixes before the commands ran.
7854                round_record.verified_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
7855                round_record.verified_at = Some(Timestamp::now());
7856            }
7857
7858            if incomplete {
7859                let missing: Vec<String> = round_record
7860                    .reviews
7861                    .iter()
7862                    .filter(|r| r.failed.is_some())
7863                    .map(|r| format!("review-{}", r.reviewer))
7864                    .collect();
7865                self.state.event(
7866                    "review",
7867                    format!(
7868                        "round {round}: {answered}/{expected} reviewer(s) answered ({} never answered)",
7869                        missing.join(", ")
7870                    ),
7871                );
7872            }
7873
7874            if clean {
7875                self.state.event(
7876                    "review",
7877                    if incomplete && policy == IncompleteReviewPolicy::Warn {
7878                        format!(
7879                            "round {round}: clean (warn policy, incomplete panel) — no \
7880                             blocking findings from the seats that answered, verification green"
7881                        )
7882                    } else if incomplete {
7883                        format!(
7884                            "round {round}: clean ({} rate-limited reviewer(s) excluded from \
7885                             quorum) — no blocking findings from the seats that answered, \
7886                             verification green",
7887                            expected - answered
7888                        )
7889                    } else {
7890                        format!("round {round}: clean — no blocking findings, verification green")
7891                    },
7892                );
7893                self.state.reviews.push(round_record);
7894                self.state.status = RunStatus::Gating;
7895                self.state.save()?;
7896                return Ok(());
7897            }
7898
7899            // Nothing was raised and verification passed, but not every seat
7900            // answered and `round_is_clean` still refused to call it clean —
7901            // either a seat is missing for a reason other than its own quota
7902            // (a crash, a timeout, unparsable output — worth another try), or
7903            // every seat that could have answered lost its quota and nobody
7904            // is left to decide on: re-review rather than send the fixer
7905            // after a round with nothing to fix.
7906            if incomplete && blocking == 0 && e2e_ok {
7907                self.state.reviews.push(round_record);
7908                self.state.save()?;
7909                if round == max_rounds {
7910                    self.state.status = RunStatus::Blocked;
7911                    self.state.event(
7912                        "review",
7913                        format!(
7914                            "{} reviewer seat(s) never answered after {max_rounds} rounds; \
7915                             refusing to call it clean",
7916                            expected - answered
7917                        ),
7918                    );
7919                    return Ok(());
7920                }
7921                continue;
7922            }
7923
7924            // Nothing for the fixer to act on (`blocking == 0`) and the only
7925            // reason this round is not clean is that magi itself never got
7926            // a command to run — the shared build cache, not the patch (see
7927            // `CommandOutcome::resource_blocked`'s own doc). Sending that to
7928            // the fixer would invite a change to appease contention that has
7929            // nothing to do with the diff, and would leave this attempt
7930            // sitting in the next round's prompt as if it were about an
7931            // earlier, superseded commit rather than what it actually is:
7932            // the same head, still waiting to be checked. Wait for it the
7933            // same way the final round's own contention is already handled,
7934            // whatever round this happens to be.
7935            if blocking == 0 && round_record.e2e_status() == E2eStatus::ResourceBlocked {
7936                self.state.reviews.push(round_record);
7937                return self
7938                    .stop_unresolved_review(
7939                        "the round's own verification could not run",
7940                        &shell,
7941                        &winner.worktree,
7942                    )
7943                    .await;
7944            }
7945
7946            if round == max_rounds {
7947                self.state.reviews.push(round_record);
7948                return self
7949                    .stop_reviewing(
7950                        &format!(
7951                            "{blocking} blocking finding(s) still open after {max_rounds} round(s)"
7952                        ),
7953                        &shell,
7954                        &winner.worktree,
7955                    )
7956                    .await;
7957            }
7958
7959            if !self.fix_review_round(&winner, round_record).await? {
7960                return Ok(());
7961            }
7962        }
7963        Ok(())
7964    }
7965
7966    /// Run the same fix chain for an in-loop failure or a persisted catch-up failure.
7967    /// False means admission or continuation policy stopped the review loop.
7968    async fn fix_review_round(
7969        &mut self,
7970        winner: &Candidate,
7971        mut round_record: ReviewRound,
7972    ) -> Result<bool> {
7973        let round = round_record.round;
7974        let shell = self.state.config.shell();
7975        let step = self.run_fix_round(winner, &mut round_record).await?;
7976        if matches!(step, FixStep::Resource) {
7977            self.stop_for_resource()?;
7978            return Ok(false);
7979        }
7980        if self.state.reviews.len() < round {
7981            self.state.reviews.push(round_record);
7982        } else {
7983            self.state.reviews[round - 1] = round_record;
7984        }
7985        self.state.save()?;
7986
7987        // The fixer's own report never came back this round, even after
7988        // `continue_fix_report`'s own budget was spent on it — not an
7989        // ordinary "no report" (dropped stream, quota, plain failure),
7990        // which already reads that way and is left to the existing round
7991        // budget. Stopping here, rather than opening another round, is
7992        // what keeps a next reviewer/fixer wave from ever being
7993        // dispatched onto `winner.worktree` while whatever the seat's
7994        // last call may still have running there is unaccounted for: no
7995        // process liveness check exists (and none is being added — see
7996        // AGENTS.md/this task's own scope), so the only way to honour
7997        // "nothing starts before a valid report returns" is to not start
7998        // anything further on this worktree from this run at all.
7999        if matches!(step, FixStep::Recorded { report_lost: true }) {
8000            self.stop_reviewing(
8001                "the fixer's adoption report never came back, even after resuming its \
8002                         own seat; refusing to start another round against the same worktree \
8003                         while that is unresolved",
8004                &shell,
8005                &winner.worktree,
8006            )
8007            .await?;
8008            return Ok(false);
8009        }
8010
8011        let streak = self
8012            .state
8013            .reviews
8014            .iter()
8015            .rev()
8016            .take_while(|r| !r.progressed)
8017            .count();
8018        if streak >= STAGNANT_LIMIT {
8019            self.stop_reviewing(
8020                &format!("the tree has not moved against base for {streak} round(s) in a row"),
8021                &shell,
8022                &winner.worktree,
8023            )
8024            .await?;
8025            return Ok(false);
8026        }
8027        Ok(true)
8028    }
8029
8030    /// Execute the shared fixer chain; the caller owns persistence and stop policy.
8031    async fn run_fix_round(
8032        &mut self,
8033        winner: &Candidate,
8034        round_record: &mut ReviewRound,
8035    ) -> Result<FixStep> {
8036        let round = round_record.round;
8037        let max_rounds = self.state.config.graph.review_rounds;
8038        let run_id = self.state.id.clone();
8039        let prompts = self.state.config.prompts.clone();
8040        let language = self.state.config.graph.language.clone();
8041        let sessions = self.state.config.graph.sessions;
8042        let artifacts = self.merge_repair_artifacts();
8043        let base = self.landing_base();
8044        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
8045        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
8046        let this_round_verification = round_record.verification_summary(&head);
8047        let all_findings: Vec<_> = round_record
8048            .reviews
8049            .iter()
8050            .flat_map(|r| r.findings.iter().cloned())
8051            .collect();
8052        // Fix. The winner's own implementer seat continues its conversation:
8053        // the competition is over, so context is pure benefit now.
8054        let blocking_findings: Vec<_> = all_findings
8055            .iter()
8056            .filter(|f| f.severity.blocks())
8057            .cloned()
8058            .collect();
8059        let fix_prompt = prompt::fix_in(
8060            &self.state.instruction,
8061            &blocking_findings,
8062            this_round_verification.as_ref(),
8063            round,
8064            max_rounds,
8065            &language,
8066            &self.state.config.graph.github_language,
8067        );
8068        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
8069        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
8070        let (job, seat, out) = self
8071            .ask_fixer(winner, "fix", Some(round), |spec, seat| SeatJob {
8072                prompt: fix_prompt.clone(),
8073                spec,
8074                seat,
8075                cwd: winner.worktree.clone(),
8076                timeout,
8077                allow_write: true,
8078                sessions,
8079                artifacts: artifacts.clone(),
8080                stem: format!("fix-{round}"),
8081                handover: None,
8082            })
8083            .await;
8084        // Not asked: the round is not recorded (so a resume repeats it),
8085        // no fixer was handed over to, and the seat is left as it was.
8086        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
8087            return Ok(FixStep::Resource);
8088        }
8089        let agent_id = seat.agent.clone();
8090
8091        let mut fix = FixRecord {
8092            agent: agent_id,
8093            addressed: Vec::new(),
8094            rejected: Vec::new(),
8095            notes: String::new(),
8096            committed: false,
8097            failed: None,
8098            duration_ms: 0,
8099            continuation: None,
8100        };
8101        let mut continuation = ContinuationRecord::not_needed();
8102        let mut final_seat = seat.clone();
8103        match out {
8104            AgentOutcome::Ok(o) => {
8105                fix.duration_ms = o.duration_ms;
8106                let parsed = verdict::extract_json::<FixReport>(&o.text);
8107                // A parsed report standing next to a command this same
8108                // reply's own CLI never confirmed the exit status of is
8109                // not a resolved answer — the identical `CommandEvidence`
8110                // `state.jobs` renders, read here instead of only on
8111                // display, per the completion judgment and the shown
8112                // record needing to agree.
8113                let incomplete_reason = match &parsed {
8114                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
8115                        "the reply parsed, but it reported a command whose own CLI never \
8116                             confirmed an exit status"
8117                            .to_owned(),
8118                    ),
8119                    Ok(_) => None,
8120                    Err(e) => Some(e.to_string()),
8121                };
8122                match incomplete_reason {
8123                    None => {
8124                        let report = parsed.expect("checked Ok above");
8125                        fix.addressed = report.addressed;
8126                        fix.rejected = report.rejected;
8127                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
8128                    }
8129                    Some(reason) => {
8130                        let (resumed_seat, resolved, failure, cont) = self
8131                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, round)
8132                            .await;
8133                        fix.duration_ms += cont.cumulative_wait_ms;
8134                        continuation = cont;
8135                        final_seat = resumed_seat;
8136                        match resolved {
8137                            Some(report) => {
8138                                fix.addressed = report.addressed;
8139                                fix.rejected = report.rejected;
8140                                fix.notes =
8141                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
8142                            }
8143                            None => fix.failed = failure,
8144                        }
8145                    }
8146                }
8147            }
8148            // The CLI's raw error JSON is not a fix report to parse.
8149            AgentOutcome::Dropped(o) => {
8150                fix.duration_ms = o.duration_ms;
8151                let why = o
8152                    .dropped
8153                    .as_ref()
8154                    .map(|d| d.why.as_str())
8155                    .unwrap_or("the CLI ended the stream without delivering its answer");
8156                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
8157            }
8158            AgentOutcome::Quota(o) => {
8159                self.state.quota.push(QuotaLoss::from_report(
8160                    final_seat.key.clone(),
8161                    "fix",
8162                    o.quota.as_ref(),
8163                ));
8164                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
8165            }
8166            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => fix.failed = Some(e),
8167        }
8168        if self.state.resource_block.is_some() {
8169            self.state.seats.insert(final_seat.key.clone(), final_seat);
8170            return Ok(FixStep::Resource);
8171        }
8172        fix.continuation = Some(continuation);
8173        self.state.seats.insert(final_seat.key.clone(), final_seat);
8174        let coordination = self.coordinate(&winner.worktree).await?;
8175        if let Ok(r) = git::rescue_commit(
8176            &winner.worktree,
8177            &format!("magi: review round {round} fixes (uncommitted work)"),
8178        )
8179        .await
8180        {
8181            self.state.note_withheld("fix", &r.withheld);
8182        }
8183        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
8184        fix.committed = after != before;
8185        // Judged by what `git` says moved against base, never by the
8186        // fixer's own `addressed`/`rejected` count — see
8187        // `ReviewRound::progressed`. Propagated with `?`, the same as the
8188        // `patch` snapshot above: swallowing this error would default
8189        // `diff_after` to empty, which almost always differs from a
8190        // non-empty `patch` and reads as "progressed" — exactly backwards
8191        // for a `git` failure the stagnation check cannot see through.
8192        let diff_after = git::diff(&winner.worktree, &base, "HEAD").await?;
8193        drop(coordination);
8194        let progressed = diff_after != patch;
8195        let commit_note = if fix.committed {
8196            "committed"
8197        } else {
8198            "NO new commit"
8199        };
8200        let tree_note = if progressed {
8201            "changed vs base"
8202        } else {
8203            "unchanged vs base"
8204        };
8205        self.state.event(
8206            "fix",
8207            match &fix.failed {
8208                // Distinct on purpose from "0 addressed, 0 rejected": the
8209                // fixer's own diff still landed (blocking counts do keep
8210                // falling round over round), only its adoption report did
8211                // not come back, so this must never read like every
8212                // finding was reviewed and declined.
8213                Some(reason) => {
8214                    format!(
8215                        "round {round}: fixer's adoption report was lost ({reason}); \
8216                             {commit_note}, tree {tree_note}"
8217                    )
8218                }
8219                None => format!(
8220                    "round {round}: {} addressed, {} rejected, {commit_note}, tree \
8221                         {tree_note}{}",
8222                    fix.addressed.len(),
8223                    fix.rejected.len(),
8224                    if continuation.outcome == ContinuationOutcome::Resumed {
8225                        format!(
8226                            " (adoption report recovered after {} continuation(s))",
8227                            continuation.attempts
8228                        )
8229                    } else {
8230                        String::new()
8231                    },
8232                ),
8233            },
8234        );
8235        round_record.fix = Some(fix);
8236        round_record.progressed = progressed;
8237        Ok(FixStep::Recorded {
8238            report_lost: matches!(
8239                continuation.outcome,
8240                ContinuationOutcome::Exhausted
8241                    | ContinuationOutcome::QuotaLost
8242                    | ContinuationOutcome::NoSession
8243            ),
8244        })
8245    }
8246
8247    /// Decide, from the last recorded round's own verification, whether
8248    /// stopping the review loop is a hand-off or a genuine block.
8249    ///
8250    /// Called once the loop has given up trying — the round budget is spent,
8251    /// or the tree stopped moving (see [`STAGNANT_LIMIT`]) — with blocking
8252    /// findings still open, never while a round is still clean or the
8253    /// incomplete-panel case handled inline above. Gate and e2e are facts
8254    /// about the tree; a lingering review finding is an opinion, and this
8255    /// workload's own `magi stats` puts reviewer precision low enough
8256    /// (12-33%, 0.18-0.29 adopted per round) that a panel of open findings
8257    /// must not by itself stand between a green, verified change and the
8258    /// human who decides what to do with it. A red e2e is not an opinion, so
8259    /// that case still blocks, with the failing command and a tail of its
8260    /// output recorded here rather than left in `run.json` for someone to go
8261    /// find.
8262    ///
8263    /// A round that deferred its own e2e (see [`Config::graph`]'s
8264    /// `e2e_every_round`) is never read as that green: its `e2e` is empty
8265    /// only because nothing ran, and treating an empty list as a passing one
8266    /// here is exactly the "deferred painted green" bug this function exists
8267    /// to not have. When the last round's own verification never resolved —
8268    /// deferred on purpose, or a real attempt the shared build cache blocked
8269    /// — this makes (or retries) the real run, on the actual worktree this
8270    /// loop is about to stop touching, before deciding anything. A
8271    /// resource-blocked attempt is likewise never read as either green or
8272    /// red: it is evidence about the machine, not the patch (see
8273    /// [`CommandOutcome::resource_blocked`]'s own doc), so a persistently
8274    /// blocked cache leaves this call without deciding rather than guessing
8275    /// — the caller retries on a later reentry.
8276    /// Record, once, that the review loop handed off over a blocking finding
8277    /// a reviewer rejected on (see [`ReviewRound::contested_handoff`]), so
8278    /// `land` asks the owner even with `land_approval` off. Called from every
8279    /// path that concludes `Gating`; a reentry keeps the first record.
8280    fn record_contested_handoff(&mut self) {
8281        if self.state.contested_handoff.is_some() {
8282            return;
8283        }
8284        let Some(contested) = self
8285            .state
8286            .reviews
8287            .last()
8288            .and_then(ReviewRound::contested_handoff)
8289        else {
8290            return;
8291        };
8292        self.state.event(
8293            "review",
8294            format!(
8295                "{} blocking finding(s) open and {} reviewer(s) rejecting — the merge will \
8296                 wait for the owner's approval",
8297                contested.findings.len(),
8298                contested.rejecters.len()
8299            ),
8300        );
8301        self.state.contested_handoff = Some(contested);
8302    }
8303
8304    async fn stop_unresolved_review(
8305        &mut self,
8306        why: &str,
8307        shell: &[String],
8308        worktree: &Path,
8309    ) -> Result<()> {
8310        self.stop_reviewing_inner(why, shell, worktree, true).await
8311    }
8312
8313    async fn stop_reviewing(&mut self, why: &str, shell: &[String], worktree: &Path) -> Result<()> {
8314        self.stop_reviewing_inner(why, shell, worktree, false).await
8315    }
8316
8317    async fn stop_reviewing_inner(
8318        &mut self,
8319        why: &str,
8320        shell: &[String],
8321        worktree: &Path,
8322        repairable: bool,
8323    ) -> Result<()> {
8324        let round_idx = self.state.reviews.len() - 1;
8325        // A deferred round and a resource-blocked one are the same shape
8326        // here: neither has a real result yet, and both get one more
8327        // attempt. Read off `e2e_status` — the single source for this —
8328        // rather than `e2e.is_empty()` alone, so a resource-blocked attempt
8329        // (whose `e2e` is *not* empty; see `CommandOutcome::resource_blocked`)
8330        // still retries instead of being read as a settled result the
8331        // instant it stops being empty.
8332        let needs_catchup_run = matches!(
8333            self.state.reviews[round_idx].e2e_status(),
8334            E2eStatus::Deferred | E2eStatus::ResourceBlocked
8335        );
8336        if needs_catchup_run {
8337            let round = self.state.reviews[round_idx].round;
8338            let timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
8339            let commands = self.state.config.verify.e2e.clone();
8340            let before_head = git::rev_parse(worktree, "HEAD").await?;
8341            let winner = self.state.winner().cloned();
8342            let cache_dir = self.state.config.cache_dir();
8343            let context = format!(
8344                "round {round}: verification unresolved, catching up before the final decision"
8345            );
8346            let wait = self.repository_wait();
8347            let (outcomes, verify_retried) = with_cache_lease(
8348                &mut self.state,
8349                cache_dir.as_deref(),
8350                "e2e",
8351                "e2e",
8352                worktree,
8353                &before_head,
8354                timeout,
8355                &context,
8356                &wait,
8357                |state, budget| {
8358                    let shell = shell.to_vec();
8359                    let commands = commands.clone();
8360                    let context = context.clone();
8361                    async move {
8362                        if let Some(winner) = winner.filter(|_| !commands.is_empty()) {
8363                            // Same reason as in the round itself: format before
8364                            // the suite, not after it.
8365                            Self::run_pre_gate(state, &winner).await;
8366                        }
8367                        run_e2e_with_retry(
8368                            state,
8369                            &shell,
8370                            &commands,
8371                            worktree,
8372                            budget,
8373                            &context,
8374                            Some(round),
8375                        )
8376                        .await
8377                    }
8378                },
8379            )
8380            .await?;
8381            // After `pre_gate`: the commit the commands actually ran against.
8382            let attempted_head = git::rev_parse(worktree, "HEAD").await?;
8383            if !outcomes.is_empty() && !verify_inconclusive(&outcomes) {
8384                self.state.record_base_progress(&attempted_head);
8385            }
8386            let last = &mut self.state.reviews[round_idx];
8387            last.e2e = outcomes;
8388            last.verify_retried = verify_retried;
8389            // Always the commit and time this attempt actually targeted,
8390            // whether or not it happens to equal the reviewed `head` and
8391            // whether or not a command finished — see
8392            // `ReviewRound::verified_head`'s own doc. A still-inconclusive
8393            // attempt is recorded too, so a later reader sees "attempted
8394            // again at T2" rather than silence.
8395            last.verified_head = Some(attempted_head);
8396            last.verified_at = Some(Timestamp::now());
8397            if verify_inconclusive(&last.e2e) {
8398                // Still not a real result: `e2e_deferred` is left exactly
8399                // as it was, so `needs_catchup_run` above reads
8400                // `ResourceBlocked` (via `e2e_status`, which checks
8401                // `resource_blocked` before `e2e_deferred`) and retries
8402                // again on the next reentry, rather than recording
8403                // contention as a red e2e and blocking the run on it.
8404                self.state.save()?;
8405                return Ok(());
8406            }
8407            last.e2e_deferred = false;
8408            // A complete panel may have been saved as unclean solely because
8409            // verification could not run. Refresh that verdict with the new
8410            // outcomes before a granted repair consumes the round's result.
8411            // Incomplete panels retain their original policy/quota decision.
8412            if last.answered == last.expected {
8413                last.clean = round_is_clean(
8414                    last.blocking,
8415                    last.e2e.iter().all(CommandOutcome::ok),
8416                    last.answered,
8417                    last.expected,
8418                    0,
8419                    self.state.config.graph.incomplete_review,
8420                );
8421            }
8422        }
8423        let last = &self.state.reviews[round_idx];
8424        let open: usize = last.reviews.iter().map(|r| r.findings.len()).sum();
8425
8426        match last.e2e_status() {
8427            E2eStatus::Failed => {
8428                let red: Vec<String> = last
8429                    .e2e
8430                    .iter()
8431                    .filter(|o| !o.ok())
8432                    .map(|o| {
8433                        format!(
8434                            "`{}` -> {:?}\n{}",
8435                            o.command,
8436                            o.code,
8437                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
8438                        )
8439                    })
8440                    .collect();
8441                let can_repair = last.blocking == 0 && last.fix.is_none();
8442                self.state.reviews[round_idx].clean = false;
8443                self.state
8444                    .event("review", format!("{why}; e2e failed:\n{}", red.join("\n")));
8445                self.state.status = RunStatus::Blocked;
8446                if repairable
8447                    && can_repair
8448                    && self.state.reviews.len() < self.state.config.graph.review_rounds
8449                {
8450                    self.state.status = RunStatus::Reviewing;
8451                }
8452            }
8453            // `needs_catchup_run` above already retried once this call; if
8454            // it is still blocked, this is magi's own admission it could
8455            // not get a command to run, never a verdict on the patch — the
8456            // run is left exactly where a later reentry can retry again.
8457            E2eStatus::ResourceBlocked => {
8458                self.state.event(
8459                    "review",
8460                    format!(
8461                        "{why}; e2e could not run (resource unavailable); not \
8462                         deciding yet"
8463                    ),
8464                );
8465            }
8466            E2eStatus::Passed | E2eStatus::Deferred | E2eStatus::NotConfigured => {
8467                self.state.event(
8468                    "review",
8469                    format!("{why}; e2e is green — handing off with {open} finding(s) still open"),
8470                );
8471                self.record_contested_handoff();
8472                self.state.status = RunStatus::Gating;
8473            }
8474        }
8475        self.state.save()?;
8476        Ok(())
8477    }
8478
8479    // ----------------------------------------------------------------- gate
8480
8481    async fn gate(&mut self) -> Result<()> {
8482        if self.hold_base_sync().await? {
8483            return Ok(());
8484        }
8485        // Judged by the review record itself, not by `status`: a solo
8486        // candidate's `judge`/`deliberate` skip rewrites `status` on every
8487        // reentry (see `judge`), and trusting it here is exactly how a run
8488        // that exhausted its review budget got gated and merged a second
8489        // time around. `review_conclusion` recomputes the review loop's own
8490        // verdict from the round records themselves — `Gating` for a clean
8491        // round or a hand-off (see `stop_reviewing`), anything else means the
8492        // loop is still going or genuinely blocked.
8493        // A base the winner could not be replayed onto is a decision, not a
8494        // round: there is no landing tree to gate. Read as its own record for
8495        // the same reason the review verdict is.
8496        if self.state.status == RunStatus::Failed
8497            || self
8498                .state
8499                .base_sync
8500                .as_ref()
8501                .is_some_and(|s| s.conflict.is_some())
8502            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
8503                != Some(RunStatus::Gating)
8504        {
8505            return Ok(());
8506        }
8507        let Some(winner) = self.state.winner().cloned() else {
8508            return Ok(());
8509        };
8510        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
8511        self.state.reconcile_verification_head(&head);
8512        self.state.save()?;
8513        let wait = self.repository_wait();
8514        if !verify_current_head(&mut self.state, &winner, &wait).await? {
8515            return Ok(());
8516        }
8517        if self.state.gate_ran {
8518            // `review_loop` derives its conclusion from the clean review
8519            // record on every reentry and therefore puts a completed run back
8520            // in `Gating`. A recorded gate is a stronger, terminal fact:
8521            // retain its original command output (or lack of any, for a repo
8522            // with no `verify.gate` commands — see `RunState::gate_ran`'s own
8523            // doc) and restore `Blocked` on a real failure rather than
8524            // pretending the command is still running or running it a second
8525            // time. `gate_ran == false` remains the only shape — unattempted,
8526            // or a resource-blocked retry — that may still need to execute a
8527            // command.
8528            if self.state.gate.iter().any(|outcome| !outcome.ok()) {
8529                self.state.status = RunStatus::Blocked;
8530                self.state.save()?;
8531            }
8532            return Ok(());
8533        }
8534        self.state.status = RunStatus::Gating;
8535        let mut outcomes = self.run_gate(&winner).await?;
8536        let mut attempted_head = self.state.gate_head.clone();
8537        loop {
8538            // A resource-blocked outcome means the gate command never actually
8539            // ran - the shared build cache could not be acquired or confirmed
8540            // fresh in time - which is evidence about the machine, not about
8541            // the tree (see `CommandOutcome::resource_blocked`'s own doc).
8542            // Recording it as a red gate would mark a run `Blocked` on nothing
8543            // but contention magi has already logged; leaving `self.state.gate`
8544            // empty and `self.state.gate_ran` false instead keeps the shape
8545            // this function already treats as "still needs to run" (see the
8546            // early-return above), so the next call retries the command
8547            // rather than concluding anything.
8548            if verify_inconclusive(&outcomes) {
8549                self.state.save()?;
8550                return Ok(());
8551            }
8552            if outcomes.iter().all(CommandOutcome::ok) {
8553                break;
8554            }
8555            let fixes_before = self.state.gate_fixes.len();
8556            match self.gate_fix_round(&winner, &outcomes).await? {
8557                GateFix::Retry => {
8558                    outcomes = self.run_gate(&winner).await?;
8559                    attempted_head = self.state.gate_head.clone();
8560                }
8561                GateFix::Stop => {
8562                    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
8563                    if self.state.gate_fixes.len() > fixes_before
8564                        && attempted_head.as_deref() != Some(current.as_str())
8565                        && verify_current_head(&mut self.state, &winner, &wait).await?
8566                    {
8567                        // A new SHA owes a gate even when a spent fixer changed only
8568                        // commit metadata. This does not grant another repair round.
8569                        outcomes = self.run_gate(&winner).await?;
8570                        attempted_head = self.state.gate_head.clone();
8571                    } else {
8572                        break;
8573                    }
8574                }
8575                GateFix::Defer => {
8576                    self.state.save()?;
8577                    return Ok(());
8578                }
8579            }
8580        }
8581        let passed = outcomes.iter().all(CommandOutcome::ok);
8582        self.state.gate = outcomes;
8583        self.state.gate_ran = true;
8584        self.state.gate_head = attempted_head;
8585        if !self.state.gate.is_empty()
8586            && !verify_inconclusive(&self.state.gate)
8587            && let Some(head) = self.state.gate_head.clone()
8588        {
8589            self.state.record_base_progress(&head);
8590        }
8591        self.state.save()?;
8592        if !verify_current_head(&mut self.state, &winner, &wait).await? {
8593            return Ok(());
8594        }
8595        if !passed {
8596            self.state.status = RunStatus::Blocked;
8597            let spent = self.state.gate_fixes.len();
8598            self.state.event(
8599                "gate",
8600                if spent == 0 {
8601                    "gate failed; not merging".to_owned()
8602                } else {
8603                    format!("gate failed after {spent} gate-fix round(s); not merging")
8604                },
8605            );
8606        }
8607        self.state.save()?;
8608        Ok(())
8609    }
8610
8611    /// Run `verify.pre_gate` in the winner's worktree, then fold whatever it
8612    /// changed into one commit. Runs before `verify.e2e` in the review loop
8613    /// and again before the gate commands, always on the winner and never on
8614    /// a candidate awaiting judging.
8615    ///
8616    /// Before e2e as well as before the gate because command evidence belongs
8617    /// to a SHA ([`verify_current_head`]): a commit made only at the gate is a
8618    /// commit e2e never saw, and the suite ran again for a formatter's diff -
8619    /// 5 of the 22 gated runs on this repository in November 2026. The gate's
8620    /// own call then finds nothing left to change. The commands must be
8621    /// idempotent; one that is not makes a commit per call.
8622    ///
8623    /// Never fails the run: a non-zero exit or timeout is a warning and a
8624    /// recorded outcome, and the gate remains the single arbiter. Nothing
8625    /// configured means nothing happens - no event, no commit. `commit_all`
8626    /// commits any leftover change under the neutral identity and returns
8627    /// `false` when the tree is clean, so no empty commit is ever made.
8628    async fn run_pre_gate(state: &mut RunState, winner: &Candidate) {
8629        let commands = state.config.verify.pre_gate.clone();
8630        if commands.is_empty() {
8631            return;
8632        }
8633        let shell = state.config.shell();
8634        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
8635        let (outcomes, _) = run_commands(
8636            state,
8637            "pre_gate",
8638            "pre_gate",
8639            0,
8640            &shell,
8641            &commands,
8642            &winner.worktree,
8643            timeout,
8644        )
8645        .await;
8646        for o in &outcomes {
8647            if !o.ok() {
8648                tracing::warn!(
8649                    "pre_gate `{}` failed ({:?}); the gate decides",
8650                    o.command,
8651                    o.code
8652                );
8653            }
8654            state.event(
8655                "pre_gate",
8656                format!(
8657                    "`{}` -> {}",
8658                    o.command,
8659                    if o.ok() {
8660                        "pass".to_owned()
8661                    } else {
8662                        format!(
8663                            "FAIL ({:?})\n{}",
8664                            o.code,
8665                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
8666                        )
8667                    }
8668                ),
8669            );
8670        }
8671        state.pre_gate = outcomes;
8672        match git::commit_all(&winner.worktree, "magi: pre_gate (mechanical fixes)").await {
8673            Ok(true) => match git::rev_parse(&winner.worktree, "HEAD").await {
8674                Ok(head) => {
8675                    state.event("pre_gate", format!("committed mechanical fixes ({head})"));
8676                    state.pre_gate_commit = Some(head);
8677                }
8678                Err(e) => tracing::warn!("pre_gate committed but HEAD unreadable: {e:#}"),
8679            },
8680            Ok(false) => {}
8681            Err(e) => tracing::warn!("pre_gate could not commit its changes: {e:#}"),
8682        }
8683        if let Err(e) = state.save() {
8684            tracing::warn!("could not persist the pre_gate record: {e:#}");
8685        }
8686    }
8687
8688    /// Run `verify.gate` once against the winner's current tree, logging one
8689    /// event per command. Empty when nothing is configured.
8690    async fn run_gate(&mut self, winner: &Candidate) -> Result<Vec<CommandOutcome>> {
8691        let wait = self.repository_wait();
8692        run_landing_gate(&mut self.state, winner, &wait).await
8693    }
8694
8695    /// One bounded fix round for a failing gate.
8696    ///
8697    /// The fixer is told the failure came from the gate itself, not from a
8698    /// reviewer, and is shown the failed commands, their exit codes and a tail
8699    /// of their output - whatever `[verify].gate` holds, nothing here knows
8700    /// what those commands run. Only a normal non-zero exit that printed
8701    /// something earns a round (see [`gate_fixable`]): a timeout, a missing
8702    /// command or a full disk says nothing about the code, and a fixer sent
8703    /// after it can only appease the machine. The round is judged by what git
8704    /// says moved, never by the fixer's own report, and `verify.e2e` runs
8705    /// again before the gate does, so a fix cannot trade a green gate for a
8706    /// red e2e unnoticed.
8707    async fn gate_fix_round(
8708        &mut self,
8709        winner: &Candidate,
8710        outcomes: &[CommandOutcome],
8711    ) -> Result<GateFix> {
8712        let cap = if self.state.repair_grants.last().is_some_and(|g| {
8713            g.phase == crate::repair_budget::Phase::Fixing
8714                && g.receipt.request.kind == crate::repair_budget::Kind::Gate
8715        }) {
8716            self.state.gate_fixes.len().saturating_add(1)
8717        } else {
8718            self.state.config.graph.gate_fix_rounds
8719        };
8720        let spent = self.state.gate_fixes.len();
8721        if spent >= cap {
8722            if cap > 0 {
8723                self.state.event(
8724                    "gate",
8725                    format!("{spent} gate-fix round(s) spent and the gate still fails"),
8726                );
8727            }
8728            return Ok(GateFix::Stop);
8729        }
8730        if !gate_fixable(outcomes) {
8731            self.state.event(
8732                "gate",
8733                "gate failure is not an ordinary non-zero exit with output (timeout, missing \
8734                 command or similar); not spending a fix round on it",
8735            );
8736            return Ok(GateFix::Stop);
8737        }
8738        let min_free = self.state.config.disk.min_free_bytes;
8739        if min_free > 0 {
8740            match crate::disk::free_bytes(&winner.worktree) {
8741                Ok(free) if crate::disk::enough_space(free, min_free) => {}
8742                Ok(free) => {
8743                    self.state.event(
8744                        "gate",
8745                        format!(
8746                            "only {free} bytes free ({min_free} required by `[disk] \
8747                             min_free_bytes`); not spending a fix round on a failure the disk \
8748                             may explain"
8749                        ),
8750                    );
8751                    return Ok(GateFix::Stop);
8752                }
8753                Err(e) => {
8754                    self.state.event(
8755                        "gate",
8756                        format!("free disk space could not be measured ({e:#}); no fix round"),
8757                    );
8758                    return Ok(GateFix::Stop);
8759                }
8760            }
8761        }
8762
8763        let attempt = spent + 1;
8764        let failed: Vec<CommandOutcome> = outcomes.iter().filter(|o| !o.ok()).cloned().collect();
8765        let base = self.landing_base();
8766        let fix_prompt = prompt::gate_fix_in(
8767            &self.state.instruction,
8768            &failed,
8769            attempt,
8770            cap,
8771            &self.state.config.graph.language,
8772            &self.state.config.graph.github_language,
8773        );
8774        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
8775        let sessions = self.state.config.graph.sessions;
8776        let artifacts = self.merge_repair_artifacts();
8777        self.state.event(
8778            "gate",
8779            format!("gate failed; gate-fix round {attempt} of {cap}"),
8780        );
8781        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
8782        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
8783        // Persist before invoking the fixer: it may commit and then be
8784        // interrupted before its result (or the following e2e) is saved.
8785        self.state.gate_repair_e2e = Some(crate::run::GateRepairE2e {
8786            head: before.clone(),
8787            passed: false,
8788            outcomes: Vec::new(),
8789        });
8790        self.state.save()?;
8791        let (_, seat, out) = self
8792            .ask_fixer(winner, "gate-fix", None, |spec, seat| SeatJob {
8793                prompt: fix_prompt.clone(),
8794                spec,
8795                seat,
8796                cwd: winner.worktree.clone(),
8797                timeout,
8798                allow_write: true,
8799                sessions,
8800                artifacts: artifacts.clone(),
8801                stem: format!("gate-fix-{attempt}"),
8802                handover: None,
8803            })
8804            .await;
8805        // The fixer was never asked: no round is spent (nothing is recorded)
8806        // and a later reentry asks the same agent again.
8807        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
8808            return Ok(GateFix::Defer);
8809        }
8810        let mut record = GateFixRecord {
8811            agent: seat.agent.clone(),
8812            failed,
8813            notes: String::new(),
8814            committed: false,
8815            error: None,
8816        };
8817        match out {
8818            AgentOutcome::Ok(o) => {
8819                // A missing report is not a failed fix: the round is judged
8820                // by the tree below, and the report only carries prose.
8821                if let Ok(report) = verdict::extract_json::<FixReport>(&o.text) {
8822                    record.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
8823                }
8824            }
8825            AgentOutcome::Dropped(_) => {
8826                record.error = Some("the CLI dropped the stream".to_owned());
8827            }
8828            AgentOutcome::Quota(o) => {
8829                self.state.quota.push(QuotaLoss::from_report(
8830                    seat.key.clone(),
8831                    "gate-fix",
8832                    o.quota.as_ref(),
8833                ));
8834                record.error = Some("rate limited (quota); fixer could not run".to_owned());
8835            }
8836            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => record.error = Some(e),
8837        }
8838        self.state.seats.insert(seat.key.clone(), seat);
8839        let coordination = self.coordinate(&winner.worktree).await?;
8840        if let Ok(r) = git::rescue_commit(
8841            &winner.worktree,
8842            &format!("magi: gate fix {attempt} (uncommitted work)"),
8843        )
8844        .await
8845        {
8846            self.state.note_withheld("gate-fix", &r.withheld);
8847        }
8848        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
8849        record.committed = after != before;
8850        let changed = git::diff(&winner.worktree, &base, "HEAD").await? != patch;
8851        let note = record.error.clone();
8852        self.state.gate_fixes.push(record);
8853        self.state.save()?;
8854        if !changed {
8855            self.state.event(
8856                "gate",
8857                match note {
8858                    Some(why) => format!("gate-fix round {attempt}: fixer failed ({why})"),
8859                    None => format!("gate-fix round {attempt}: the tree did not change"),
8860                },
8861            );
8862            return Ok(GateFix::Stop);
8863        }
8864        self.state.event(
8865            "gate",
8866            format!("gate-fix round {attempt}: tree changed vs base; re-running verify.e2e"),
8867        );
8868
8869        drop(coordination);
8870        let wait = self.repository_wait();
8871        check_gate_repair_e2e(&mut self.state, winner, &wait).await
8872    }
8873
8874    // ---------------------------------------------------------------- merge
8875
8876    /// One read-only rewrite by the summary's author; a text the gate still
8877    /// withholds goes to the owner (see `github_text`) and the fixed fallback
8878    /// applies on their word or on silence. `None` means the run is parked on
8879    /// that question and nothing may be pushed or opened yet.
8880    async fn guarded_pr_message(
8881        &mut self,
8882        winner: &Candidate,
8883        facts: Option<&BranchFacts>,
8884        posting: bool,
8885    ) -> Result<Option<PrMessage>> {
8886        let final_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
8887        let head = match final_head.as_deref() {
8888            Some(h) => crate::pr_outcome::FinalHead::At(h),
8889            None => crate::pr_outcome::FinalHead::Unknown,
8890        };
8891        // Only a pull request that is about to be posted pays for a summary.
8892        let summarized = if posting {
8893            Some(self.summarize_change(winner, final_head.as_deref()).await)
8894        } else {
8895            None
8896        };
8897        // A busy shared resource is not a permanent cause: publishing an
8898        // "unavailable" description would stick (a later head move never
8899        // edits the body). Stop before anything is pushed or opened; the
8900        // run is `Blocked` and a resume asks the summary again.
8901        if self.state.resource_block.is_some() {
8902            self.state.event(
8903                "pr-summary",
8904                "a shared resource was busy; nothing was published, resume to summarize again",
8905            );
8906            return Ok(None);
8907        }
8908        if posting && git::rev_parse(&winner.worktree, "HEAD").await.ok() != final_head {
8909            anyhow::bail!(
8910                "the final commit moved during public description generation; retry before publishing"
8911            );
8912        }
8913        let note = match (&summarized, &self.state.change_summary) {
8914            (Some(Ok(())), Some(c)) => ChangeNote::Summary(c),
8915            (Some(Err(why)), _) => ChangeNote::Unavailable(why),
8916            (Some(Ok(())), None) => ChangeNote::Unavailable("no summary was recorded"),
8917            (None, _) => ChangeNote::NotAsked,
8918        };
8919        let mut pr = pr_message_raw(&self.state, winner.label, facts, head, note);
8920        if !posting {
8921            let identity = crate::scrub::Identity::current();
8922            return Ok(Some(PrMessage {
8923                title: crate::scrub::scrub(&pr.title, &identity),
8924                body: crate::scrub::scrub(&pr.body, &identity),
8925            }));
8926        }
8927        // This very text was already rejected and asked about: no second
8928        // judge call, rewrite or question, just carry the record on.
8929        let raw_fp = crate::github_text::fingerprint(&pr.title, &pr.body);
8930        if let Some(known) = self
8931            .state
8932            .github_text
8933            .clone()
8934            .filter(|g| g.fingerprint == raw_fp)
8935        {
8936            return self.settle_withheld(winner, &pr, known).await;
8937        }
8938        let mut decision = self.judge_pr_language(&winner.worktree, &pr).await;
8939        let mut violations =
8940            crate::github_text::check_for(&self.state.config.graph, &pr.title, &pr.body, decision);
8941        let identity = crate::scrub::Identity::current();
8942        if (crate::scrub::scrub(&pr.title, &identity) != pr.title
8943            || crate::scrub::scrub(&pr.body, &identity) != pr.body)
8944            && !violations.contains(&crate::github_text::Violation::SensitiveData)
8945        {
8946            violations.push(crate::github_text::Violation::SensitiveData);
8947        }
8948        // A rewrite cannot fix sensitive data (e.g. a quoted original task), so
8949        // only a language violation starts one; sensitive data alone goes
8950        // straight to the owner, with the redacted text as the fallback.
8951        let has_language = violations
8952            .iter()
8953            .any(|v| *v != crate::github_text::Violation::SensitiveData);
8954        if self.state.config.graph.github_text_guard && !violations.is_empty() {
8955            self.state.event(
8956                "github-text",
8957                if has_language {
8958                    format!("description rejected: {violations:?}; requesting one rewrite")
8959                } else {
8960                    format!("description rejected: {violations:?}; asking the owner")
8961                },
8962            );
8963            let mut rewritten = false;
8964            let mut rejected_rewrite = None;
8965            if has_language && let Some(text) = self.rewrite_pr_text(winner, &pr, &violations).await
8966            {
8967                let output = text;
8968                if let Some(title) = summary_title(&output) {
8969                    // Judge the redacted candidate that will actually be posted.
8970                    // Sensitive data alone must not discard a useful rewrite.
8971                    let raw_body = summary_without_title(&output);
8972                    let clean_title = crate::scrub::scrub(&title, &identity);
8973                    let mut body = crate::scrub::scrub(&raw_body, &identity);
8974                    let redacted = clean_title != title || body != raw_body;
8975                    let title = clean_title;
8976                    let complete = crate::pr_outcome::covers_required_findings(&self.state, &body);
8977                    if !complete {
8978                        self.state.event(
8979                            "github-text",
8980                            "description rewrite omitted required findings",
8981                        );
8982                    }
8983                    if !body.trim().is_empty() {
8984                        body.push_str("\n\n");
8985                        body.push_str(&public_pr_evidence(&self.state, head));
8986                    }
8987                    let marker = format!("magi:run/{}", self.state.id);
8988                    if !body.trim().is_empty() && !body.contains(&marker) {
8989                        body.push_str(&format!("\n\n{marker}"));
8990                    }
8991                    let rewrite = PrMessage {
8992                        title: title.clone(),
8993                        body: body.clone(),
8994                    };
8995                    let redecision = self.judge_pr_language(&winner.worktree, &rewrite).await;
8996                    let mut failed = crate::github_text::check_for(
8997                        &self.state.config.graph,
8998                        &title,
8999                        &body,
9000                        redecision,
9001                    );
9002                    if (!crate::github_text::shareable(&title)
9003                        || !crate::github_text::shareable(&body))
9004                        && !failed.contains(&crate::github_text::Violation::SensitiveData)
9005                    {
9006                        failed.push(crate::github_text::Violation::SensitiveData);
9007                    }
9008                    if complete
9009                        && !title.trim().is_empty()
9010                        && !body.trim().is_empty()
9011                        && !failed.is_empty()
9012                    {
9013                        rejected_rewrite = Some(crate::run::GithubTextRewrite {
9014                            title: title.clone(),
9015                            body: body.clone(),
9016                            failed: failed
9017                                .iter()
9018                                .map(|v| crate::github_text::category(*v).to_owned())
9019                                .collect(),
9020                        });
9021                    }
9022                    if complete
9023                        && !title.trim().is_empty()
9024                        && !raw_body.trim().is_empty()
9025                        && failed.is_empty()
9026                    {
9027                        decision = redecision;
9028                        pr = PrMessage { title, body };
9029                        rewritten = true;
9030                        self.state
9031                            .event("github-text", "description rewrite passed");
9032                        if redacted {
9033                            self.state.event(
9034                                "github-text",
9035                                "sensitive data removed from description rewrite",
9036                            );
9037                        }
9038                    }
9039                }
9040            }
9041            if !rewritten {
9042                self.state.event(
9043                    "github-text",
9044                    "description rewrite unavailable or rejected; asking the owner",
9045                );
9046                if let Some(w) =
9047                    crate::github_text::Withheld::from_check(&violations, &pr.title, &pr.body)
9048                {
9049                    // A different text than the one asked about before: that
9050                    // question no longer describes anything.
9051                    self.retire_github_text_question("the withheld text changed");
9052                    let record = crate::run::GithubTextAsk {
9053                        rewrite: rejected_rewrite,
9054                        fingerprint: raw_fp,
9055                        title: w.title,
9056                        body: w.body,
9057                        categories: w.categories.iter().map(|c| (*c).to_owned()).collect(),
9058                        question: None,
9059                        asks: 0,
9060                        resolved: false,
9061                        chosen_title: None,
9062                        choice: None,
9063                        publication: None,
9064                    };
9065                    return self.settle_withheld(winner, &pr, record).await;
9066                }
9067            }
9068        }
9069        let (title, body) =
9070            crate::github_text::prepare_with(&mut self.state, &pr.title, &pr.body, decision);
9071        Ok(Some(PrMessage { title, body }))
9072    }
9073
9074    /// Describe the whole change from its final diff in either run mode.
9075    ///
9076    /// The summary is tied to the final commit and to the merge base of the
9077    /// resolved remote base; a record for any other pair is dropped and the
9078    /// agent asked again, so a description never outlives the diff it was
9079    /// written from. The seat is read-only and the prompt tells it to read the
9080    /// diff and the code around it. `[roles] synthesizer` selects the agents
9081    /// (unset: the default pick), each asked at most once, advancing on an
9082    /// error, quota, unusable answer or a reply with no `TITLE:` line. `Err`
9083    /// carries the reason it is unavailable; nothing is invented then.
9084    async fn summarize_change(
9085        &mut self,
9086        winner: &Candidate,
9087        head: Option<&str>,
9088    ) -> std::result::Result<(), String> {
9089        let Some(head) = head else {
9090            return Err("the final commit could not be read".to_owned());
9091        };
9092        let remote = self.state.config.merge.remote.clone();
9093        let tracking = format!("{remote}/{}", self.state.base_branch);
9094        if !git::rev_exists(&winner.worktree, &tracking).await {
9095            return Err(format!("the remote base `{tracking}` could not be read"));
9096        }
9097        let base = match git::merge_base(&winner.worktree, &tracking, head).await {
9098            Ok(b) if !b.is_empty() => b,
9099            _ => return Err("the merge base with the remote base could not be read".to_owned()),
9100        };
9101        let evidence = crate::pr_outcome::summary_evidence(
9102            &self.state,
9103            crate::pr_outcome::FinalHead::At(head),
9104        );
9105        let fingerprint = crate::pr_outcome::summary_fingerprint(&self.state, &evidence);
9106        if self
9107            .state
9108            .change_summary
9109            .as_ref()
9110            .is_some_and(|c| c.head == head && c.base == base && c.evidence == fingerprint)
9111        {
9112            return Ok(());
9113        }
9114        if self.state.change_summary.take().is_some() {
9115            self.state.event(
9116                "pr-summary",
9117                "the final diff or evidence changed; the earlier change summary was discarded",
9118            );
9119        }
9120        // Save the source snapshot even if no generation agent is available.
9121        if let Err(e) = write_artifact(
9122            &self.state,
9123            &format!("public-description-{fingerprint}.md"),
9124            &format!("Final diff: {base}..{head}\n\n{evidence}"),
9125        ) {
9126            tracing::warn!("could not save public description evidence: {e:#}");
9127        }
9128        let chain = match agent::pick_chain(
9129            &self.state.config.agents,
9130            self.state.config.roles.synthesizer.as_ref(),
9131            &agent::installed,
9132            "synthesizer",
9133        ) {
9134            Ok(chain) => chain,
9135            Err(e) => {
9136                tracing::warn!("no agent for the change summary: {e:#}");
9137                self.state.event("pr-summary", "no summary agent available");
9138                return Err("no agent was available to summarize it".to_owned());
9139            }
9140        };
9141        let subjects = git::subjects(&winner.worktree, &base, head)
9142            .await
9143            .unwrap_or_default();
9144        let stat = git::diff_stat(&winner.worktree, &base, head)
9145            .await
9146            .unwrap_or_default();
9147        let stat: String = stat.chars().take(6_000).collect();
9148        let mut prompt = crate::prompt::change_summary_in(
9149            &base,
9150            head,
9151            &subjects,
9152            stat.trim(),
9153            &self.state.config.graph.github_language,
9154        );
9155        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."));
9156        let sessions = self.state.config.graph.sessions;
9157        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
9158        let prompts = self.state.config.prompts.clone();
9159        let cache = self.state.config.cache_dir();
9160        let run = self.state.id.clone();
9161        for (i, spec) in chain.into_iter().enumerate() {
9162            let seat = crate::fixer::seat_for(&mut self.state, "change-summary", &spec.id);
9163            let github_spec = match agent::for_github_text(
9164                &spec,
9165                &self.state.config.graph.github_language,
9166                &winner.worktree,
9167            ) {
9168                Ok(spec) => spec,
9169                Err(e) => {
9170                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9171                    continue;
9172                }
9173            };
9174            let job = SeatJob {
9175                spec: github_spec,
9176                seat,
9177                cwd: winner.worktree.clone(),
9178                prompt: prompt.clone(),
9179                timeout,
9180                allow_write: false,
9181                sessions,
9182                artifacts: agent::artifacts_dir(&self.state.dir()),
9183                stem: if i == 0 {
9184                    "change-summary".to_owned()
9185                } else {
9186                    format!("change-summary-{}", spec.id)
9187                },
9188                handover: None,
9189            };
9190            let ctx = WaveCtx {
9191                run: &run,
9192                node: "pr-summary",
9193                prompts: &prompts,
9194                cache: cache.as_deref(),
9195                round: None,
9196                carry_seats: false,
9197                pauses: Some((&self.pause, &self.interrupt)),
9198            };
9199            let (seat, outcome) =
9200                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9201            self.state.seats.insert(seat.key.clone(), seat);
9202            let text = match outcome {
9203                AgentOutcome::Ok(o) if !agent::output_advances(&o) => o.text,
9204                AgentOutcome::ResourceBlocked(why) => {
9205                    // No agent was asked: the run stops resumably before
9206                    // anything is published (see `guarded_pr_message`).
9207                    if self.state.resource_block.is_none() {
9208                        self.state.resource_block = Some(crate::run::ResourceBlock {
9209                            cause: crate::run::ResourceBlockCause::Other,
9210                            node: "pr-summary".to_owned(),
9211                            kind: "shared resource".to_owned(),
9212                            detail: why,
9213                            at: Timestamp::now(),
9214                        });
9215                    }
9216                    return Err("a shared resource was busy".to_owned());
9217                }
9218                _ => continue,
9219            };
9220            let blind = &self.state.config.blind;
9221            let Some(title) = summary_title(&text) else {
9222                continue;
9223            };
9224            let body: String = summary_without_title(&text)
9225                .lines()
9226                .filter(|l| !l.contains("magi:run/"))
9227                .collect::<Vec<_>>()
9228                .join("\n");
9229            let body = blind::sanitize_prose(body.trim(), blind);
9230            let title = blind::sanitize_prose(&title, blind);
9231            if body.trim().is_empty() || title.trim().is_empty() {
9232                continue;
9233            }
9234            if !crate::pr_outcome::covers_required_findings(&self.state, &body) {
9235                continue;
9236            }
9237            // The branch must still be the one the agent was shown.
9238            if git::rev_parse(&winner.worktree, "HEAD")
9239                .await
9240                .ok()
9241                .as_deref()
9242                != Some(head)
9243            {
9244                return Err("the branch moved while the summary was written".to_owned());
9245            }
9246            if git::merge_base(&winner.worktree, &tracking, head)
9247                .await
9248                .ok()
9249                .as_deref()
9250                != Some(base.as_str())
9251                || crate::pr_outcome::summary_evidence(
9252                    &self.state,
9253                    crate::pr_outcome::FinalHead::At(head),
9254                ) != evidence
9255            {
9256                return Err("the summary evidence changed while it was written".to_owned());
9257            }
9258            self.state.change_summary = Some(crate::run::ChangeSummary {
9259                head: head.to_owned(),
9260                base,
9261                evidence: fingerprint,
9262                title,
9263                body,
9264            });
9265            self.state.event(
9266                "pr-summary",
9267                format!("change summary written by {} for the final diff", spec.id),
9268            );
9269            if let Err(e) = self.state.save() {
9270                tracing::warn!("could not save the change summary: {e:#}");
9271            }
9272            return Ok(());
9273        }
9274        self.state
9275            .event("pr-summary", "no agent produced a change summary");
9276        Err("the summarizing agents were unavailable or gave no usable answer".to_owned())
9277    }
9278
9279    /// One read-only rewrite request for a withheld description. The
9280    /// implementer's own conversation is tried first when it exists and can be
9281    /// resumed; then the `[roles] language_judge` chain (or the default pick)
9282    /// writes it in a separate conversation, skipping the implementer's agent.
9283    /// The prompt carries the whole text, so no agent needs any memory. Each
9284    /// agent is asked at most once and the chain advances on an error, quota,
9285    /// unusable answer or a reply with no `TITLE:` line: a resumed implementer
9286    /// that has run out of quota must not end the rewrite. Nothing is recorded
9287    /// as a handover.
9288    async fn rewrite_pr_text(
9289        &mut self,
9290        winner: &Candidate,
9291        pr: &PrMessage,
9292        violations: &[crate::github_text::Violation],
9293    ) -> Option<String> {
9294        let prompt = format!(
9295            "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{}",
9296            pr.title, pr.body
9297        );
9298        let sessions = self.state.config.graph.sessions;
9299        let timeout_full = Duration::from_secs(self.state.config.graph.timeout_implement);
9300        // (spec, the resumed implementer's seat). A fallback seat is created
9301        // only when its turn comes, so an unused fallback leaves no record.
9302        let mut attempts: Vec<(AgentSpec, Option<SeatState>)> = Vec::new();
9303        let key = format!("impl-{}", winner.label);
9304        if let Some(spec) = self
9305            .state
9306            .config
9307            .agents
9308            .iter()
9309            .find(|a| a.id == winner.agent)
9310            .cloned()
9311            && let Some(existing) = self.state.seats.get(&key)
9312            && existing.agent == spec.id
9313            && agent::has_session(spec.kind, existing, sessions)
9314        {
9315            attempts.push((spec, Some(existing.clone())));
9316        }
9317        match agent::pick_chain(
9318            &self.state.config.agents,
9319            self.state.config.roles.language_judge.as_ref(),
9320            &agent::installed,
9321            "language_judge",
9322        ) {
9323            Ok(chain) => {
9324                for spec in chain {
9325                    if attempts.iter().any(|(tried, _)| tried.id == spec.id) {
9326                        continue;
9327                    }
9328                    attempts.push((spec, None));
9329                }
9330            }
9331            Err(e) if attempts.is_empty() => {
9332                tracing::warn!("no agent for the description rewrite: {e:#}");
9333                self.state
9334                    .event("github-text", "no rewrite agent available");
9335                return None;
9336            }
9337            Err(e) => tracing::warn!("no fallback agent for the description rewrite: {e:#}"),
9338        }
9339        let prompts = self.state.config.prompts.clone();
9340        let cache = self.state.config.cache_dir();
9341        let run = self.state.id.clone();
9342        for (i, (spec, resumed_seat)) in attempts.into_iter().enumerate() {
9343            let resumed = resumed_seat.is_some();
9344            let seat = resumed_seat.unwrap_or_else(|| {
9345                crate::fixer::seat_for(&mut self.state, "github-text-rewrite", &spec.id)
9346            });
9347            let github_spec = match agent::for_github_text(
9348                &spec,
9349                &self.state.config.graph.github_language,
9350                &winner.worktree,
9351            ) {
9352                Ok(spec) => spec,
9353                Err(e) => {
9354                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9355                    continue;
9356                }
9357            };
9358            let job = SeatJob {
9359                spec: github_spec,
9360                seat,
9361                cwd: winner.worktree.clone(),
9362                prompt: prompt.clone(),
9363                timeout: retry_budget(timeout_full, resumed),
9364                allow_write: false,
9365                sessions,
9366                artifacts: agent::artifacts_dir(&self.state.dir()),
9367                stem: if i == 0 {
9368                    "github-text-rewrite".to_owned()
9369                } else {
9370                    format!("github-text-rewrite-{}", spec.id)
9371                },
9372                handover: None,
9373            };
9374            let ctx = WaveCtx {
9375                run: &run,
9376                node: "github-text",
9377                prompts: &prompts,
9378                cache: cache.as_deref(),
9379                round: None,
9380                carry_seats: false,
9381                pauses: Some((&self.pause, &self.interrupt)),
9382            };
9383            let (seat, outcome) =
9384                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9385            self.state.seats.insert(seat.key.clone(), seat);
9386            match outcome {
9387                AgentOutcome::Ok(o)
9388                    if !agent::output_advances(&o) && summary_title(&o.text).is_some() =>
9389                {
9390                    return Some(o.text);
9391                }
9392                AgentOutcome::ResourceBlocked(_) => return None,
9393                _ => {}
9394            }
9395        }
9396        None
9397    }
9398
9399    /// Abandon the standing posting-gate question, if any.
9400    fn retire_github_text_question(&mut self, why: &str) {
9401        let Some(id) = self
9402            .state
9403            .github_text
9404            .as_ref()
9405            .and_then(|g| g.question.clone())
9406        else {
9407            return;
9408        };
9409        let _ = ask::Questions::open().update(&id, |q| {
9410            q.abandon(why);
9411            Ok(())
9412        });
9413    }
9414
9415    /// Carry a withheld text to its end: file the question, park while it is
9416    /// open, and on an answer, silence or timeout pick the text to post. The
9417    /// decision is saved before it is used, so it applies once.
9418    async fn settle_withheld(
9419        &mut self,
9420        winner: &Candidate,
9421        pr: &PrMessage,
9422        mut g: crate::run::GithubTextAsk,
9423    ) -> Result<Option<PrMessage>> {
9424        use crate::github_text as gt;
9425        let store = ask::Questions::open();
9426        let timeout = self.state.config.graph.answer_timeout;
9427        if !g.resolved {
9428            let mut standing = g
9429                .question
9430                .as_ref()
9431                .and_then(|id| store.list_for_effects().into_iter().find(|q| &q.id == id));
9432            if let Some(q) = standing.as_ref()
9433                && q.status.open()
9434                && !store.held_reply(&q.id)
9435                && gt::expired(q, timeout)
9436            {
9437                let why = format!("no answer within {}s of asking", timeout.max(1));
9438                standing = store
9439                    .update(&q.id, |q| {
9440                        q.abandon(&why);
9441                        Ok(())
9442                    })
9443                    .ok()
9444                    .map(|(q, ())| q);
9445            }
9446            let mut ask_again: Option<Option<Vec<String>>> = None;
9447            match standing {
9448                // Recorded but never written (a stop between the two saves),
9449                // or removed: ask again without spending the retry.
9450                None if g.asks <= 1 => {
9451                    g.asks = 0;
9452                    ask_again = Some(None);
9453                }
9454                None => {
9455                    g.resolved = true;
9456                    g.chosen_title = None;
9457                    g.choice = Some(GithubTextChoice::Fallback);
9458                }
9459                Some(q) if q.status.open() => {
9460                    self.park_on_github_text(&g)?;
9461                    return Ok(None);
9462                }
9463                Some(q) => match gt::read_reply(&q) {
9464                    gt::Reply::Fallback => {
9465                        g.resolved = true;
9466                        g.chosen_title = None;
9467                        g.choice = Some(GithubTextChoice::Fallback);
9468                    }
9469                    gt::Reply::Original => {
9470                        g.resolved = true;
9471                        g.chosen_title = None;
9472                        g.choice = Some(GithubTextChoice::Original);
9473                    }
9474                    gt::Reply::Rewrite => {
9475                        g.resolved = true;
9476                        g.chosen_title = None;
9477                        g.choice = Some(if g.rewrite.is_some() {
9478                            GithubTextChoice::Rewrite
9479                        } else {
9480                            GithubTextChoice::Fallback
9481                        });
9482                    }
9483                    gt::Reply::Title(text) => {
9484                        let first = text
9485                            .lines()
9486                            .map(str::trim)
9487                            .find(|l| !l.is_empty())
9488                            .unwrap_or("");
9489                        let decision = if first.is_empty() {
9490                            None
9491                        } else {
9492                            let candidate = PrMessage {
9493                                title: first.to_owned(),
9494                                body: String::new(),
9495                            };
9496                            self.judge_pr_language(&winner.worktree, &candidate).await
9497                        };
9498                        match gt::vet_title(
9499                            &text,
9500                            decision,
9501                            self.state.config.graph.github_english(),
9502                        ) {
9503                            Ok(title) => {
9504                                g.resolved = true;
9505                                g.chosen_title = Some(title);
9506                                g.choice = Some(GithubTextChoice::MyTitle);
9507                            }
9508                            Err(cats) if g.asks < 2 => {
9509                                ask_again = Some(Some(
9510                                    cats.into_iter().map(str::to_owned).collect::<Vec<_>>(),
9511                                ))
9512                            }
9513                            Err(_) => {
9514                                g.resolved = true;
9515                                g.chosen_title = None;
9516                                g.choice = Some(GithubTextChoice::Fallback);
9517                            }
9518                        }
9519                    }
9520                },
9521            }
9522            if let Some(rejected) = ask_again {
9523                // A retry (after a rejected replacement title) is still about
9524                // the original text: the same ORIGINAL / FALLBACK comparison.
9525                let w = gt::Withheld {
9526                    title: g.title,
9527                    body: g.body,
9528                    categories: g.categories.clone(),
9529                };
9530                // Named by the original text's fingerprint alone, so a resume
9531                // rewrites the same file and the detail stays identical.
9532                let artifact = match crate::run::write_artifact(
9533                    &self.state,
9534                    &gt::artifact_name(&gt::fingerprint(&pr.title, &pr.body)),
9535                    &gt::artifact_text(&w, &pr.title, &pr.body, &self.state.id, g.rewrite.as_ref()),
9536                ) {
9537                    Ok(p) => Some(p),
9538                    Err(e) => {
9539                        tracing::warn!("could not write the withheld-text artifact: {e:#}");
9540                        None
9541                    }
9542                };
9543                let (detail, comparison) = gt::question_content(
9544                    &w,
9545                    &pr.title,
9546                    &pr.body,
9547                    &self.state.id,
9548                    rejected.as_deref(),
9549                    artifact.as_deref(),
9550                    g.rewrite.as_ref(),
9551                );
9552                let mut q = ask::Question::new(
9553                    self.state.id.clone(),
9554                    gt::ASK_NODE.to_owned(),
9555                    gt::ASK_SEAT.to_owned(),
9556                    gt::question_summary(&self.state.config.graph.language, &w),
9557                    detail,
9558                    gt::question_choices(&w, g.rewrite.as_ref()),
9559                );
9560                q.posting_comparison = Some(comparison);
9561                q.answer_timeout = timeout;
9562                // Recorded before it is written: a stop in between leaves a
9563                // record naming a question the resume then files again.
9564                g.question = Some(q.id.clone());
9565                g.asks += 1;
9566                self.state.github_text = Some(g.clone());
9567                self.state.event(
9568                    "github-text",
9569                    format!("asking the owner about the withheld text ({})", q.short()),
9570                );
9571                self.state.save()?;
9572                store
9573                    .put_executable(&mut q)
9574                    .context("file the posting-gate question")?;
9575                if let Err(e) = ask::notify(&self.state.config.notify, &q).await {
9576                    tracing::warn!(
9577                        "could not notify about posting-gate question {}: {e:#}",
9578                        q.short()
9579                    );
9580                }
9581                self.park_on_github_text(&g)?;
9582                return Ok(None);
9583            }
9584        }
9585        let resolved = g.chosen_title.clone();
9586        let original = g.choice == Some(GithubTextChoice::Original);
9587        // Field names only: the event log never records the text.
9588        self.state.event(
9589            "github-text",
9590            if original {
9591                format!(
9592                    "posting the original text for: {}",
9593                    match (g.title, g.body) {
9594                        (true, true) => "title, description",
9595                        (true, false) => "title",
9596                        _ => "description",
9597                    }
9598                )
9599            } else if g.choice == Some(GithubTextChoice::Rewrite) && g.rewrite.is_some() {
9600                "posting the saved rewrite title and description".to_owned()
9601            } else if resolved.is_some() {
9602                "posting the owner's replacement title".to_owned()
9603            } else {
9604                "posting the neutral text for the withheld fields".to_owned()
9605            },
9606        );
9607        self.state.github_text = Some(g.clone());
9608        self.state.save()?;
9609        if g.choice == Some(GithubTextChoice::Rewrite)
9610            && let Some(r) = g.rewrite.as_ref()
9611        {
9612            return Ok(Some(PrMessage {
9613                title: r.title.clone(),
9614                body: r.body.clone(),
9615            }));
9616        }
9617        let w = gt::Withheld {
9618            title: g.title,
9619            body: g.body,
9620            categories: g.categories.clone(),
9621        };
9622        let (mut title, body) = gt::fallback_text(&w, &pr.title, &pr.body, &self.state.id);
9623        if let Some(t) = resolved {
9624            title = t;
9625        }
9626        // Every withheld field is now neutral or vetted English.
9627        let english = gt::LanguageDecision {
9628            title_english: true,
9629            body_english: true,
9630            body_complete: true,
9631        };
9632        let (mut title, mut body) = gt::prepare_with(&mut self.state, &title, &body, Some(english));
9633        if original {
9634            // The owner's explicit choice overrides the gate for the fields it
9635            // was made for; the others keep what the gate produced.
9636            if g.title {
9637                title = pr.title.clone();
9638            }
9639            if g.body {
9640                body = pr.body.clone();
9641            }
9642        }
9643        Ok(Some(PrMessage { title, body }))
9644    }
9645
9646    fn park_on_github_text(&mut self, g: &crate::run::GithubTextAsk) -> Result<()> {
9647        self.state.github_text = Some(g.clone());
9648        self.state.end_pass_parked(ParkCause::Question);
9649        self.state.parked = true;
9650        self.state.event(
9651            "github-text",
9652            "parked awaiting the owner's word on the withheld pull request text - resumes once answered",
9653        );
9654        self.state.save()
9655    }
9656
9657    /// Ask `[roles] language_judge` about this text and record which source
9658    /// decided; the text itself is never recorded.
9659    async fn judge_pr_language(
9660        &mut self,
9661        cwd: &Path,
9662        pr: &PrMessage,
9663    ) -> Option<crate::github_text::LanguageDecision> {
9664        self.state.config.roles.language_judge.as_ref()?;
9665        if !self.state.config.graph.language_gate() {
9666            return None;
9667        }
9668        let decision =
9669            crate::github_text::judge_language(&self.state.config, cwd, &pr.title, &pr.body).await;
9670        self.state.event(
9671            "github-text",
9672            if decision.is_some() {
9673                "language decided by the language judge"
9674            } else {
9675                "language judge unavailable; using built-in heuristics"
9676            },
9677        );
9678        decision
9679    }
9680
9681    fn merge(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
9682        Box::pin(self.merge_inner())
9683    }
9684
9685    async fn merge_inner(&mut self) -> Result<()> {
9686        if self.resource_halt()? || self.hold_base_sync().await? {
9687            return Ok(());
9688        }
9689        // Same reasoning as `gate`: ask the review and gate records directly
9690        // rather than `status`, which a solo-candidate `judge`/`deliberate`
9691        // skip can rewrite on reentry to something that no longer says
9692        // `Blocked`. `review_conclusion` is the same derivation `gate` uses,
9693        // so a hand-off (open findings, green verification) reaches merge
9694        // exactly like a genuinely clean round does.
9695        //
9696        // A run resumed mid-`land` never reaches here at all: `execute`
9697        // recognises `RunStatus::Landing` before it even calls `prep`, and
9698        // routes straight to `run_land` instead. That has to happen a level
9699        // up from this function, not with a check in here, because
9700        // `review_loop`'s own status recomputation (see its doc) runs
9701        // *before* `merge` on every reentry and would otherwise overwrite
9702        // the `Landing` marker with `Gating` before this node ever saw it.
9703        if self
9704            .state
9705            .base_sync
9706            .as_ref()
9707            .is_some_and(|s| s.conflict.is_some())
9708            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
9709                != Some(RunStatus::Gating)
9710            // `gate_ran == false` is not "passed" - `gate` leaves it false
9711            // both before it has ever run and when its last attempt was
9712            // resource-blocked (see `Runner::gate`'s own doc), and neither is
9713            // permission to merge on nothing but the review record. Only a
9714            // gate that actually ran may proceed; an intentional local
9715            // review can also finish with verification explicitly not configured.
9716            // `RunState::gate_status` computes that distinction.
9717            || !self.state.gate_allows_progress()
9718        {
9719            return Ok(());
9720        }
9721        // This node's own record, not `status`: `status == Ready` is not
9722        // unique to the harmless `MergeMode::None` path this line was
9723        // written for. `land` (below) sets it too, when a `MergeMode::Pr`
9724        // run's PR was closed without merging — and on that run `mode` is
9725        // still `Pr`, so a reentry that fell through here would push and
9726        // open a second pull request. `self.state.merge` is set exactly once
9727        // this node (or `land`) has already produced a verdict, under every
9728        // mode, which is what "already done" actually means here.
9729        if self.state.merge.is_some() && !self.state.pr_publication_pending {
9730            return Ok(());
9731        }
9732        let Some(winner) = self.state.winner().cloned() else {
9733            return Ok(());
9734        };
9735        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
9736        if self.state.gate_head.as_deref() != Some(head.as_str()) {
9737            self.state.status = RunStatus::Blocked;
9738            self.state.event(
9739                "gate",
9740                "winner changed after gate; fresh verification required",
9741            );
9742            self.state.save()?;
9743            return Ok(());
9744        }
9745        let wait = self.repository_wait();
9746        if !verify_current_head(&mut self.state, &winner, &wait).await? {
9747            return Ok(());
9748        }
9749        let repo = self.state.repo.clone();
9750        let base = self.state.base_branch.clone();
9751        let mode = self.state.config.merge.mode;
9752        let style = self.state.config.merge.style;
9753        let facts = if is_review_run(&self.state) {
9754            refresh_reviewed_commits(&mut self.state, &winner.branch).await;
9755            let start = review_base(
9756                &repo,
9757                &self.state.config.merge.remote,
9758                &base,
9759                &self.state.base_commit,
9760                &winner.branch,
9761            )
9762            .await;
9763            branch_facts(&repo, &start, &winner.branch).await
9764        } else {
9765            None
9766        };
9767        // `None` when the base could not be freshly read: then an adopted
9768        // pull request's title is left alone.
9769        let leaked = if is_review_run(&self.state) {
9770            leaked_subjects(&self.state, &winner.branch).await
9771        } else {
9772            Some(Vec::new())
9773        };
9774        // `None`: parked on the owner's word about a withheld title or body.
9775        // Nothing has been pushed or opened, and `merge` stays unrecorded so
9776        // the resume arrives here again.
9777        let Some(pr) = self
9778            .guarded_pr_message(&winner, facts.as_ref(), mode == MergeMode::Pr)
9779            .await?
9780        else {
9781            return Ok(());
9782        };
9783        let message = pr.commit_message();
9784
9785        let delivery_head = git::rev_parse(&winner.worktree, "HEAD").await?;
9786        if !crate::foreign_checkout::write_back(&mut self.state, &delivery_head).await? {
9787            return Ok(());
9788        }
9789        let outcome = match mode {
9790            MergeMode::None => MergeOutcome {
9791                mode,
9792                ok: true,
9793                detail: manual_merge_command(style, &repo, &winner.branch, &message),
9794                empty: false,
9795            },
9796            MergeMode::Pr | MergeMode::Local
9797                if merge_is_empty(&repo, &self.state, &winner.branch, mode).await =>
9798            {
9799                MergeOutcome {
9800                    mode,
9801                    ok: false,
9802                    detail: empty_candidate_detail(&self.state, &base),
9803                    empty: true,
9804                }
9805            }
9806            MergeMode::Local => {
9807                let on = git::current_branch(&repo).await?;
9808                if on.as_deref() != Some(base.as_str()) {
9809                    MergeOutcome {
9810                        mode,
9811                        ok: false,
9812                        detail: format!(
9813                            "{} has {} checked out, not the base branch {base}",
9814                            repo.display(),
9815                            on.unwrap_or_else(|| "a detached HEAD".to_owned())
9816                        ),
9817                        empty: false,
9818                    }
9819                } else if !git::is_clean(&repo).await? {
9820                    MergeOutcome {
9821                        mode,
9822                        ok: false,
9823                        detail: format!("{} is dirty; refusing to merge", repo.display()),
9824                        empty: false,
9825                    }
9826                } else {
9827                    let out = match style {
9828                        MergeStyle::Merge => {
9829                            git::merge_no_ff(&repo, &winner.branch, &message).await?
9830                        }
9831                        MergeStyle::Squash => {
9832                            git::merge_squash(&repo, &winner.branch, &message).await?
9833                        }
9834                        MergeStyle::Rebase => git::merge_ff_only(&repo, &winner.branch).await?,
9835                    };
9836                    MergeOutcome {
9837                        mode,
9838                        ok: out.ok(),
9839                        detail: if out.ok() { out.stdout } else { out.stderr },
9840                        empty: false,
9841                    }
9842                }
9843            }
9844            MergeMode::Pr if self.state.task_pr_branch().is_some() => {
9845                self.state.pr_publication_pending = true;
9846                self.state.save()?;
9847                let out =
9848                    crate::pr_head::publish(&mut self.state, &winner, &pr.title, &pr.body).await;
9849                self.state.pr_publication_pending = out.is_err();
9850                MergeOutcome {
9851                    mode,
9852                    ok: out.is_ok(),
9853                    detail: match out {
9854                        Ok(url) => url,
9855                        Err(e) => format!("{e:#}"),
9856                    },
9857                    empty: false,
9858                }
9859            }
9860            MergeMode::Pr => {
9861                let remote = self.state.config.merge.remote.clone();
9862                let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
9863                let pushed = if self.state.foreign_checkout.is_some() {
9864                    let refspec = format!("{delivery_head}:refs/heads/{public}");
9865                    git::git_raw(&winner.worktree, &["push", &remote, &refspec]).await?
9866                } else {
9867                    git::push(&winner.worktree, &remote, &winner.branch).await?
9868                };
9869                if !pushed.ok() {
9870                    MergeOutcome {
9871                        mode,
9872                        ok: false,
9873                        detail: pushed.stderr,
9874                        empty: false,
9875                    }
9876                } else {
9877                    if self.state.foreign_checkout.is_some() {
9878                        self.state.pr_pushed_head = Some(delivery_head.clone());
9879                    }
9880                    // A retry or resume of a run whose branch already has an
9881                    // open pull request adopts it rather than failing on a
9882                    // duplicate. Only this winner branch into this base:
9883                    // `branch_for` derives the name from the run id, so a
9884                    // different run's pull request never matches.
9885                    let found = land::find_open_pr(&winner.worktree, &public, &base).await;
9886                    let out = match pr_merge_plan(found) {
9887                        PrPlan::Create => {
9888                            gh_pr_create(&winner.worktree, &base, &public, &pr.title, &pr.body)
9889                                .await
9890                        }
9891                        PrPlan::Adopt { url, title } => {
9892                            self.state
9893                                .event("merge", format!("Pr: adopted open pull request {url}"));
9894                            if self.state.explicit_github_text_selection() {
9895                                // An explicit publication selection applies the prepared
9896                                // payload; acceptance alone is not publication proof.
9897                                land::set_pr_text_verbatim(
9898                                    &winner.worktree,
9899                                    &url,
9900                                    &pr.title,
9901                                    &pr.body,
9902                                )
9903                                .await
9904                                .map(|()| url)
9905                            } else {
9906                                if title != pr.title
9907                                    && (!is_review_run(&self.state)
9908                                        || leaked
9909                                            .as_deref()
9910                                            .is_some_and(|l| should_retitle(&title, &pr.title, l)))
9911                                    && let Err(e) =
9912                                        if self.state.github_text.as_ref().is_some_and(|g| {
9913                                            g.resolved
9914                                                && g.title
9915                                                && g.choice == Some(GithubTextChoice::Original)
9916                                        }) {
9917                                            // The owner chose to post this title unmodified.
9918                                            land::set_pr_title_verbatim(
9919                                                &winner.worktree,
9920                                                &url,
9921                                                &pr.title,
9922                                            )
9923                                            .await
9924                                        } else {
9925                                            land::set_pr_title(
9926                                                &mut self.state,
9927                                                &winner.worktree,
9928                                                &url,
9929                                                &pr.title,
9930                                            )
9931                                            .await
9932                                        }
9933                                {
9934                                    tracing::warn!("could not refresh title of {url}: {e:#}");
9935                                    self.state
9936                                        .event("merge", format!("Pr: title refresh failed: {e:#}"));
9937                                }
9938                                Ok(url)
9939                            }
9940                        }
9941                        PrPlan::Stop(why) => Err(anyhow::anyhow!(why)),
9942                    };
9943                    match out {
9944                        Ok(url) => MergeOutcome {
9945                            mode,
9946                            ok: true,
9947                            detail: url,
9948                            empty: false,
9949                        },
9950                        Err(e) => MergeOutcome {
9951                            mode,
9952                            ok: false,
9953                            detail: e.to_string(),
9954                            empty: false,
9955                        },
9956                    }
9957                }
9958            }
9959        };
9960
9961        self.state.status = match (mode, outcome.ok) {
9962            (MergeMode::None, _) => RunStatus::Ready,
9963            (_, true) if outcome.empty => RunStatus::Ready,
9964            (MergeMode::Pr, true) => RunStatus::Ready,
9965            (_, true) => RunStatus::Merged,
9966            (_, false) => RunStatus::Blocked,
9967        };
9968        self.state.event(
9969            "merge",
9970            format!(
9971                "{:?}: {}",
9972                mode,
9973                outcome.detail.lines().next().unwrap_or("")
9974            ),
9975        );
9976        if mode == MergeMode::Pr && outcome.ok && !outcome.empty {
9977            self.state.record_github_text_publication(&outcome.detail);
9978        }
9979        self.state.merge = Some(outcome);
9980        self.state.save()?;
9981
9982        // The PR is open and the run would historically stop here, leaving the
9983        // operator to watch checks, feed review comments back to a fixer, and
9984        // merge. That was done by hand six times in one session before this
9985        // existed. Opt-in, because merging is the one irreversible thing magi
9986        // can do to a repository.
9987        if self.state.config.graph.land
9988            && mode == MergeMode::Pr
9989            && self.state.merge.as_ref().is_some_and(|m| m.ok && !m.empty)
9990        {
9991            self.run_land().await?;
9992        }
9993        // `run_land` may have left `status` at `Landing` - still waiting on
9994        // CI or the owner's approval, not actually settled - so this has to
9995        // read whatever `status` ended up as here, not the `Merged` this
9996        // function set a few lines up.
9997        self.settle_questions();
9998        Ok(())
9999    }
10000
10001    /// Enter `land`.
10002    ///
10003    /// Shared between a fresh run's first pass through [`Runner::merge`] and
10004    /// a resumed run's re-entry. `land::land` itself is what serialises the
10005    /// two git-mutating moments inside the loop — the rebase push and
10006    /// `gh pr merge` — per repository (see its own doc); nothing here needs
10007    /// to hold a lock across the whole call, and doing so would serialise
10008    /// this run's CI wait against a *different* run's land-approval resume
10009    /// in the same repository, which is exactly the "must not wait on
10010    /// another task" property the daemon's slot-freeing exists to give.
10011    fn run_land(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
10012        Box::pin(self.run_land_inner())
10013    }
10014
10015    async fn run_land_inner(&mut self) -> Result<()> {
10016        crate::pr_head::ensure_owner(&self.state)?;
10017        let url = self
10018            .state
10019            .pr
10020            .as_ref()
10021            .map(|pr| pr.url.clone())
10022            .or_else(|| self.state.merge.as_ref().map(|m| m.detail.clone()))
10023            .unwrap_or_default();
10024        let url = url.lines().next().unwrap_or("").trim().to_owned();
10025        if !url.starts_with("http") {
10026            return Ok(());
10027        }
10028        // A land failure is not a lost run: the work is on a branch and the
10029        // pull request is open, which is exactly where a human takes over.
10030        loop {
10031            match land::land(&mut self.state, &url).await {
10032                Ok(_)
10033                    if self
10034                        .state
10035                        .merge_repairs
10036                        .last()
10037                        .is_some_and(|r| r.phase == crate::run::MergeRepairPhase::Requested) =>
10038                {
10039                    if self.repair_merge_review().await? {
10040                        continue;
10041                    }
10042                }
10043                Ok(_) if self.state.resource_block.is_some() => {
10044                    return self.stop_for_resource();
10045                }
10046                Ok(pr) if self.state.parked => {
10047                    // `land` already saved the parked marker; nothing here
10048                    // overrides `status` back to a terminal value while an
10049                    // approval is still outstanding.
10050                    let _ = pr;
10051                }
10052                Ok(_) if self.state.merge_decision.as_ref().is_some_and(|d| d.closed) => {
10053                    self.state.status = RunStatus::Superseded;
10054                    self.state.save()?;
10055                }
10056                Ok(pr) => {
10057                    self.state.status = match pr.state {
10058                        land::PrLifecycle::Merged => RunStatus::Merged,
10059                        _ => RunStatus::Blocked,
10060                    };
10061                    // Downstream of a confirmed merge only - see
10062                    // `bump::should_release_bump`'s own doc for why this one
10063                    // check covers all three of `land`'s success paths.
10064                    // Best-effort: the run already landed, so a failure here
10065                    // (the decision call, `gh`, `cargo`) is recorded and never
10066                    // turns a landed run into a failed one.
10067                    if bump::should_release_bump(self.state.status)
10068                        && let Err(e) = bump::after_merge(&mut self.state, &pr.url).await
10069                    {
10070                        // The event is the run's own record. Not-eligible cases
10071                        // (disabled, no `Cargo.toml`, ...) return `Ok`, so an
10072                        // `Err` is a bump that was tried and failed:
10073                        // `after_merge` itself raises the operator notice for
10074                        // that, whether or not a release PR exists yet.
10075                        self.state
10076                            .event("bump", format!("release bump skipped: {e:#}"));
10077                    }
10078                    // Independent of the bump, and best-effort in the same way:
10079                    // findings the merge left open become follow-up tasks.
10080                    if self.state.status == RunStatus::Merged {
10081                        crate::followup::after_merge(&mut self.state, &pr.url).await;
10082                    }
10083                    self.state.save()?;
10084                }
10085                Err(e) => {
10086                    if e.is::<crate::repo_lock::ResourceBlocked>() {
10087                        return Err(e);
10088                    }
10089                    self.state.status = RunStatus::Blocked;
10090                    self.state.event("land", format!("gave up: {e}"));
10091                    self.state.save()?;
10092                }
10093            }
10094            break;
10095        }
10096        Ok(())
10097    }
10098
10099    /// One repair cycle stays under the existing driver/task claim. An
10100    /// interrupted fixer is rolled back and held rather than run twice.
10101    async fn repair_merge_review(&mut self) -> Result<bool> {
10102        use crate::run::MergeRepairPhase as Phase;
10103        crate::pr_head::ensure_owner(&self.state)?;
10104        let i = self.state.merge_repairs.len() - 1;
10105        let request = self.state.merge_repairs[i].clone();
10106        if request.phase == Phase::Fixing {
10107            let restored = match self.state.winner().cloned() {
10108                Some(winner) => self.graft_restore(&winner.worktree, &request.head).await,
10109                None => Err(anyhow::anyhow!("repair has no winning branch")),
10110            };
10111            let why = match restored {
10112                Ok(()) => "repair was interrupted during the fixer and rolled back; inspect its artifacts and the PR head, then run an explicit review".to_owned(),
10113                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => return Err(e),
10114                Err(e) => format!("repair was interrupted; rollback failed: {e:#}; restore the reviewed branch before running an explicit review"),
10115            };
10116            self.hold_merge_repair(i, why)?;
10117            return Ok(false);
10118        }
10119        // A completed repair gate is a publication checkpoint. On reentry,
10120        // reject external changes before the ordinary gate path can replace
10121        // that evidence by verifying a new head. Requested repairs still
10122        // start their own review generation below.
10123        if request.phase == Phase::Reviewing && self.state.gate_ran {
10124            let winner = self
10125                .state
10126                .winner()
10127                .context("repair has no winning branch")?;
10128            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
10129            if self.state.gate_head.as_deref() != Some(head.as_str())
10130                || !git::is_clean(&winner.worktree).await?
10131            {
10132                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())?;
10133                return Ok(false);
10134            }
10135        }
10136        let failure = if i >= self.state.config.graph.land_rounds
10137            || self.state.config.graph.review_rounds == 0
10138        {
10139            Some("repair generation budget exhausted or review disabled; increase the configured budget and request a new review explicitly".to_owned())
10140        } else {
10141            None
10142        };
10143        if let Some(why) = failure {
10144            self.hold_merge_repair(i, why)?;
10145            return Ok(false);
10146        }
10147        if request.phase == Phase::Requested {
10148            let pr = match land::repair_preflight(&self.state, &request.pr, &request.head).await {
10149                Ok(pr) => pr,
10150                Err(e) => {
10151                    self.hold_merge_repair(i, format!("cannot resume repair: {e:#}; restore the reviewed PR branch and run an explicit review"))?;
10152                    return Ok(false);
10153                }
10154            };
10155            self.state.merge_repairs[i].phase = Phase::Fixing;
10156            self.state.land_approval = None;
10157            self.state.land_armed_head = None;
10158            self.state.save()?;
10159            // Serialize the exact records, including finding ids/details,
10160            // reconsideration reasons, final votes and verification output.
10161            let evidence = serde_json::to_string_pretty(&request)?;
10162            let reason = format!(
10163                "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}"
10164            );
10165            let budget = self.state.config.graph.land_rounds;
10166            let result = land::fix_round(&mut self.state, &pr, i + 1, budget, &reason, "").await;
10167            match result {
10168                Ok(land::Fixed::Committed { .. } | land::Fixed::Declined) => {}
10169                Ok(land::Fixed::Deferred) => {
10170                    // An unavailable fixer did not spend this repair request.
10171                    // Restore partial fallback work before retrying it, as for
10172                    // an interrupted repair, without closing the request.
10173                    let worktree = self
10174                        .state
10175                        .winner()
10176                        .context("repair has no winning branch")?
10177                        .worktree
10178                        .clone();
10179                    self.graft_restore(&worktree, &request.head).await?;
10180                    self.state.merge_repairs[i].phase = Phase::Requested;
10181                    self.stop_for_resource()?;
10182                    return Ok(false);
10183                }
10184                Ok(land::Fixed::Failed(why)) => {
10185                    self.hold_merge_repair(
10186                        i,
10187                        format!(
10188                            "repair failed: {why}; inspect the branch and run an explicit review"
10189                        ),
10190                    )?;
10191                    return Ok(false);
10192                }
10193                Err(e) => {
10194                    self.hold_merge_repair(
10195                        i,
10196                        format!(
10197                            "repair failed: {e:#}; inspect the branch and run an explicit review"
10198                        ),
10199                    )?;
10200                    return Ok(false);
10201                }
10202            }
10203            // Even no change gets a real new reviewer wave. The previous
10204            // evidence remains in the request; a former clean/concluded round
10205            // cannot short-circuit the new review or gate.
10206            self.begin_merge_repair_review(i)?;
10207        }
10208        self.review_loop().await?;
10209        self.gate().await?;
10210        if self.resource_halt()? || self.state.parked {
10211            return Ok(false);
10212        }
10213        if review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
10214            != Some(RunStatus::Gating)
10215            || !self.state.gate_allows_progress()
10216        {
10217            self.hold_merge_repair(i, "updated review or gate did not pass; inspect the new results and resume review explicitly".to_owned())?;
10218            return Ok(false);
10219        }
10220        // Review and gate may have added commits after the initial repair.
10221        // Publish exactly their final head to the existing PR, with a lease.
10222        let winner = self
10223            .state
10224            .winner()
10225            .cloned()
10226            .context("repair has no winning branch")?;
10227        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
10228        if self.state.gate_head.as_deref() != Some(after.as_str())
10229            || !git::is_clean(&winner.worktree).await?
10230        {
10231            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())?;
10232            return Ok(false);
10233        }
10234        let expected = self
10235            .state
10236            .pr_pushed_head
10237            .as_deref()
10238            .unwrap_or(&request.head)
10239            .to_owned();
10240        let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
10241        // Push the checked commit itself: a local ref moving after the check
10242        // must not change which commit the forge receives.
10243        if !crate::foreign_checkout::write_back(&mut self.state, &after).await? {
10244            return Ok(false);
10245        }
10246        let lease = format!("--force-with-lease=refs/heads/{public}:{expected}");
10247        let refspec = format!("{after}:refs/heads/{public}");
10248        let push = git::git_raw(
10249            &winner.worktree,
10250            &["push", &lease, &self.state.config.merge.remote, &refspec],
10251        )
10252        .await;
10253        match push {
10254            Ok(out) if out.ok() => self.state.pr_pushed_head = Some(after),
10255            Ok(out) => {
10256                self.hold_merge_repair(i, format!("publishing reviewed repair failed: {}; inspect the PR head and resume review explicitly", out.stderr))?;
10257                return Ok(false);
10258            }
10259            Err(e) => {
10260                self.hold_merge_repair(i, format!("publishing reviewed repair failed: {e:#}; inspect the PR head and resume review explicitly"))?;
10261                return Ok(false);
10262            }
10263        }
10264        self.state.merge_repairs[i].phase = Phase::Complete;
10265        self.state.status = RunStatus::Landing;
10266        self.state.event(
10267            "repair",
10268            "new review and gate completed; fresh owner merge decision required",
10269        );
10270        self.state.save()?;
10271        Ok(true)
10272    }
10273
10274    fn merge_repair_artifacts(&self) -> PathBuf {
10275        let artifacts = agent::artifacts_dir(&self.state.dir());
10276        match self
10277            .state
10278            .merge_repairs
10279            .last()
10280            .filter(|r| r.phase == crate::run::MergeRepairPhase::Reviewing)
10281        {
10282            Some(r) => artifacts.join(format!("merge-repair-{}", r.question)),
10283            None => artifacts,
10284        }
10285    }
10286
10287    fn begin_merge_repair_review(&mut self, index: usize) -> Result<()> {
10288        if let Some(e2e) = self.state.head_e2e.take() {
10289            self.state
10290                .verification_history
10291                .push(crate::run::VerificationEvidence {
10292                    superseded_by: None,
10293                    archived_at: Some(Timestamp::now()),
10294                    fixes_spent: Some(self.state.gate_fixes.len()),
10295                    gate_head: None,
10296                    gate_ran: false,
10297                    gate: Vec::new(),
10298                    e2e: Some(e2e),
10299                });
10300        }
10301        self.state.reviews.clear();
10302        self.state.gate.clear();
10303        self.state.gate_ran = false;
10304        self.state.gate_head = None;
10305        self.state.gate_fixes.clear();
10306        self.state.gate_repair_e2e = None;
10307        self.state.pre_gate.clear();
10308        self.state.pre_gate_commit = None;
10309        self.state.contested_handoff = None;
10310        self.state.land_reruns = None;
10311        self.state.land_approval = None;
10312        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Reviewing;
10313        self.state.status = RunStatus::Reviewing;
10314        self.state.save()
10315    }
10316
10317    fn hold_merge_repair(&mut self, index: usize, why: String) -> Result<()> {
10318        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Failed;
10319        self.state.merge_repairs[index].failure = Some(why.clone());
10320        self.state.status = RunStatus::Blocked;
10321        self.state.event("repair", why);
10322        self.state.save()
10323    }
10324
10325    // -------------------------------------------------------------- helpers
10326
10327    /// Fetch or create a seat, keeping its conversation across nodes.
10328    fn seat(&mut self, key: &str, agent: &str) -> SeatState {
10329        if let Some(existing) = self.state.seats.get(key)
10330            && existing.agent == agent
10331        {
10332            return existing.clone();
10333        }
10334        // A seat that changes agent mints its session id from the agent too,
10335        // like a handover: the old agent's uuid is already taken by the CLI.
10336        let fresh = if self.state.seats.contains_key(key) {
10337            handover_seat(key, agent, self.state.next_seat_seed())
10338        } else {
10339            SeatState::new(key, agent, self.state.seed)
10340        };
10341        self.state.seats.insert(key.to_owned(), fresh.clone());
10342        fresh
10343    }
10344
10345    /// The agent now holding seat `key`: `spec`, unless a handover moved the
10346    /// seat to another roster agent, in which case that agent. Nodes that
10347    /// continue a seat's conversation (deliberation, the votes, a reviewer's
10348    /// reconsideration) must keep talking to whoever answered it, not slip
10349    /// back to the agent that failed it.
10350    fn occupant(&self, key: &str, spec: AgentSpec) -> AgentSpec {
10351        match self.state.seats.get(key) {
10352            Some(s) if s.agent != spec.id => {
10353                self.state.config.agent(&s.agent).cloned().unwrap_or(spec)
10354            }
10355            _ => spec,
10356        }
10357    }
10358
10359    /// A candidate rendered for judging, with the leak policy applied.
10360    fn view(&self, c: &Candidate) -> CandidateView {
10361        let raw = crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
10362            .unwrap_or_default();
10363        let (patch, _) = blind::sanitize_patch(
10364            &format!("candidate {} patch", c.label),
10365            &raw,
10366            &self.state.config.blind,
10367        );
10368        CandidateView {
10369            label: c.label,
10370            branch: c.branch.clone(),
10371            summary: c.summary.clone(),
10372            stat: c.stat.clone(),
10373            patch,
10374        }
10375    }
10376
10377    /// The full candidate set as prompt text, for seats with no live session.
10378    fn candidate_block(&self, candidates: &[Candidate], base_short: &str) -> String {
10379        let views: Vec<CandidateView> = candidates.iter().map(|c| self.view(c)).collect();
10380        prompt::judge(
10381            "(see above)",
10382            &views,
10383            self.roles.judges.len(),
10384            base_short,
10385            "en",
10386        )
10387    }
10388
10389    /// The final-vote prompt with everything a seat that has no session of its
10390    /// own needs: the candidates, the seat's own ranking and reasons, and the
10391    /// anonymised deliberation it took part in (only when there was one, so a
10392    /// handed-over seat never sees more than the seat it replaces did). The
10393    /// `Final vote` heading stays first.
10394    fn vote_prompt_full(
10395        &self,
10396        j: usize,
10397        labels: &[char],
10398        language: &str,
10399        candidates: &[Candidate],
10400        base_short: &str,
10401    ) -> String {
10402        let mut text = format!(
10403            "{}\n\n# The task the candidates were given\n\n{}\n\n# Candidates\n\n{}",
10404            prompt::final_vote(labels, language),
10405            self.state.instruction,
10406            self.candidate_block(candidates, base_short)
10407        );
10408        if let Some(own) = self
10409            .state
10410            .judgements
10411            .get(j)
10412            .filter(|r| !r.ranking.is_empty())
10413        {
10414            let reasons = own
10415                .reasons
10416                .iter()
10417                .map(|(k, v)| format!("- {k}: {v}"))
10418                .collect::<Vec<_>>()
10419                .join("\n");
10420            text.push_str(&format!(
10421                "\n\n# Your own earlier ranking\n\nYou ranked {}{}{reasons}\n",
10422                own.ranking.iter().collect::<String>(),
10423                if reasons.is_empty() {
10424                    ""
10425                } else {
10426                    ", because:\n"
10427                }
10428            ));
10429        }
10430        if !self.state.deliberation.is_empty() {
10431            text.push_str("\n# What was argued before this vote\n");
10432            for t in self.transcript(&[], j) {
10433                text.push_str(&format!(
10434                    "\n## {}{}\n\n{}\n",
10435                    t.who,
10436                    if t.is_self { " (you)" } else { "" },
10437                    t.body.trim()
10438                ));
10439            }
10440        }
10441        text
10442    }
10443
10444    /// Anonymised transcript for judge `self_idx`.
10445    ///
10446    /// The initial rankings are always the opening statements. Seeding them
10447    /// only when no turn had been taken yet meant every judge after the first
10448    /// argued against a single voice instead of against the actual split — the
10449    /// disagreement is the information, so it is always on the table.
10450    fn transcript(&self, current: &[DeliberationTurn], self_idx: usize) -> Vec<Turn> {
10451        let mut turns = Vec::new();
10452        for j in &self.state.judgements {
10453            if j.ranking.is_empty() {
10454                continue;
10455            }
10456            let reasons = j
10457                .reasons
10458                .iter()
10459                .map(|(k, v)| format!("- {k}: {v}"))
10460                .collect::<Vec<_>>()
10461                .join("\n");
10462            turns.push(Turn {
10463                who: format!("Judge {} (opening ranking)", j.judge),
10464                is_self: j.judge == self_idx + 1,
10465                body: format!(
10466                    "Ranked {}{}{reasons}",
10467                    j.ranking.iter().collect::<String>(),
10468                    if reasons.is_empty() {
10469                        ""
10470                    } else {
10471                        ", because:\n"
10472                    }
10473                ),
10474            });
10475        }
10476        for t in self
10477            .state
10478            .deliberation
10479            .iter()
10480            .flat_map(|r| r.turns.iter())
10481            .chain(current)
10482        {
10483            turns.push(Turn {
10484                who: format!("Judge {}", t.judge),
10485                is_self: t.judge == self_idx + 1,
10486                body: t.body.clone(),
10487            });
10488        }
10489        turns
10490    }
10491}
10492
10493/// Does this seat still hold the context a follow-up prompt would rely on?
10494fn has_context(spec: &AgentSpec, seat: &SeatState, sessions: bool) -> bool {
10495    agent::has_session(spec.kind, seat, sessions)
10496}
10497
10498/// The next entry in `roster` after `start`, never wrapping back to the
10499/// front, whose id is not in `tried` yet.
10500///
10501/// Starts one past `start` rather than at the front of `roster`: `start` is
10502/// the seat's own original position, and a seat whose candidate slot already
10503/// sits on the roster's second entry must fall through to the third next, not
10504/// restart at the first — which is very likely a different candidate's own
10505/// agent already. Never wraps back past `start`, for the same reason: an
10506/// entry earlier in the roster than the seat's own position is almost
10507/// certainly some *other* candidate slot's own agent, and once the tail of
10508/// the roster is exhausted there are no more untried agents for *this* seat
10509/// to fall through to — the caller's fallback chain ends there, exactly as
10510/// "no further untried agents remain in the list for that seat" asks for.
10511///
10512/// Matched by [`AgentSpec::id`], never the whole spec: a roster that names
10513/// the same id twice (an operator's `roles.implementers` typo, or a
10514/// `[[agents]]` list reused across roles) must not let
10515/// [`Runner::resume_seat_handovers`] retry that id forever — one forward pass
10516/// over `roster` either finds an untried id or runs out, so this always
10517/// terminates regardless of duplicates.
10518fn next_untried_in_roster<'a>(
10519    roster: &'a [AgentSpec],
10520    start: usize,
10521    tried: &BTreeSet<String>,
10522) -> Option<&'a AgentSpec> {
10523    roster
10524        .get(start + 1..)?
10525        .iter()
10526        .find(|s| !tried.contains(&s.id))
10527}
10528
10529/// The successor for a seat, shared by all four seat kinds (implement, judge,
10530/// review, advise). `others` holds the ids that *currently* occupy the other
10531/// seats of the same wave (after any earlier handover, as [`Runner::occupant`]
10532/// sees them), so roster entries beyond the seat count act as spares: a failed
10533/// seat goes to an agent no other seat holds whenever the roster permits.
10534///
10535/// `carried` is `Some` only for the review loop's carried failure history.
10536/// Order: (1) forward from `start`, never wrapping, untried, not a carried
10537/// failure, not another seat's occupant; (2) with `carried`, a rescue over the
10538/// whole roster: untried and not another seat's occupant; (3) the plain walk
10539/// ([`next_untried_in_roster`] / [`next_for_seat`]) that ignores `others`.
10540/// Step 3 is deliberate: a duplicate agent on two seats is a worse panel but
10541/// a better outcome than an empty seat, and it keeps the answer to "is there
10542/// a successor at all" exactly what it was before occupants were considered,
10543/// so no handover rule (`should_hand_over`, nudges, the tried-once bound)
10544/// moves. The rescue excludes occupants too, on the same reasoning: retrying a
10545/// carried failure is a cheaper bet than doubling an agent on the panel, and
10546/// if it fails again `tried` bounds it and step 3 takes over. Seats failing in
10547/// the same round are handled one at a time, so a seat later in the batch
10548/// sees an earlier one's new occupant but not yet its own freed agent.
10549fn pick_successor<'a>(
10550    roster: &'a [AgentSpec],
10551    start: usize,
10552    tried: &BTreeSet<String>,
10553    carried: Option<&BTreeSet<String>>,
10554    others: &BTreeSet<String>,
10555) -> Option<&'a AgentSpec> {
10556    let free = |s: &&AgentSpec| !tried.contains(&s.id) && !others.contains(&s.id);
10557    roster
10558        .get(start + 1..)
10559        .and_then(|tail| {
10560            tail.iter()
10561                .filter(free)
10562                .find(|s| carried.is_none_or(|c| !c.contains(&s.id)))
10563        })
10564        .or_else(|| {
10565            carried
10566                .is_some()
10567                .then(|| roster.iter().find(free))
10568                .flatten()
10569        })
10570        .or_else(|| match carried {
10571            Some(c) => next_for_seat(roster, start, tried, c),
10572            None => next_untried_in_roster(roster, start, tried),
10573        })
10574}
10575
10576/// The next agent for a seat that carries its failure history across rounds
10577/// (the review loop). `round_tried` is this round's own bound and starts
10578/// empty every round; `carried_failed` only decides priority.
10579///
10580/// First: an id walking forward from `start`, never wrapping, that is neither
10581/// tried this round nor failed in an earlier one. Only when that is exhausted
10582/// does it rescue: the first roster id (in roster order, so this one *does*
10583/// look before `start`) not yet tried this round, which is by then a carried
10584/// failure. Each id is rescued at most once per round, so it cannot loop.
10585fn next_for_seat<'a>(
10586    roster: &'a [AgentSpec],
10587    start: usize,
10588    round_tried: &BTreeSet<String>,
10589    carried_failed: &BTreeSet<String>,
10590) -> Option<&'a AgentSpec> {
10591    roster
10592        .get(start + 1..)?
10593        .iter()
10594        .find(|s| !round_tried.contains(&s.id) && !carried_failed.contains(&s.id))
10595        .or_else(|| roster.iter().find(|s| !round_tried.contains(&s.id)))
10596}
10597
10598/// Where a reviewer seat starts a round: the agent that last answered it when
10599/// it is still on the roster and not marked failed, else the spec's own agent
10600/// unless it failed, else the next roster agent that has not failed, else the
10601/// spec's own agent again (the whole roster failed). Ids no longer on the
10602/// roster are ignored. An empty roster has no handover, so the spec stands.
10603fn pick_start_spec(roster: &[AgentSpec], spec: AgentSpec, hist: Option<&SeatHistory>) -> AgentSpec {
10604    let Some(h) = hist.filter(|_| !roster.is_empty()) else {
10605        return spec;
10606    };
10607    let ok = |id: &str| !h.failed.contains(id);
10608    if let Some(last) = h.last_ok.as_deref()
10609        && ok(last)
10610        && let Some(s) = roster.iter().find(|s| s.id == last)
10611    {
10612        return s.clone();
10613    }
10614    if ok(&spec.id) {
10615        return spec;
10616    }
10617    let from = roster.iter().position(|s| s.id == spec.id).unwrap_or(0);
10618    roster
10619        .get(from + 1..)
10620        .into_iter()
10621        .flatten()
10622        .chain(roster.iter())
10623        .find(|s| ok(&s.id))
10624        .cloned()
10625        .unwrap_or(spec)
10626}
10627
10628/// A fresh seat for the agent taking over `key`. Mixes the agent id into the
10629/// seed so a CLI that mints its session id up front (`--session-id`) never
10630/// reuses the uuid the previous agent already opened under the same seat key.
10631pub(crate) fn handover_seat(key: &str, agent: &str, run_seed: u64) -> SeatState {
10632    SeatState::new(key, agent, run_seed ^ crate::rng::fnv1a(agent))
10633}
10634
10635/// What an agent's turn timed out as, in [`AgentOutcome::Failed`]. One const
10636/// so the classifier below and the code that builds the message cannot drift.
10637const TIMED_OUT: &str = "timed out";
10638
10639impl FailClass {
10640    /// `None` for an answer; otherwise how the turn failed.
10641    fn of(out: &AgentOutcome) -> Option<Self> {
10642        match out {
10643            AgentOutcome::Ok(_) => None,
10644            AgentOutcome::Quota(_) => Some(Self::Quota),
10645            AgentOutcome::Dropped(_) => Some(Self::Other("dropped".to_owned())),
10646            AgentOutcome::Failed(e) if e == TIMED_OUT => Some(Self::Timeout),
10647            AgentOutcome::Failed(e) => Some(Self::Other(failure_signature(e))),
10648            // Not a failure of the agent. Callers check for it first; `None`
10649            // here means "no class to hand over on".
10650            AgentOutcome::ResourceBlocked(_) => None,
10651        }
10652    }
10653
10654    /// The word in a handover's artifact stem (`impl-A-quota-beta`).
10655    fn stem_word(&self) -> &'static str {
10656        match self {
10657            Self::Quota => "quota",
10658            _ => "handover",
10659        }
10660    }
10661}
10662
10663/// The message's first line with its variable parts removed — digit runs and
10664/// path-like tokens — so "exit code 2" and "exit code 7" read
10665/// as one kind of failure.
10666fn failure_signature(msg: &str) -> String {
10667    let mut line = msg.lines().next().unwrap_or("").trim().to_lowercase();
10668    // `SeatHistory::last_fail` persists these signatures across resumes. Keep
10669    // the historical machine key while the process diagnosis uses readable prose.
10670    if let Some(code) = line
10671        .strip_prefix("process exited with no usable output (exit code ")
10672        .and_then(|s| s.strip_suffix(')'))
10673        .and_then(|s| s.parse::<i32>().ok())
10674    {
10675        line = format!("exited with some({code}) and no usable output");
10676    } else if matches!(
10677        line.as_str(),
10678        "process exited with no usable output (no exit code reported)"
10679            | "process exited with no usable output (exit code unavailable)"
10680    ) {
10681        line = "exited with none and no usable output".to_owned();
10682    }
10683    let mut out = Vec::new();
10684    for word in line.split_whitespace() {
10685        if word.contains('/') || word.contains('\\') {
10686            out.push("<path>".to_owned());
10687            continue;
10688        }
10689        let mut w = String::new();
10690        let mut in_digits = false;
10691        for c in word.chars() {
10692            if c.is_ascii_digit() {
10693                if !in_digits {
10694                    w.push('#');
10695                }
10696                in_digits = true;
10697            } else {
10698                in_digits = false;
10699                w.push(c);
10700            }
10701        }
10702        out.push(w);
10703    }
10704    out.join(" ").chars().take(120).collect()
10705}
10706
10707/// Whether a seat that just failed with `cur` may go to the next roster agent.
10708/// A quota or a timeout always may. Any other failure may not when the agent
10709/// before it failed the same way: an error the prompt causes would otherwise
10710/// walk the whole roster. `prev` is the class of the immediately preceding
10711/// agent's failure, so a quota or timeout in between breaks the run of
10712/// identical failures by itself.
10713fn should_hand_over(prev: Option<&FailClass>, cur: &FailClass) -> bool {
10714    match cur {
10715        FailClass::Quota | FailClass::Timeout => true,
10716        FailClass::Other(_) => prev != Some(cur),
10717    }
10718}
10719
10720/// A short human reason for a failed outcome, for the handover record.
10721fn fail_reason(out: &AgentOutcome) -> String {
10722    match out {
10723        AgentOutcome::Ok(_) => String::new(),
10724        AgentOutcome::Quota(_) => "rate limited (quota)".to_owned(),
10725        AgentOutcome::Dropped(o) => format!(
10726            "the CLI dropped the stream ({})",
10727            o.dropped
10728                .as_ref()
10729                .map(|d| d.why.as_str())
10730                .unwrap_or("it ended without delivering its answer")
10731        ),
10732        AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
10733            e.lines().next().unwrap_or("").chars().take(160).collect()
10734        }
10735    }
10736}
10737
10738/// Note one handover in the run: the structured record and, in the timeline,
10739/// the sentence a person reads. A quota keeps the wording it always had.
10740pub(crate) fn record_handover(
10741    state: &mut RunState,
10742    node: &str,
10743    seat: &str,
10744    from: &str,
10745    to: &str,
10746    class: &FailClass,
10747    reason: &str,
10748) {
10749    let message = if *class == FailClass::Quota {
10750        format!("{seat}: rate limited (quota) on {from}; retrying with {to}")
10751    } else {
10752        format!("{seat}: handed over {from} -> {to} ({reason})")
10753    };
10754    state.event(node, message);
10755    state.handovers.push(Handover {
10756        at: Timestamp::now(),
10757        node: node.to_owned(),
10758        seat: seat.to_owned(),
10759        from: from.to_owned(),
10760        to: to.to_owned(),
10761        reason: reason.to_owned(),
10762    });
10763}
10764
10765/// Did this reply report running a command whose own CLI never confirmed an
10766/// exit status?
10767///
10768/// An [`agent::CommandEvidence`] only ever exists when the CLI reported the
10769/// command *finished* (see that type's own doc), so this can only be `true`
10770/// for a command whose completion event carried no readable exit code — not
10771/// for one that simply is not mentioned at all. That is the one signal this
10772/// crate can read, from the same record `state.jobs` renders, about a reply
10773/// standing next to work its own CLI cannot vouch for finishing; it is
10774/// deliberately not a check on the exit code's *value* (a fixer legitimately
10775/// runs a command that fails mid-iteration before it succeeds) and not a
10776/// guess at a command still running in the background (which emits no event
10777/// at all, and so leaves no evidence here to find).
10778fn has_unconfirmed_command(commands: &[agent::CommandEvidence]) -> bool {
10779    commands.iter().any(|c| c.exit_code.is_none())
10780}
10781
10782/// Whether a `NO CHANGE NEEDED` marker in an implementer's reply should be
10783/// trusted as a verified no-op — the adoption guard's own text-level half.
10784///
10785/// `usable` is the caller's `AgentOutput::usable()` (a clean CLI exit, not
10786/// timed out): a marker only earns the benefit of the doubt from a turn the
10787/// CLI itself vouches for finishing properly, the same house style
10788/// `resume_unconfirmed_commands` and `continue_fix_report` already hold a
10789/// *fix* report to for `commands`. A candidate that timed out, exited
10790/// non-zero, or left a command unconfirmed is read as the ordinary loss it
10791/// is, whatever prose it wrote — this returns `None` before it ever looks at
10792/// `text`. The remaining guards (the tree really is empty, the evidence is
10793/// non-empty) are the caller's: this only reads what the reply *claimed*.
10794fn verified_noop_claim(
10795    usable: bool,
10796    commands: &[agent::CommandEvidence],
10797    text: &str,
10798) -> Option<String> {
10799    (usable && !has_unconfirmed_command(commands))
10800        .then(|| verdict::verified_noop(text))
10801        .flatten()
10802}
10803
10804fn short(commit: &str) -> String {
10805    commit.chars().take(7).collect()
10806}
10807
10808fn make_executable(path: &Path) -> Result<()> {
10809    #[cfg(unix)]
10810    {
10811        use std::os::unix::fs::PermissionsExt as _;
10812        let mut perms = std::fs::metadata(path)?.permissions();
10813        perms.set_mode(0o755);
10814        std::fs::set_permissions(path, perms)?;
10815    }
10816    #[cfg(not(unix))]
10817    {
10818        let _ = path;
10819    }
10820    Ok(())
10821}
10822
10823/// What every seat in one batch shares: where the answers are attributed, the
10824/// prompt overlay they inherit, and the build cache they are told to use.
10825///
10826/// A struct rather than four more parameters: `wave` also needs the run's
10827/// state (to record who is answering right now) and the attempt number, and
10828/// eight positional arguments is both unreadable and a clippy error.
10829struct WaveCtx<'a> {
10830    /// Exported as `MAGI_RUN`, so a task an agent files names the run that
10831    /// paid for it.
10832    run: &'a str,
10833    /// Exported as `MAGI_NODE`, and the key the prompt overlay is chosen by.
10834    node: &'a str,
10835    prompts: &'a Prompts,
10836    /// The shared `CARGO_TARGET_DIR`, when the config declares one.
10837    cache: Option<&'a Path>,
10838    /// The review round this wave belongs to, for `"review"`/`"fix"` — see
10839    /// `JobRecord::round`. `None` for every other node.
10840    round: Option<usize>,
10841    /// Carry each seat's failed-agent history across waves (the review loop
10842    /// only): start-of-round priority and handover choice read
10843    /// [`RunState::seat_history`], and every answer or failure writes it.
10844    carry_seats: bool,
10845    /// The run's park / interrupt requests, so a wait for a shared resource
10846    /// can be abandoned the moment the operator asks to park.
10847    pauses: Option<(&'a Pause, &'a Pause)>,
10848}
10849
10850/// Shared scheduling policy for operations and spawned seat invocations.
10851fn repository_wait(
10852    state: &RunState,
10853    pauses: Option<(&Pause, &Pause)>,
10854) -> crate::repo_lock::WaitPolicy {
10855    let pauses = pauses.map(|(a, b)| (a.clone(), b.clone()));
10856    let inherited = crate::repo_lock::WaitPolicy::current();
10857    crate::repo_lock::WaitPolicy::new(
10858        Duration::from_secs(state.config.graph.timeout_resource_wait),
10859        move || {
10860            inherited.cancelled()
10861                || pauses
10862                    .as_ref()
10863                    .is_some_and(|(a, b)| a.parked() || b.parked())
10864        },
10865    )
10866}
10867
10868fn record_repository_block(state: &mut RunState, error: &anyhow::Error) {
10869    if let Some(timeout) = error.downcast_ref::<agent::IsolatedSeatWait>() {
10870        state.event("resource", timeout.0.description());
10871        state.resource_block = Some(timeout.0.clone());
10872        return;
10873    }
10874    if error.is::<crate::repo_lock::ResourceBlocked>() {
10875        state.resource_block = Some(crate::run::ResourceBlock {
10876            cause: crate::run::ResourceBlockCause::Other,
10877            node: "repository".into(),
10878            kind: if error.is::<crate::build_target::AdmissionDiskWait>() {
10879                "disk admission"
10880            } else if error.to_string().contains("disk pressure") {
10881                "disk pressure"
10882            } else if error.to_string().contains("disk admission") {
10883                "disk admission"
10884            } else if error.to_string().contains(crate::incremental::BLOCKED) {
10885                "incremental cache admission"
10886            } else {
10887                "repository coordination"
10888            }
10889            .into(),
10890            detail: format!("{error:#}"),
10891            at: Timestamp::now(),
10892        });
10893        state.event("resource", error.to_string());
10894    }
10895}
10896
10897async fn coordinate_operation(
10898    state: &mut RunState,
10899    cwd: &Path,
10900    wait: &crate::repo_lock::WaitPolicy,
10901) -> Result<Option<crate::repo_lock::SeatLease>> {
10902    let result =
10903        crate::repo_lock::SeatLease::operation_with(cwd, state.config.coordination.as_ref(), wait)
10904            .await;
10905    if let Err(e) = &result {
10906        record_repository_block(state, e);
10907    }
10908    result
10909}
10910
10911/// Run one job, honouring the parallelism budget.
10912async fn run_one(
10913    job: SeatJob,
10914    sem: Arc<Semaphore>,
10915    ctx: &WaveCtx<'_>,
10916    state: &mut RunState,
10917    attempt: usize,
10918) -> (SeatState, AgentOutcome) {
10919    let (_, seat, out) = wave(vec![job], sem, ctx, state, attempt)
10920        .await
10921        .pop()
10922        .expect("one job in, one result out");
10923    (seat, out)
10924}
10925
10926/// Run every job concurrently, capped by the semaphore, preserving order.
10927///
10928/// Every seat in the batch is recorded into [`RunState::active`] before the
10929/// wave starts and cleared as each answer lands, so the run's own record says
10930/// who is still being waited on rather than only who finished.
10931async fn wave(
10932    jobs: Vec<SeatJob>,
10933    sem: Arc<Semaphore>,
10934    ctx: &WaveCtx<'_>,
10935    state: &mut RunState,
10936    attempt: usize,
10937) -> Vec<(usize, SeatState, AgentOutcome)> {
10938    let WaveCtx {
10939        run,
10940        node,
10941        prompts,
10942        cache,
10943        round,
10944        carry_seats: _,
10945        pauses,
10946    } = *ctx;
10947    let cache = cache.filter(|_| !crate::build_target::isolated(&state.config));
10948    for job in &jobs {
10949        state.seat_started(node, &job.seat.key, job.timeout, attempt);
10950    }
10951    if let Err(e) = state.save() {
10952        // A failed persist of "who is answering right now" must not abort the
10953        // wave: the seats are already being asked, and the alternative is
10954        // losing the answers to save a status line nobody may even be
10955        // watching.
10956        tracing::warn!("could not persist in-progress seats: {e:#}");
10957    }
10958    // Shared-mode waves keep their existing single lease. Isolated writers
10959    // acquire their own checkout's target at seat admission.
10960    let jobs_had_a_writer = jobs.iter().any(|j| j.allow_write);
10961    // The wait for the lease has its own bound, `timeout_resource_wait`; it is
10962    // never borrowed from a job's agent budget (and never charged to it either,
10963    // see below). The agent's clock starts in `agent::invoke`, at spawn.
10964    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
10965    let cache_guard = if let Some(cache_dir) = cache {
10966        if jobs_had_a_writer {
10967            let owner = crate::cache::Owner::here(run, node, "*", Path::new("(wave)"), "");
10968            let cancel = move || pauses.is_some_and(|(a, b)| a.parked() || b.parked());
10969            match acquire_cache_lease(
10970                state,
10971                cache_dir,
10972                &owner,
10973                resource_limit,
10974                node,
10975                node,
10976                &cancel,
10977            )
10978            .await
10979            {
10980                Ok(Some(g)) => Some(g),
10981                // Parking: leave without spawning anything. The run parks at
10982                // the next boundary and the seats are asked afresh on resume.
10983                Ok(None) => {
10984                    if let Some(block) = &mut state.resource_block {
10985                        block.cause = crate::run::ResourceBlockCause::Cancelled {
10986                            park: pauses.and_then(|(a, b)| b.cause().or_else(|| a.cause())),
10987                        };
10988                    }
10989                    return block_wave(
10990                        jobs,
10991                        state,
10992                        node,
10993                        attempt,
10994                        "parked while waiting for the shared build cache",
10995                    );
10996                }
10997                // An unreadable lease is not contention: keep the old
10998                // fallback (no shared cache for this wave's seats).
10999                Err(e) if e.downcast_ref::<CacheCheckError>().is_some() => None,
11000                Err(e) => {
11001                    // Writing seats may not build into a cache this run does
11002                    // not hold, and an agent that cannot be given one is not
11003                    // asked at all: the run stops resumably instead.
11004                    let why = format!("{e:#}");
11005                    state.event(
11006                        "resource",
11007                        format!("{node}: no agent was started - {why}; resume to ask the same agents again"),
11008                    );
11009                    return block_wave(jobs, state, node, attempt, &why);
11010                }
11011            }
11012        } else {
11013            None
11014        }
11015    } else {
11016        None
11017    };
11018    // Every job keeps its whole budget: the wait above was not the agent's.
11019    // Restart the seats' clocks so "started" means "being spawned now".
11020    state.seats_spawning(node, attempt);
11021    if let Err(e) = state.save() {
11022        tracing::warn!("could not persist the start of a wave: {e:#}");
11023    }
11024    // Queueing behind this wave's own seats for a parallelism slot is normal
11025    // (each of them is bounded by its own agent timeout); only a wait beyond
11026    // all of them plus the resource limit means the slots never came back.
11027    let slot_limit = resource_limit
11028        + jobs
11029            .iter()
11030            .map(|j| j.timeout)
11031            .max()
11032            .unwrap_or_default()
11033            .saturating_mul(jobs.len() as u32);
11034    let mut set = tokio::task::JoinSet::new();
11035    // Seats announce themselves here the moment they hold a parallelism
11036    // permit, i.e. just before their CLI is spawned.
11037    let (spawned_tx, mut spawned_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
11038    let overlay = prompts.overlay(node);
11039    let repository_wait = repository_wait(state, pauses);
11040    for (i, mut job) in jobs.into_iter().enumerate() {
11041        job.prompt = prompt::with_overlay(job.prompt, overlay.clone());
11042        if cache.is_some() {
11043            job.prompt.push('\n');
11044            job.prompt
11045                .push_str(&prompt::build_cache_note(node, job.allow_write));
11046        }
11047        let sem = Arc::clone(&sem);
11048        let run = run.to_owned();
11049        let node = node.to_owned();
11050        // Only implementers were told about the task's attachments, so only
11051        // their seats get the directory widened for reading.
11052        let attachments = if node == "implement" {
11053            state.attachments.clone()
11054        } else {
11055            Vec::new()
11056        };
11057        // A read-only seat is never handed `CARGO_TARGET_DIR` — see
11058        // `prompt::build_cache_note`'s doc for why setting it anyway is
11059        // exactly how a sandboxed reviewer's write refusal got reported as a
11060        // defect in the patch, not a property of its own seat. And a
11061        // write-allowed one is handed it only when the lease above was
11062        // actually acquired: a wave that could not get it (`cache_guard` is
11063        // `None`, see its own comment) must not send seats to build into a
11064        // directory this run does not hold - that is the exact concurrent,
11065        // unmanaged-write race this module exists to prevent, not something
11066        // "proceeding anyway" is allowed to reintroduce.
11067        let cache = cache
11068            .filter(|_| job.allow_write && cache_guard.is_some())
11069            .map(Path::to_path_buf);
11070        let spawned_tx = spawned_tx.clone();
11071        let repository_wait = repository_wait.clone();
11072        let coordination = state.config.coordination.clone();
11073        let fetched_base = state.fetched_base.clone();
11074        set.spawn(async move {
11075            // A wait for a parallelism slot is scheduling, not the agent: it
11076            // is bounded by its own limit and ends as a resource block, never
11077            // as a timeout of the agent that was not started.
11078            let _permit = match tokio::time::timeout(slot_limit, sem.acquire()).await {
11079                Ok(p) => p,
11080                Err(_) => {
11081                    return (
11082                        i,
11083                        job.seat,
11084                        AgentOutcome::ResourceBlocked(format!(
11085                            "no parallel slot became free within {}s",
11086                            slot_limit.as_secs()
11087                        )),
11088                        None,
11089                        false,
11090                    );
11091                }
11092            };
11093            spawned_tx.send(job.seat.key.clone()).ok();
11094            let mut seat = job.seat;
11095            let out = repository_wait
11096                .scope(agent::invoke(
11097                    &job.spec,
11098                    &mut seat,
11099                    &Invocation {
11100                        coordination: coordination.as_ref(),
11101                        fetched_base: fetched_base.as_ref(),
11102                        cwd: &job.cwd,
11103                        prompt: &job.prompt,
11104                        timeout: job.timeout,
11105                        allow_write: job.allow_write,
11106                        sessions: job.sessions,
11107                        artifacts: &job.artifacts,
11108                        stem: &job.stem,
11109                        run: &run,
11110                        node: &node,
11111                        cache_dir: cache.as_deref(),
11112                        attachments: &attachments,
11113                        writable: &[],
11114                    },
11115                ))
11116                .await;
11117            let cache_block = out
11118                .as_ref()
11119                .err()
11120                .and_then(|error| error.downcast_ref::<agent::IsolatedSeatWait>())
11121                .map(|timeout| timeout.0.clone());
11122            let interrupted = out
11123                .as_ref()
11124                .err()
11125                .is_some_and(|error| error.is::<agent::ExecutionInterrupted>());
11126            let out = match out {
11127                Ok(o) if o.quota_exhausted() => AgentOutcome::Quota(o),
11128                Ok(o) if o.usable() => AgentOutcome::Ok(o),
11129                // Billed work the CLI failed to hand over is not an ordinary
11130                // failure, but its text is the CLI's raw error JSON, not an
11131                // answer — `Dropped` keeps it out of `Ok` so a caller cannot
11132                // read it as one by forgetting to check. `usable()` is always
11133                // false here (dropped implies an empty response), so this has
11134                // to be checked before the catch-all `Failed` below or the
11135                // one shape this exists for is lost with the rest.
11136                Ok(o) if o.work_undelivered() => AgentOutcome::Dropped(o),
11137                Ok(o) if o.timed_out => AgentOutcome::Failed(TIMED_OUT.to_owned()),
11138                Ok(o) => AgentOutcome::Failed(format!(
11139                    "process exited with no usable output ({})",
11140                    crate::notices::exit_status(o.exit_code)
11141                )),
11142                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
11143                    AgentOutcome::ResourceBlocked(e.to_string())
11144                }
11145                Err(e) => AgentOutcome::Failed(e.to_string()),
11146            };
11147            (i, seat, out, cache_block, interrupted)
11148        });
11149    }
11150    drop(spawned_tx);
11151    let mut collected: Vec<Option<(usize, SeatState, AgentOutcome)>> = Vec::new();
11152    loop {
11153        let joined = tokio::select! {
11154            Some(key) = spawned_rx.recv() => {
11155                // The clock of this seat starts now, not when it queued.
11156                state.seat_spawned(&key);
11157                if let Err(e) = state.save() {
11158                    tracing::warn!("could not persist a seat's start: {e:#}");
11159                }
11160                continue;
11161            }
11162            joined = set.join_next() => joined,
11163        };
11164        let Some(joined) = joined else {
11165            break;
11166        };
11167        let (i, seat, out, cache_block, interrupted) = match joined {
11168            Ok(v) => v,
11169            // No seat to clear: a panicked task never reported which one it
11170            // was. The defensive sweep below this loop is what stops that
11171            // seat's `active` entry from surviving forever.
11172            Err(e) => {
11173                tracing::error!("agent task panicked: {e}");
11174                continue;
11175            }
11176        };
11177        state.seat_finished(&seat.key);
11178        if interrupted
11179            && node == "implement"
11180            && let Some(label) = state
11181                .candidates
11182                .iter()
11183                .find(|candidate| seat.key == format!("impl-{}", candidate.label))
11184                .map(|candidate| candidate.label)
11185        {
11186            state.candidate_preservation.insert(
11187                label,
11188                "interrupted implementation awaiting persistence".into(),
11189            );
11190            state.interrupted_implementations.insert(label);
11191        }
11192        if let Some(block) = cache_block
11193            && state.resource_block.is_none()
11194        {
11195            state.event("resource", block.description());
11196            state.resource_block = Some(block);
11197        }
11198        if let AgentOutcome::ResourceBlocked(why) = &out
11199            && state.resource_block.is_none()
11200        {
11201            state.resource_block = Some(crate::run::ResourceBlock {
11202                cause: crate::run::ResourceBlockCause::Other,
11203                node: node.to_owned(),
11204                kind: if why.contains("disk pressure") {
11205                    "disk pressure"
11206                } else if why.contains("disk admission") {
11207                    "disk admission"
11208                } else if why.contains(crate::incremental::BLOCKED) {
11209                    "incremental cache admission"
11210                } else if why.contains(crate::build_target::KIND) {
11211                    crate::build_target::KIND
11212                } else if why.contains("repository coordination") {
11213                    "repository coordination"
11214                } else {
11215                    "parallel slot"
11216                }
11217                .to_owned(),
11218                detail: why.clone(),
11219                at: Timestamp::now(),
11220            });
11221            let activity = if interrupted {
11222                "agent execution interrupted"
11223            } else {
11224                "no agent was started"
11225            };
11226            state.event("resource", format!("{node}: {activity} - {why}"));
11227        }
11228        record_jobs(state, node, round, &seat.key, &out);
11229        if let Err(e) = state.save() {
11230            tracing::warn!("could not persist a seat's completion: {e:#}");
11231        }
11232        if collected.len() <= i {
11233            collected.resize_with(i + 1, || None);
11234        }
11235        collected[i] = Some((i, seat, out));
11236    }
11237    // Belt-and-braces for the panic branch above: every seat this exact batch
11238    // started shares this `(node, attempt)` pair, and every seat that finished
11239    // normally already cleared itself, so anything left tagged with it here
11240    // can only be a panicked task's leftover. Cleared unconditionally rather
11241    // than left to read as still answering forever.
11242    if state
11243        .active
11244        .values()
11245        .any(|a| a.node == node && a.attempt == attempt)
11246    {
11247        state
11248            .active
11249            .retain(|_, a| !(a.node == node && a.attempt == attempt));
11250        if let Err(e) = state.save() {
11251            tracing::warn!("could not persist the end of a wave: {e:#}");
11252        }
11253    }
11254    // Whether or not the lease above was actually held, several worktrees
11255    // may just have built into the cache with nothing here able to name one
11256    // coherent (worktree, head) for it - see `cache::invalidate_identity`'s
11257    // own doc. Forgetting the old record costs the next `e2e`/`gate` one
11258    // clean it might not have strictly needed; trusting a stale match would
11259    // cost it a wrong answer.
11260    if let Some(cache_dir) = cache
11261        && jobs_had_a_writer
11262    {
11263        crate::cache::invalidate_identity(&crate::run::home(), cache_dir);
11264    }
11265    if let Some(guard) = cache_guard {
11266        guard.release();
11267    }
11268    collected.into_iter().flatten().collect()
11269}
11270
11271/// Fold one seat's [`agent::CommandEvidence`] (if its outcome carries any)
11272/// into the run's [`JobRecord`] log — every node, every seat, uniformly:
11273/// this is data collection, not the fix-specific completion contract in
11274/// [`Runner::continue_fix_report`], and applies regardless of which node
11275/// asked.
11276///
11277/// Only `AgentOutcome::Ok`/`Quota`/`Dropped` carry an [`AgentOutput`] to read
11278/// evidence from; `Failed` does not, and correctly contributes nothing — a
11279/// timeout or crash is not itself evidence about a command the seat may have
11280/// started.
11281fn record_jobs(
11282    state: &mut RunState,
11283    node: &str,
11284    round: Option<usize>,
11285    seat: &str,
11286    out: &AgentOutcome,
11287) {
11288    let commands: &[agent::CommandEvidence] = match out {
11289        AgentOutcome::Ok(o) | AgentOutcome::Quota(o) | AgentOutcome::Dropped(o) => &o.commands,
11290        AgentOutcome::Failed(_) | AgentOutcome::ResourceBlocked(_) => &[],
11291    };
11292    let checked_at = Timestamp::now();
11293    for c in commands {
11294        state.jobs.push(JobRecord {
11295            node: node.to_owned(),
11296            round,
11297            seat: seat.to_owned(),
11298            id: c.id.clone(),
11299            description: c.description.clone(),
11300            checked_at,
11301            status: match c.exit_code {
11302                Some(0) => JobStatus::Completed,
11303                Some(_) => JobStatus::Failed,
11304                None => JobStatus::Unknown,
11305            },
11306            exit_code: c.exit_code,
11307            result_summary: c.result_summary.clone(),
11308            source: c.source.clone(),
11309        });
11310    }
11311}
11312
11313/// Is a review round clean, given how many reviewer seats answered against
11314/// how many the round expected?
11315///
11316/// A seat that never answered (timeout, crash, unparsable output) is not a
11317/// seat that read the patch and found nothing — treating it as such is
11318/// exactly the bug this function exists to close. Under the default `block`
11319/// policy a missing seat can never be clean; `warn` still requires the seats
11320/// that *did* answer to have found nothing blocking and verification to be
11321/// green.
11322///
11323/// `quota_missing` narrows that `block` default for exactly one cause of
11324/// absence: a seat lost to its own rate limit this round. Re-reviewing hoping
11325/// a session limit lifts by the very next round buys nothing — the seat is
11326/// asked again with the same quota — so once every missing seat is accounted
11327/// for by a quota loss (and at least one seat *did* answer, so a decision has
11328/// something to rest on) the round is decided on the panel that could answer,
11329/// same as `warn` would. A panel that lost every seat to quota is not
11330/// decided here: `answered == 0` falls through to the existing `block`
11331/// fallback so a fully collapsed panel still waits rather than landing on no
11332/// review at all.
11333fn round_is_clean(
11334    blocking: usize,
11335    e2e_ok: bool,
11336    answered: usize,
11337    expected: usize,
11338    quota_missing: usize,
11339    policy: IncompleteReviewPolicy,
11340) -> bool {
11341    if blocking != 0 || !e2e_ok {
11342        return false;
11343    }
11344    if answered == expected || policy == IncompleteReviewPolicy::Warn {
11345        return true;
11346    }
11347    answered > 0 && expected - answered <= quota_missing
11348}
11349
11350/// The review loop's own conclusion, derived entirely from its persisted
11351/// round records and the round budget that produced them — never from
11352/// `status`, so a reentry (or `gate`/`merge` reading it independently)
11353/// recomputes the identical answer regardless of what an earlier node in the
11354/// same walk, or a previous walk, did to `status`.
11355///
11356/// `None` while more rounds remain to try, including when review never ran
11357/// at all (`review_rounds = 0`, or nothing yet recorded). Once a round has
11358/// gone clean, or the budget is spent, or the tree has stopped moving (see
11359/// [`STAGNANT_LIMIT`]), the answer is one of two things:
11360///
11361/// - An incomplete panel that raised nothing is missing input, not a
11362///   verified tree — never a hand-off candidate, whatever verification said
11363///   (see [`ReviewRound::incomplete`], `IncompleteReviewPolicy`).
11364/// - Otherwise, green e2e on the last round hands off (see
11365///   [`Runner::stop_reviewing`]); red e2e blocks.
11366///
11367/// A last round whose own verification is still `ResourceBlocked` — magi
11368/// itself never got a command to run, not evidence the patch is broken —
11369/// is neither: this returns `None` for it too, the same as "more rounds
11370/// remain", so a reentry retries the check (see `Runner::review_loop`'s own
11371/// handling of that shape) instead of this cheap recomputation guessing a
11372/// verdict a real attempt never produced.
11373pub(crate) fn review_conclusion(reviews: &[ReviewRound], max_rounds: usize) -> Option<RunStatus> {
11374    if max_rounds == 0
11375        || reviews.last().is_some_and(|r| {
11376            r.clean && matches!(r.e2e_status(), E2eStatus::Passed | E2eStatus::NotConfigured)
11377        })
11378    {
11379        return Some(RunStatus::Gating);
11380    }
11381    let last = reviews.last()?;
11382    let stagnant = reviews.iter().rev().take_while(|r| !r.progressed).count() >= STAGNANT_LIMIT;
11383    if reviews.len() < max_rounds && !stagnant {
11384        return None;
11385    }
11386    if last.incomplete() && last.blocking == 0 {
11387        return Some(RunStatus::Blocked);
11388    }
11389    if last.e2e_status() == E2eStatus::ResourceBlocked
11390        || (last.e2e_status() == E2eStatus::Deferred && last.blocking == 0 && last.fix.is_none())
11391    {
11392        return None;
11393    }
11394    Some(if last.e2e.iter().all(CommandOutcome::ok) {
11395        RunStatus::Gating
11396    } else {
11397        RunStatus::Blocked
11398    })
11399}
11400
11401/// How long a re-ask may take, given the budget the first attempt had.
11402///
11403/// A `nudged` retry is a request to restate an answer the seat has already
11404/// worked out: it carries no new work, so it does not deserve the original
11405/// budget. Measured on run 01c2, two judges restated their ranking in 41 and
11406/// 133 seconds while a third sat for over ten minutes on a resumed session
11407/// holding 410 KB of prior output - and because the retry had inherited the
11408/// full 1200s judge timeout, one stuck nudge nearly doubled the wall time of a
11409/// judging round whose other seats were long finished.
11410///
11411/// A quarter of the budget, with a floor so that a deliberately short timeout
11412/// does not collapse to nothing. A retry that re-sends the whole prompt
11413/// (because the seat kept no context) is the original job again, and keeps the
11414/// original budget.
11415pub(crate) fn retry_budget(full: Duration, nudged: bool) -> Duration {
11416    if nudged {
11417        (full / 4).max(Duration::from_secs(120)).min(full)
11418    } else {
11419        full
11420    }
11421}
11422
11423/// Run a wave and parse each reply, re-asking the seats whose reply was
11424/// unusable.
11425///
11426/// The re-ask is a nudge rather than the whole prompt again when the seat still
11427/// holds its conversation, which is the difference between a cheap retry and
11428/// paying for the entire candidate set twice.
11429///
11430/// A seat whose agent *fails* (rate limit, timeout, any other error) and has a
11431/// successor in `roster` is handed to it instead of being re-asked: the
11432/// handover is the retry. A seat with no successor left (a single-agent
11433/// roster, the roster's tail) is nudged as before, up to `retries` times. So
11434/// the asks to one seat in one node number at most
11435/// `roster.len().max(1) * (1 + retries)`; an agent that still has a successor
11436/// is asked once (a dropped stream is nudged first), and only the last agent
11437/// of the chain gets the `retries` same-agent nudges. Each roster agent is
11438/// tried at most once per seat, walking forward from the seat's own position and never wrapping
11439/// ([`next_untried_in_roster`]); a quota or timeout always hands over, any
11440/// other failure stops the chain when the previous agent failed the same way
11441/// ([`should_hand_over`]). The new agent takes a fresh [`SeatState`], so
11442/// [`has_context`] is false and the job's own full prompt and full budget are
11443/// sent. A seat whose chain ends on a quota records one [`QuotaLoss`] (the
11444/// intermediate ones are not losses) and is returned as a failure like any
11445/// other absent seat — the caller decides whether the panel still has a
11446/// quorum. An empty `roster` disables handover: failures are nudged as they
11447/// always were, and a quota is simply lost. A reply that fails to parse or
11448/// validate is the prompt's doing and is only ever nudged, never handed over.
11449///
11450/// The returned [`SeatState`] names the agent that answered (or tried last).
11451#[allow(clippy::too_many_arguments)]
11452async fn ask_json_wave<T>(
11453    jobs: Vec<SeatJob>,
11454    sem: Arc<Semaphore>,
11455    retries: usize,
11456    roster: &[AgentSpec],
11457    ctx: &WaveCtx<'_>,
11458    losses: &mut Vec<QuotaLoss>,
11459    state: &mut RunState,
11460    validate: &(dyn Fn(&T) -> Result<()> + Send + Sync),
11461) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
11462where
11463    T: serde::de::DeserializeOwned + Send + 'static,
11464{
11465    ask_wave_with(
11466        jobs,
11467        sem,
11468        retries,
11469        roster,
11470        ctx,
11471        losses,
11472        state,
11473        &|text: &str| {
11474            let v = verdict::extract_json::<T>(text)?;
11475            validate(&v)?;
11476            Ok(v)
11477        },
11478    )
11479    .await
11480}
11481
11482/// [`ask_json_wave`] with the reading of an answer supplied by the caller, so
11483/// a node whose answer is prose (deliberation) shares the same handover,
11484/// failure classification, quota bookkeeping and bounds instead of a copy.
11485///
11486/// A seat handed to another roster agent is sent the job's `handover` prompt
11487/// (when it has one) rather than `prompt`: the new agent has no session, so a
11488/// resume-style prompt would be incomplete. That holds for the handover ask
11489/// and for every nudge to that agent whose `has_context` is false.
11490#[allow(clippy::too_many_arguments)]
11491async fn ask_wave_with<T>(
11492    jobs: Vec<SeatJob>,
11493    sem: Arc<Semaphore>,
11494    retries: usize,
11495    roster: &[AgentSpec],
11496    ctx: &WaveCtx<'_>,
11497    losses: &mut Vec<QuotaLoss>,
11498    state: &mut RunState,
11499    parse: &(dyn Fn(&str) -> Result<T> + Send + Sync),
11500) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
11501where
11502    T: Send + 'static,
11503{
11504    let n = jobs.len();
11505    let originals: Vec<SeatJob> = jobs;
11506    let mut seats: Vec<SeatState> = originals.iter().map(|j| j.seat.clone()).collect();
11507    let mut done: Vec<Option<Result<(T, AgentOutput)>>> = (0..n).map(|_| None).collect();
11508    // Nudges each seat's *current* agent has taken — 0 for a first-ask
11509    // answer, N once it has gone through N nudges. Read back once this
11510    // returns, so a caller building a history record (`ReviewRecord`) can
11511    // tell "never answered" (`failed: Some(_)`, `attempts == 0`) apart from
11512    // "recovered after a nudge" (`failed: None`, `attempts > 0`) — see that
11513    // field's own doc.
11514    let mut nudges: Vec<usize> = vec![0; n];
11515    // The agent now occupying each seat, the ids it has already been through,
11516    // where in the roster the walk began, the class of the last failure, and
11517    // the stem word of a handover not yet asked (full prompt, full budget).
11518    let mut specs: Vec<AgentSpec> = originals.iter().map(|j| j.spec.clone()).collect();
11519    let mut tried: Vec<BTreeSet<String>> = specs
11520        .iter()
11521        .map(|s| BTreeSet::from([s.id.clone()]))
11522        .collect();
11523    let starts: Vec<usize> = specs
11524        .iter()
11525        .map(|s| roster.iter().position(|r| r.id == s.id).unwrap_or(0))
11526        .collect();
11527    let carry = ctx.carry_seats && !roster.is_empty();
11528    // Carried across rounds: ids that failed the seat earlier, and how the
11529    // last failure went (so a repeat of it is not handed over again).
11530    let carried: Vec<BTreeSet<String>> = originals
11531        .iter()
11532        .map(|j| {
11533            state
11534                .seat_history
11535                .get(&j.seat.key)
11536                .filter(|_| carry)
11537                .map(|h| h.failed.clone())
11538                .unwrap_or_default()
11539        })
11540        .collect();
11541    let mut prev: Vec<Option<FailClass>> = originals
11542        .iter()
11543        .map(|j| {
11544            state
11545                .seat_history
11546                .get(&j.seat.key)
11547                .filter(|_| carry)
11548                .and_then(|h| h.last_fail.clone())
11549        })
11550        .collect();
11551    let next_agent =
11552        |i: usize, tried: &BTreeSet<String>, specs: &[AgentSpec]| -> Option<AgentSpec> {
11553            let others: BTreeSet<String> = specs
11554                .iter()
11555                .enumerate()
11556                .filter(|(j, _)| *j != i)
11557                .map(|(_, s)| s.id.clone())
11558                .collect();
11559            pick_successor(
11560                roster,
11561                starts[i],
11562                tried,
11563                carry.then(|| &carried[i]),
11564                &others,
11565            )
11566            .cloned()
11567        };
11568    let mut fresh: Vec<Option<String>> = vec![None; n];
11569    let mut last_quota: Vec<Option<agent::Quota>> = vec![None; n];
11570    let mut pending: Vec<usize> = (0..n).collect();
11571
11572    // Per seat the work is bounded by `roster.len().max(1) * (1 + retries)`
11573    // asks: an agent with a successor is asked once and handed over, and only
11574    // a seat with no successor spends `retries` nudges on the same agent. This
11575    // only guarantees the loop's own termination whatever those say.
11576    let max_rounds = (retries + 1) * roster.len().max(1) + 1;
11577    for round in 0..max_rounds {
11578        if pending.is_empty() {
11579            break;
11580        }
11581        let mut batch = Vec::with_capacity(pending.len());
11582        let mut renudged: Vec<&str> = Vec::new();
11583        for &i in &pending {
11584            let src = &originals[i];
11585            // A seat now held by another agent than the job named has no
11586            // session of its own: it gets the full-context prompt whenever
11587            // it is asked in full (the handover ask, a nudge it cannot
11588            // resume).
11589            let full: &str = match &src.handover {
11590                Some(h) if specs[i].id != src.spec.id => h,
11591                _ => &src.prompt,
11592            };
11593            // The prompt and the budget are one decision: a nudge restates
11594            // finished work, a re-sent prompt redoes it.
11595            let (prompt, timeout, stem) = if let Some(word) = fresh[i].take() {
11596                (
11597                    full.to_owned(),
11598                    src.timeout,
11599                    format!("{}-{word}-{}", src.stem, specs[i].id),
11600                )
11601            } else if nudges[i] == 0 {
11602                (full.to_owned(), src.timeout, src.stem.clone())
11603            } else {
11604                renudged.push(src.seat.key.as_str());
11605                let why = done[i]
11606                    .as_ref()
11607                    .and_then(|r| r.as_ref().err().map(ToString::to_string))
11608                    .unwrap_or_else(|| "no parsable answer".to_owned());
11609                let nudge = prompt::nudge(&why);
11610                let nudged = has_context(&specs[i], &seats[i], src.sessions);
11611                let prompt = if nudged {
11612                    nudge
11613                } else {
11614                    format!("{full}\n\n---\n\n{nudge}")
11615                };
11616                (
11617                    prompt,
11618                    retry_budget(src.timeout, nudged),
11619                    format!("{}-retry{}", src.stem, nudges[i]),
11620                )
11621            };
11622            batch.push(SeatJob {
11623                spec: specs[i].clone(),
11624                seat: seats[i].clone(),
11625                cwd: src.cwd.clone(),
11626                prompt,
11627                timeout,
11628                allow_write: src.allow_write,
11629                sessions: src.sessions,
11630                artifacts: src.artifacts.clone(),
11631                stem,
11632                handover: None,
11633            });
11634        }
11635
11636        if !renudged.is_empty() {
11637            state.event(
11638                ctx.node,
11639                format!("retry {round}: re-asking {}", renudged.join(", ")),
11640            );
11641        }
11642        let results = wave(batch, Arc::clone(&sem), ctx, state, round).await;
11643        let mut still = Vec::new();
11644        for (&i, (_wi, seat, out)) in pending.iter().zip(results) {
11645            seats[i] = seat;
11646            // No agent was asked: nothing to hand over, nudge, remember or
11647            // charge. The caller sees `resource_block` and stops the node.
11648            if let AgentOutcome::ResourceBlocked(why) = &out {
11649                done[i] = Some(Err(anyhow::anyhow!("{why}")));
11650                continue;
11651            }
11652            let class = FailClass::of(&out);
11653            // A dropped stream is nudged first (the conversation is still
11654            // there to pick up); only a seat whose nudges are spent hands over.
11655            let nudge_first = matches!(out, AgentOutcome::Dropped(_))
11656                && nudges[i] < retries
11657                && !roster.is_empty();
11658            if let Some(cur) = class.clone().filter(|_| !roster.is_empty() && !nudge_first) {
11659                let next = should_hand_over(prev[i].as_ref(), &cur)
11660                    .then(|| next_agent(i, &tried[i], &specs))
11661                    .flatten();
11662                if carry {
11663                    let h = state
11664                        .seat_history
11665                        .entry(originals[i].seat.key.clone())
11666                        .or_default();
11667                    h.failed.insert(specs[i].id.clone());
11668                    h.last_fail = Some(cur.clone());
11669                    if h.last_ok.as_deref() == Some(specs[i].id.as_str()) {
11670                        h.last_ok = None;
11671                    }
11672                    // Saved before the next agent is asked, so a restart in
11673                    // between does not forget who failed.
11674                    if let Err(e) = state.save() {
11675                        tracing::warn!("could not persist a seat's failure history: {e:#}");
11676                    }
11677                }
11678                if let Some(next) = next {
11679                    record_handover(
11680                        state,
11681                        ctx.node,
11682                        &originals[i].seat.key,
11683                        &specs[i].id,
11684                        &next.id,
11685                        &cur,
11686                        &fail_reason(&out),
11687                    );
11688                    tried[i].insert(next.id.clone());
11689                    prev[i] = Some(cur.clone());
11690                    seats[i] =
11691                        handover_seat(&originals[i].seat.key, &next.id, state.next_seat_seed());
11692                    specs[i] = next;
11693                    fresh[i] = Some(cur.stem_word().to_owned());
11694                    nudges[i] = 0;
11695                    done[i] = Some(Err(anyhow::anyhow!(
11696                        "handed over after: {}",
11697                        fail_reason(&out)
11698                    )));
11699                    still.push(i);
11700                    continue;
11701                }
11702            }
11703            if carry
11704                && !nudge_first
11705                && let Some(cur) = class.clone()
11706            {
11707                // The chain ended here (no successor, or a repeated failure).
11708                let h = state
11709                    .seat_history
11710                    .entry(originals[i].seat.key.clone())
11711                    .or_default();
11712                h.failed.insert(specs[i].id.clone());
11713                h.last_fail = Some(cur);
11714            }
11715            let parsed = match out {
11716                AgentOutcome::Ok(o) => parse(&o.text).map(|v| (v, o)),
11717                AgentOutcome::Quota(o) => {
11718                    last_quota[i] = o.quota.clone();
11719                    Err(anyhow::anyhow!("rate limited (quota); not retrying now"))
11720                }
11721                // Not a parseable answer: the nudge loop re-asks it, which is
11722                // exactly what a dropped stream needs. Just don't hand its raw
11723                // error JSON to `extract_json`.
11724                AgentOutcome::Dropped(o) => {
11725                    let why = o
11726                        .dropped
11727                        .as_ref()
11728                        .map(|d| d.why.as_str())
11729                        .unwrap_or("the CLI ended the stream without delivering its answer");
11730                    Err(anyhow::anyhow!("the CLI dropped the stream ({why})"))
11731                }
11732                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
11733                    Err(anyhow::anyhow!(e))
11734                }
11735            };
11736            let quota = class == Some(FailClass::Quota);
11737            let failed = parsed.is_err();
11738            if !failed && matches!(ctx.node, "judge" | "vote") {
11739                // A validated answer restores this seat's quorum presence,
11740                // including on the normal path after an all-seat block.
11741                state
11742                    .quota
11743                    .retain(|loss| loss.seat != originals[i].seat.key);
11744            }
11745            done[i] = Some(parsed);
11746            if carry && !failed {
11747                let h = state
11748                    .seat_history
11749                    .entry(originals[i].seat.key.clone())
11750                    .or_default();
11751                h.failed.remove(&specs[i].id);
11752                h.last_ok = Some(specs[i].id.clone());
11753                h.last_fail = None;
11754            }
11755            // Do not re-ask a rate-limited seat (quota) — a retry is known to
11756            // fail the same way; and never re-ask a seat that already parsed.
11757            // A failed agent that still has a successor is not re-asked
11758            // either: the handover was its remedy and has just been refused
11759            // (the chain stops on a repeated failure class). A seat with no
11760            // successor left (a single-agent roster, the roster's tail, or an
11761            // empty roster) keeps the same-agent nudge, bounded by `retries`.
11762            let agent_failure = class.is_some()
11763                && !nudge_first
11764                && !roster.is_empty()
11765                && next_agent(i, &tried[i], &specs).is_some();
11766            if failed && !quota && !agent_failure && nudges[i] < retries {
11767                nudges[i] += 1;
11768                still.push(i);
11769            }
11770        }
11771        pending = still;
11772    }
11773
11774    // One loss per seat whose chain ended on a quota: the intermediate ones
11775    // were absorbed by a handover and are not losses.
11776    for (i, q) in last_quota.into_iter().enumerate() {
11777        if let Some(quota) = q {
11778            losses.push(QuotaLoss::from_report(
11779                originals[i].seat.key.clone(),
11780                ctx.node,
11781                Some(&quota),
11782            ));
11783        }
11784    }
11785
11786    // A stalled quorum already has its own recovery checkpoint. Refresh
11787    // its missing seats before deciding whether it can resume.
11788    if state.status != RunStatus::Stalled
11789        && ctx.node != "deliberate"
11790        && n > 0
11791        && losses.len() == n
11792        && done.iter().all(|r| r.as_ref().is_some_and(Result::is_err))
11793    {
11794        block_machine_outage(state, ctx.node, losses);
11795        state.quota.append(losses);
11796    }
11797
11798    seats
11799        .into_iter()
11800        .zip(done)
11801        .zip(nudges)
11802        .map(|((seat, res), attempts)| {
11803            (
11804                seat,
11805                res.unwrap_or_else(|| Err(anyhow::anyhow!("no attempt was made"))),
11806                attempts,
11807            )
11808        })
11809        .collect()
11810}
11811
11812/// A node with no available agent has no task verdict. Preserve the node
11813/// checkpoint and record why a subsequent explicit resume is needed.
11814pub(crate) fn block_machine_outage(state: &mut RunState, node: &str, losses: &[QuotaLoss]) {
11815    let mut auth: Vec<_> = losses
11816        .iter()
11817        .filter(|loss| loss.cause == agent::QuotaCause::Authentication)
11818        .map(|loss| loss.agent.clone())
11819        .collect();
11820    auth.sort();
11821    auth.dedup();
11822    let (kind, detail) = if auth.is_empty() {
11823        (
11824            "agent usage limit",
11825            "All seats reached their agent usage limits; resume after usage is available"
11826                .to_owned(),
11827        )
11828    } else {
11829        (
11830            "agent authentication",
11831            format!(
11832                "Agents {} cannot authenticate; re-authenticate these agents, then resume the held task",
11833                auth.join(", ")
11834            ),
11835        )
11836    };
11837    state.resource_block = Some(crate::run::ResourceBlock {
11838        node: node.to_owned(),
11839        kind: kind.to_owned(),
11840        cause: crate::run::ResourceBlockCause::Other,
11841        detail: detail.clone(),
11842        at: Timestamp::now(),
11843    });
11844    state.event(node, detail);
11845}
11846
11847/// Did the wave end without asking any agent (see [`block_wave`])?
11848fn wave_blocked(results: &[(usize, SeatState, AgentOutcome)]) -> bool {
11849    results
11850        .iter()
11851        .any(|(_, _, o)| matches!(o, AgentOutcome::ResourceBlocked(_)))
11852}
11853
11854/// Settle a wave that never spawned anything: every job answers
11855/// [`AgentOutcome::ResourceBlocked`], its seat leaves `active`, and nothing
11856/// else about the seat (session, history, quota) is touched.
11857fn block_wave(
11858    jobs: Vec<SeatJob>,
11859    state: &mut RunState,
11860    node: &str,
11861    attempt: usize,
11862    why: &str,
11863) -> Vec<(usize, SeatState, AgentOutcome)> {
11864    state.resource_wait = None;
11865    state
11866        .active
11867        .retain(|_, a| !(a.node == node && a.attempt == attempt));
11868    if let Err(e) = state.save() {
11869        tracing::warn!("could not persist a resource-blocked wave: {e:#}");
11870    }
11871    jobs.into_iter()
11872        .enumerate()
11873        .map(|(i, j)| (i, j.seat, AgentOutcome::ResourceBlocked(why.to_owned())))
11874        .collect()
11875}
11876
11877/// Acquire the shared build cache's lease, waiting out contention within
11878/// `budget` (never past it — see AGENTS.md's build-cache section on why an
11879/// unbounded wait is never acceptable).
11880///
11881/// A first, non-blocking check happens before ever waiting; if it finds the
11882/// lease busy, that fact is logged as a `verify` event *and* flushed with
11883/// [`RunState::save`] immediately — not only once the wait finally succeeds
11884/// or gives up — so a `magi show` run by a different process while this one
11885/// is still waiting reads a `run.json` that says so, rather than whatever it
11886/// looked like before the wait started. The same applies to the terminal
11887/// failure: logged and saved before this returns `Err`, so a caller that
11888/// could not get the lease at all still leaves a legible record of why.
11889async fn acquire_cache_lease(
11890    state: &mut RunState,
11891    cache_dir: &Path,
11892    owner: &crate::cache::Owner,
11893    budget: Duration,
11894    node: &str,
11895    context: &str,
11896    cancel: &(dyn Fn() -> bool + Sync),
11897) -> Result<Option<crate::cache::Guard>> {
11898    let home = crate::run::home();
11899    let kind = if crate::build_target::isolated(&state.config) {
11900        crate::build_target::KIND
11901    } else {
11902        "shared build cache"
11903    };
11904    let started = Instant::now();
11905    let busy = match crate::cache::try_acquire(&home, cache_dir, owner) {
11906        Ok(crate::cache::AcquireOutcome::Acquired(g)) => return Ok(Some(g)),
11907        Ok(crate::cache::AcquireOutcome::Busy(busy)) => busy,
11908        Err(e) => {
11909            state.event(
11910                "verify",
11911                format!(
11912                    "{context}: could not check the {kind} at {}: {e:#}",
11913                    cache_dir.display()
11914                ),
11915            );
11916            if let Err(e2) = state.save() {
11917                tracing::warn!("could not persist a cache-check failure: {e2:#}");
11918            }
11919            return Err(anyhow::Error::new(CacheCheckError(format!("{e:#}"))));
11920        }
11921    };
11922    state.event(
11923        "verify",
11924        format!(
11925            "{context}: waiting for the {kind} at {} ({})",
11926            cache_dir.display(),
11927            busy.describe()
11928        ),
11929    );
11930    // Seats of this node are waiting, not running: say so, so the countdown a
11931    // reader sees only ever measures an agent that has been spawned.
11932    state.resource_wait = Some(crate::run::ResourceWait {
11933        node: context.to_owned(),
11934        kind: kind.to_owned(),
11935        holder: format!("{}: {}", cache_dir.display(), busy.describe()),
11936        since: Timestamp::now(),
11937        limit_secs: budget.as_secs(),
11938    });
11939    if let Err(e) = state.save() {
11940        tracing::warn!("could not persist a cache wait: {e:#}");
11941    }
11942    let remaining = budget.saturating_sub(started.elapsed());
11943    let waited = crate::cache::wait_for_unless(
11944        &home,
11945        cache_dir,
11946        owner,
11947        remaining,
11948        Duration::from_secs(5),
11949        cancel,
11950    )
11951    .await;
11952    state.resource_wait = None;
11953    let cause = match &waited {
11954        Ok(Some(_)) => None,
11955        Ok(None) => Some(crate::run::ResourceBlockCause::Cancelled { park: None }),
11956        Err(error)
11957            if error.is::<crate::cache::WaitTimeout>() && kind == crate::build_target::KIND =>
11958        {
11959            Some(crate::run::ResourceBlockCause::IsolatedCacheTimeout {
11960                target: cache_dir.to_owned(),
11961                waited_secs: started.elapsed().as_secs(),
11962                limit_secs: budget.as_secs(),
11963            })
11964        }
11965        Err(error) if error.is::<crate::cache::WaitTimeout>() => {
11966            Some(crate::run::ResourceBlockCause::Timeout {
11967                waited_secs: started.elapsed().as_secs(),
11968                limit_secs: budget.as_secs(),
11969            })
11970        }
11971        Err(_) => Some(crate::run::ResourceBlockCause::Other),
11972    };
11973    if let Some(cause) = cause {
11974        let detail = match &waited {
11975            Ok(_) => "the wait for the build cache was cancelled".to_owned(),
11976            Err(error) => format!("{error:#}"),
11977        };
11978        state.resource_block = Some(crate::run::ResourceBlock {
11979            cause,
11980            node: node.to_owned(),
11981            kind: kind.into(),
11982            detail: format!("{}: {detail}", cache_dir.display()),
11983            at: Timestamp::now(),
11984        });
11985        state.event(
11986            "resource",
11987            state.resource_block.as_ref().unwrap().description(),
11988        );
11989    }
11990    if let Err(error) = state.save() {
11991        tracing::warn!("could not persist cache acquisition outcome: {error:#}");
11992    }
11993    waited
11994}
11995
11996/// The lease state could not be read at all (unreadable lease file, a
11997/// permission problem). Unlike a busy lease that outlasts its bound, nothing is
11998/// known to be contended, so a wave degrades to running without a shared cache
11999/// instead of stopping on a hold that [`crate::triage`] could never release.
12000#[derive(Debug)]
12001struct CacheCheckError(String);
12002
12003impl std::fmt::Display for CacheCheckError {
12004    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12005        f.write_str(&self.0)
12006    }
12007}
12008
12009impl std::error::Error for CacheCheckError {}
12010
12011/// Keep a specific acquisition outcome when the caller adds command evidence.
12012fn record_cache_error(state: &mut RunState, node: &str, error: &anyhow::Error) {
12013    let kind = if crate::build_target::isolated(&state.config) {
12014        crate::build_target::KIND
12015    } else {
12016        "shared build cache"
12017    };
12018    state
12019        .resource_block
12020        .get_or_insert_with(|| crate::run::ResourceBlock {
12021            cause: crate::run::ResourceBlockCause::Other,
12022            node: node.to_owned(),
12023            kind: kind.into(),
12024            detail: format!("{error:#}"),
12025            at: Timestamp::now(),
12026        });
12027    if let Err(error) = state.save() {
12028        tracing::warn!("could not persist cache resource block: {error:#}");
12029    }
12030}
12031
12032tokio::task_local! {
12033    static VERIFY_TARGET: PathBuf;
12034}
12035
12036/// Run `body` — a verify command batch — while holding the shared build
12037/// cache's lease, so this run's own full verification (`e2e`, `gate`) can
12038/// never interleave with another borrower's build against the same
12039/// `CARGO_TARGET_DIR`: a different run, a lingering reviewer past its
12040/// timeout, or a human's own `magi review`. See the `cache` module doc for
12041/// why this matters more than Cargo's own per-target locking covers — two
12042/// *different* worktrees building the same package name/version into one
12043/// cache directory is a staleness bug, not a lock contention one.
12044///
12045/// Cache acquisition has its own bound, `timeout_resource_wait`, just as
12046/// agent waves do. Repository scheduling also has its own bounded,
12047/// cancellable resource-wait policy. Contention must not consume the
12048/// verification budget: `body` receives the full `budget` after both leases
12049/// are acquired and the cache is fresh. Without a shared cache, only
12050/// repository coordination is acquired before handing over the full budget.
12051///
12052/// A lease that cannot be acquired within the resource wait is reported as a single
12053/// synthetic [`CommandOutcome`] (`code: None`) rather than silently skipping
12054/// verification — the same shape a spawn failure already takes in
12055/// [`run_commands`], so a caller need not special-case it.
12056#[allow(clippy::too_many_arguments)]
12057async fn with_cache_lease<'s, F, Fut>(
12058    state: &'s mut RunState,
12059    cache_dir: Option<&Path>,
12060    node: &str,
12061    seat: &str,
12062    worktree: &Path,
12063    head: &str,
12064    budget: Duration,
12065    context: &str,
12066    wait: &crate::repo_lock::WaitPolicy,
12067    body: F,
12068) -> Result<(Vec<CommandOutcome>, bool)>
12069where
12070    F: FnOnce(&'s mut RunState, Duration) -> Fut,
12071    Fut: std::future::Future<Output = (Vec<CommandOutcome>, bool, Vec<u32>)>,
12072{
12073    // Match editing waves: cache first, repository second. In particular,
12074    // pre_gate must never hold the repository while waiting for a wave's cache.
12075    let started = Instant::now();
12076    let home = crate::run::home();
12077    let isolated = crate::build_target::isolated(&state.config);
12078    let planned_target = if isolated {
12079        let plan = (|| -> Result<PathBuf> {
12080            crate::build_target::supports(&state.config)?;
12081            crate::build_target::resolve(&home, worktree)
12082        })();
12083        match plan {
12084            Ok(path) => Some(path),
12085            Err(error) => {
12086                record_cache_error(state, node, &error);
12087                return Ok((
12088                    vec![CommandOutcome {
12089                        command: "(planning isolated build cache)".into(),
12090                        code: None,
12091                        output_tail: format!("{error:#}"),
12092                        duration_ms: 0,
12093                        resource_blocked: true,
12094                    }],
12095                    false,
12096                ));
12097            }
12098        }
12099    } else {
12100        None
12101    };
12102    let cache_dir = planned_target.as_deref().or(cache_dir);
12103    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
12104    let guard = if let Some(cache_dir) = cache_dir {
12105        let owner = crate::cache::Owner::here(&state.id, node, seat, worktree, head);
12106        match acquire_cache_lease(
12107            state,
12108            cache_dir,
12109            &owner,
12110            resource_limit,
12111            node,
12112            context,
12113            &|| wait.cancelled(),
12114        )
12115        .await
12116        .and_then(|g| {
12117            g.ok_or_else(|| anyhow::anyhow!("the wait for the build cache was cancelled"))
12118        }) {
12119            Ok(g) => Some(g),
12120            Err(e) => {
12121                record_cache_error(state, node, &e);
12122                return Ok((
12123                    vec![CommandOutcome {
12124                        command: if isolated {
12125                            "(waiting for the isolated build cache)"
12126                        } else {
12127                            "(waiting for the shared build cache)"
12128                        }
12129                        .into(),
12130                        code: None,
12131                        output_tail: e.to_string(),
12132                        duration_ms: started.elapsed().as_millis() as u64,
12133                        resource_blocked: true,
12134                    }],
12135                    false,
12136                ));
12137            }
12138        }
12139    } else {
12140        None
12141    };
12142    let _coordination = coordinate_operation(state, worktree, wait).await?;
12143    if let Some(path) = &planned_target {
12144        state.event(node, format!("isolated build target: {}", path.display()));
12145    }
12146    if let Some(cache_dir) = cache_dir.filter(|_| !isolated) {
12147        let identity = crate::cache::Identity::new(worktree, head);
12148        let fresh = crate::cache::ensure_fresh(
12149            &home,
12150            cache_dir,
12151            &identity,
12152            &state.config.verify.cargo_manifests(),
12153        );
12154        if let Err(e) = fresh {
12155            record_cache_error(state, node, &e);
12156            state.event(
12157                "verify",
12158                format!(
12159                    "{context}: could not confirm the build cache matches {} at {}: {e:#}",
12160                    worktree.display(),
12161                    short(head)
12162                ),
12163            );
12164            if let Some(guard) = guard {
12165                guard.release();
12166            }
12167            return Ok((
12168                vec![CommandOutcome {
12169                    command: "(confirming the build cache is fresh)".into(),
12170                    code: None,
12171                    output_tail: e.to_string(),
12172                    duration_ms: started.elapsed().as_millis() as u64,
12173                    resource_blocked: true,
12174                }],
12175                false,
12176            ));
12177        }
12178    }
12179    let future = body(state, budget);
12180    let (outcomes, retried, timed_out_pids) = if let Some(target) = planned_target {
12181        VERIFY_TARGET.scope(target, future).await
12182    } else {
12183        future.await
12184    };
12185    if !timed_out_pids.is_empty() {
12186        wait_for_timed_out_children_to_die(&timed_out_pids).await;
12187    }
12188    // Drop repository coordination before releasing the cache, reversing the
12189    // acquisition order. A cancelled/error future also drops both guards.
12190    drop(_coordination);
12191    if let Some(guard) = guard {
12192        guard.release();
12193    }
12194    Ok((outcomes, retried))
12195}
12196
12197/// Poll `pids` — commands [`run_commands`] reports as still running when its
12198/// own timeout elapsed — until every one is confirmed gone, or
12199/// [`LEASE_RELEASE_MAX_WAIT`] passes, whichever comes first.
12200///
12201/// Real confirmation where confirmation is possible, not a substitute for
12202/// full process-tree observation: a grandchild the timed-out process spawned
12203/// and that survives independently of it is invisible to a pid check the
12204/// same way it always was, and continuing to observe and collect *that*
12205/// stays a different piece of work with its own owner. This only narrows a
12206/// fixed blind wait into an actual check of the pids this process does know
12207/// about.
12208async fn wait_for_timed_out_children_to_die(pids: &[u32]) {
12209    wait_for_pids_with(
12210        pids,
12211        crate::proc::pid_alive,
12212        LEASE_RELEASE_POLL,
12213        LEASE_RELEASE_MAX_WAIT,
12214    )
12215    .await;
12216}
12217
12218/// [`wait_for_timed_out_children_to_die`] with its liveness query, poll
12219/// interval and ceiling supplied by the caller, so the polling *logic* -
12220/// returns as soon as every pid reports dead, gives up at the ceiling
12221/// otherwise - is testable on millisecond durations without asking the real
12222/// OS about a pid at all.
12223async fn wait_for_pids_with<F: Fn(u32) -> bool>(
12224    pids: &[u32],
12225    alive: F,
12226    poll: Duration,
12227    max_wait: Duration,
12228) {
12229    let deadline = Instant::now() + max_wait;
12230    loop {
12231        if pids.iter().all(|&pid| !alive(pid)) {
12232            return;
12233        }
12234        if Instant::now() >= deadline {
12235            return;
12236        }
12237        tokio::time::sleep(poll).await;
12238    }
12239}
12240
12241/// Are any of `outcomes` [`CommandOutcome::resource_blocked`] - magi's own
12242/// admission that it could not even get a verify command to run, as opposed
12243/// to evidence the command actually produced? A caller that would otherwise
12244/// read a resource-blocked outcome as a red command must check this first:
12245/// see [`Runner::gate`], which retries rather than records `Blocked` when
12246/// this is true.
12247fn verify_inconclusive(outcomes: &[CommandOutcome]) -> bool {
12248    outcomes.iter().any(|o| o.resource_blocked)
12249}
12250
12251/// What [`Runner::gate_fix_round`] decided.
12252pub(crate) enum GateFix {
12253    /// The tree changed and `verify.e2e` is still green: run the gate again.
12254    Retry,
12255    /// No more rounds, nothing to fix, or the fix did not hold: the gate's
12256    /// last failure stands and the run ends blocked.
12257    Stop,
12258    /// `verify.e2e` could not run after the fix (magi's own contention):
12259    /// decide nothing now, a later reentry retries.
12260    Defer,
12261}
12262
12263/// Is every red command in `outcomes` an ordinary failure the code could
12264/// explain: it ran, exited non-zero, and said something?
12265///
12266/// A timeout, a spawn failure and a killed process all leave `code` `None`;
12267/// 126 / 127 are the POSIX shell's "cannot execute" / "not found". Output-free
12268/// exits carry nothing for a fixer to act on. Language-agnostic on purpose:
12269/// what the command is stays the gate's business.
12270pub(crate) fn gate_fixable(outcomes: &[CommandOutcome]) -> bool {
12271    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
12272    red.peek().is_some()
12273        && red.all(|o| {
12274            !o.resource_blocked
12275                && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
12276                && !o.output_tail.trim().is_empty()
12277        })
12278}
12279
12280/// Describe one verify command's outcome for the event log, distinguishing a
12281/// build/link failure — the toolchain never produced a binary to run — from
12282/// an actual test failure, since only the latter is a verdict on the patch.
12283fn e2e_outcome_label(o: &CommandOutcome) -> String {
12284    if o.ok() {
12285        return "pass".to_owned();
12286    }
12287    let reason = if o.build_failed() {
12288        format!("COULD NOT RUN ({:?}, build/link failure)", o.code)
12289    } else {
12290        format!("FAIL ({:?})", o.code)
12291    };
12292    format!(
12293        "{reason}\n{}",
12294        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
12295    )
12296}
12297
12298/// Does `outcomes` hold a failure worth one more run on the same commit?
12299///
12300/// Only an ordinary test result qualifies: every red command ran, exited
12301/// non-zero and said which way (not a build/link failure, a timeout or kill,
12302/// a spawn failure, the shell's own 126 / 127, or a resource block). Those are
12303/// evidence about the machine or the toolchain, never about a flaky test.
12304fn rerunnable_failure(outcomes: &[CommandOutcome]) -> bool {
12305    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
12306    red.peek().is_some()
12307        && !verify_inconclusive(outcomes)
12308        && red.all(|o| {
12309            !o.build_failed() && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
12310        })
12311}
12312
12313/// Said at the top of the output a fixer gets when the same command failed on
12314/// both attempts, so it reads as a reproduced failure and not a one-off.
12315const FAILED_TWICE: &str = "[this command failed twice on the same commit; the output below is \
12316                            the second attempt's]";
12317
12318/// Run `verify.e2e`, retrying once if the first attempt could not build or
12319/// link — a build/link failure is frequently a race against a shared
12320/// `CARGO_TARGET_DIR` (see AGENTS.md), not a verdict on the patch. Emits one
12321/// `verify` event per command, tagged with `context` (normally `"round N"`)
12322/// so the call sites that need this — the ordinary per-round leg in
12323/// `review_loop`, the deferred catch-up run `stop_reviewing` makes before it
12324/// will ever call a round green, `verify_current_head` and the gate-repair
12325/// check — read identically in the event log.
12326///
12327/// A failure that is a test result (see [`rerunnable_failure`]) is believed
12328/// only after the failed commands have run once more on the same commit, in
12329/// the same worktree and — because the caller holds it around this whole
12330/// function — under the same cache lease, with a full `timeout` of their own
12331/// (`[graph] rerun_failed_e2e`). A command that passes the second time is a
12332/// flake: the head is verified, the first failure is recorded and filed
12333/// (`crate::flake`, `RunState::verify_flakes`). A command that fails again
12334/// stands, carrying the second attempt's output. One verification is therefore
12335/// run at most three times: the build/link retry, then this one rerun.
12336/// `round` is the review round the verification belongs to, if any.
12337async fn run_e2e_with_retry(
12338    state: &mut RunState,
12339    shell: &[String],
12340    commands: &[String],
12341    worktree: &Path,
12342    timeout: Duration,
12343    context: &str,
12344    round: Option<usize>,
12345) -> (Vec<CommandOutcome>, bool, Vec<u32>) {
12346    let (mut e2e, mut timed_out_pids) = run_commands(
12347        state, "verify", "e2e", 0, shell, commands, worktree, timeout,
12348    )
12349    .await;
12350    for o in &e2e {
12351        state.event(
12352            "verify",
12353            format!("{context}: `{}` -> {}", o.command, e2e_outcome_label(o)),
12354        );
12355    }
12356    // A build/link failure is not a verdict on the patch — it is frequently a
12357    // race against a shared `CARGO_TARGET_DIR` (see AGENTS.md). Give verify
12358    // one retry before letting a red like that decide the round.
12359    let verify_retried = e2e.iter().any(CommandOutcome::build_failed);
12360    if verify_retried {
12361        state.event(
12362            "verify",
12363            format!(
12364                "{context}: verify could not build/link, not a test result — retrying once \
12365                 before concluding"
12366            ),
12367        );
12368        let retried = run_commands(
12369            state, "verify", "e2e", 1, shell, commands, worktree, timeout,
12370        )
12371        .await;
12372        e2e = retried.0;
12373        // Both attempts' timeouts matter, not just the last one: the first
12374        // attempt's descendants may still be alive alongside the retry's.
12375        timed_out_pids.extend(retried.1);
12376        for o in &e2e {
12377            state.event(
12378                "verify",
12379                format!(
12380                    "{context}: retry `{}` -> {}",
12381                    o.command,
12382                    e2e_outcome_label(o)
12383                ),
12384            );
12385        }
12386    }
12387    if state.config.graph.rerun_failed_e2e && rerunnable_failure(&e2e) {
12388        let failed: Vec<usize> = (0..e2e.len()).filter(|&i| !e2e[i].ok()).collect();
12389        let rerun_commands: Vec<String> = failed.iter().map(|&i| e2e[i].command.clone()).collect();
12390        let head = git::rev_parse(worktree, "HEAD").await.unwrap_or_default();
12391        state.event(
12392            "verify",
12393            format!(
12394                "{context}: {} failed with a test result — running it once more on the same \
12395                 commit {} before deciding",
12396                rerun_commands
12397                    .iter()
12398                    .map(|c| format!("`{c}`"))
12399                    .collect::<Vec<_>>()
12400                    .join(", "),
12401                short(&head)
12402            ),
12403        );
12404        let (second, pids) = run_commands(
12405            state,
12406            "verify",
12407            "e2e",
12408            1 + usize::from(verify_retried),
12409            shell,
12410            &rerun_commands,
12411            worktree,
12412            timeout,
12413        )
12414        .await;
12415        timed_out_pids.extend(pids);
12416        for o in &second {
12417            state.event(
12418                "verify",
12419                format!(
12420                    "{context}: rerun `{}` -> {}",
12421                    o.command,
12422                    e2e_outcome_label(o)
12423                ),
12424            );
12425        }
12426        let mut reproduced = false;
12427        for (slot, &i) in failed.iter().enumerate() {
12428            let Some(again) = second.get(slot) else {
12429                break;
12430            };
12431            let first = std::mem::replace(&mut e2e[i], again.clone());
12432            if again.ok() {
12433                let signature = crate::flake::signature(&first.output_tail, first.code);
12434                let flake = crate::run::VerifyFlake {
12435                    round,
12436                    context: context.to_owned(),
12437                    head: head.clone(),
12438                    command: first.command.clone(),
12439                    first_failure: summarize_verify(&first.output_tail, EVENT_OUTPUT_TAIL),
12440                    fingerprint: crate::flake::fingerprint(&state.repo, &signature),
12441                    at: Timestamp::now(),
12442                    task: None,
12443                    filed: false,
12444                    filing_error: None,
12445                };
12446                crate::flake::record(state, flake, &signature.label, &crate::queue::Queue::open());
12447            } else if !again.resource_blocked {
12448                reproduced = true;
12449                e2e[i].output_tail = format!("{FAILED_TWICE}\n{}", again.output_tail);
12450            }
12451        }
12452        if reproduced {
12453            state.event(
12454                "verify",
12455                format!("{context}: the failure reproduced on the second run — it stands"),
12456            );
12457        }
12458    }
12459    (e2e, verify_retried, timed_out_pids)
12460}
12461
12462/// Run configured shell commands in `cwd`, in order. The second element is
12463/// the pid of every command that hit `timeout` and was still running when
12464/// this stopped waiting on it (best-effort: `None` when the platform did not
12465/// hand one back) — see [`with_cache_lease`]'s use of it for why a caller
12466/// that releases a shared resource afterward needs to know.
12467///
12468/// Records `task` into [`RunState::active`] at every command boundary
12469/// (`RunState::task_command`) and clears it once the whole list has run
12470/// (`RunState::task_finished`) — a `verify.e2e` / `verify.gate` list can run
12471/// for minutes with no seat and no output of its own to show for it (see
12472/// `CommandOutcome`'s doc on why an empty `e2e`/`gate` alone cannot be told
12473/// apart from "not yet run" without this), and this is the only place that
12474/// knows which command is running right now and how many are left. Three
12475/// saves per command — start, not per second — matching the same "only at a
12476/// boundary" rule [`wave`] already follows for seats.
12477#[allow(clippy::too_many_arguments)]
12478async fn run_commands(
12479    state: &mut RunState,
12480    node: &str,
12481    task: &str,
12482    attempt: usize,
12483    shell: &[String],
12484    commands: &[String],
12485    cwd: &Path,
12486    timeout: Duration,
12487) -> (Vec<CommandOutcome>, Vec<u32>) {
12488    let isolated = crate::build_target::isolated(&state.config);
12489    if isolated && let Some(block) = &state.resource_block {
12490        return (
12491            vec![CommandOutcome {
12492                command: "(isolated build admission)".into(),
12493                code: None,
12494                output_tail: block.description(),
12495                duration_ms: 0,
12496                resource_blocked: true,
12497            }],
12498            Vec::new(),
12499        );
12500    }
12501    if commands.is_empty() {
12502        // Nothing to mark as running and nothing to clear — an empty list
12503        // means "not configured", and touching `active` (or the disk) over
12504        // that would be a write for every round of a repo with no
12505        // `verify.e2e` / `verify.gate` commands at all.
12506        return (Vec::new(), Vec::new());
12507    }
12508    let mut out = Vec::new();
12509    let mut timed_out_pids = Vec::new();
12510    let total = commands.len();
12511    for (idx, command) in commands.iter().enumerate() {
12512        state.task_command(task, node, attempt, command, idx + 1, total, timeout);
12513        if let Err(e) = state.save() {
12514            tracing::warn!("could not persist an in-progress {task} command: {e:#}");
12515        }
12516        let started = Instant::now();
12517        let mut cmd = tokio::process::Command::new(&shell[0]);
12518        cmd.quiet();
12519        // Verify the checkout as a standalone caller. Worker ownership and
12520        // pinned executable selection belong to this driver, not to tests or
12521        // tools it runs. Preserve home/seat context and Running's containment.
12522        for key in crate::worker::INVOCATION_ENV {
12523            cmd.env_remove(key);
12524        }
12525        cmd.args(&shell[1..])
12526            .current_dir(cwd)
12527            .stdin(std::process::Stdio::null())
12528            .stdout(std::process::Stdio::piped())
12529            .stderr(std::process::Stdio::piped())
12530            .kill_on_drop(true);
12531        let mut outputs = Vec::new();
12532        let mut cache = None;
12533        let home = crate::run::home();
12534        let head = if isolated {
12535            Some(git::rev_parse(cwd, "HEAD").await)
12536        } else {
12537            None
12538        };
12539        let protected = (|| -> Result<()> {
12540            crate::incremental::configure(&mut cmd, cwd)?;
12541            cache = if isolated {
12542                let target = VERIFY_TARGET
12543                    .try_with(Clone::clone)
12544                    .context("isolated verification has no target lease")?;
12545                cmd.arg(crate::build_target::command::normalize(command)?);
12546                crate::build_target::command::configure(&mut cmd, &target)?;
12547                Some(target)
12548            } else {
12549                crate::build_target::command::clear(&mut cmd)?;
12550                cmd.arg(command);
12551                state.config.cache_dir()
12552            };
12553            let mut paths = vec![cwd.to_owned()];
12554            if let Some(cache) = &cache {
12555                paths.push(cache.clone());
12556            }
12557            let admit = if isolated {
12558                crate::retention::OutputLease::admit_isolated
12559            } else {
12560                crate::retention::OutputLease::admit
12561            };
12562            outputs.extend(admit(&home, &paths, state.config.disk.min_free_bytes)?);
12563            if let Some(guard) = crate::retention::OutputLease::borrow(cwd)? {
12564                outputs.push(guard);
12565            }
12566            if let Some(cache) = &cache {
12567                outputs.push(crate::retention::OutputLease::cache(
12568                    &crate::run::home(),
12569                    cache,
12570                    false,
12571                )?);
12572                if let Some(head) = head {
12573                    crate::build_target::ensure_fresh(&home, cache, cwd, &head?, &state.config)?;
12574                    if task == "pre_gate" {
12575                        crate::cache::invalidate_identity(&home, cache);
12576                    }
12577                }
12578            }
12579            Ok(())
12580        })();
12581        if let Err(e) = protected {
12582            let detail = format!("execution admission unavailable: {e:#}");
12583            state.resource_block = Some(crate::run::ResourceBlock {
12584                cause: crate::run::ResourceBlockCause::Other,
12585                node: node.to_owned(),
12586                kind: if detail.contains("disk admission") {
12587                    "disk admission"
12588                } else {
12589                    "output ownership"
12590                }
12591                .to_owned(),
12592                detail: detail.clone(),
12593                at: Timestamp::now(),
12594            });
12595            out.push(CommandOutcome {
12596                command: command.clone(),
12597                code: None,
12598                output_tail: detail,
12599                duration_ms: 0,
12600                resource_blocked: true,
12601            });
12602            break;
12603        }
12604        let spawned = if isolated {
12605            crate::seat_process::Running::spawn_build(cmd, None, outputs)
12606        } else {
12607            crate::seat_process::Running::spawn(cmd, None, outputs)
12608        };
12609        let (code, body) = match spawned {
12610            Ok(mut running) => {
12611                let pid = running.child().id();
12612                let (stdout, out_reader) = agent::drain(running.child().stdout.take());
12613                let (stderr, err_reader) = agent::drain(running.child().stderr.take());
12614                let mut paths = vec![cwd.to_owned()];
12615                if let Some(cache) = cache {
12616                    paths.push(cache);
12617                }
12618                let mut pressure = None;
12619                let status = tokio::select! {
12620                    status = tokio::time::timeout(timeout, running.child().wait()) => Some(status),
12621                    reason = crate::retention::emergency(paths, state.config.disk.min_free_bytes, isolated) => {
12622                        pressure = Some(reason); None
12623                    }
12624                };
12625                let (code, failure) = match status {
12626                    Some(Ok(Ok(status))) => (
12627                        status.code(),
12628                        status
12629                            .code()
12630                            .is_none()
12631                            .then(|| format!("command terminated: {status}")),
12632                    ),
12633                    Some(Ok(Err(error))) => {
12634                        (None, Some(format!("failed waiting for command: {error}")))
12635                    }
12636                    Some(Err(_)) => {
12637                        // Leased cleanup confirms process-tree death itself.
12638                        // Unleased commands still need the caller's PID check
12639                        // after kill-on-drop, before releasing cache ownership.
12640                        if !running.coordinated()
12641                            && let Some(pid) = pid
12642                        {
12643                            timed_out_pids.push(pid);
12644                        }
12645                        (
12646                            None,
12647                            Some(format!("timed out after {}s", timeout.as_secs())),
12648                        )
12649                    }
12650                    None => (None, None),
12651                };
12652                running.finish().await;
12653                if let Some(reason) = pressure {
12654                    state.resource_block = Some(crate::run::ResourceBlock {
12655                        cause: crate::run::ResourceBlockCause::Other,
12656                        node: node.to_owned(),
12657                        kind: "disk pressure".to_owned(),
12658                        detail: reason.clone(),
12659                        at: Timestamp::now(),
12660                    });
12661                    out.push(CommandOutcome {
12662                        command: command.clone(),
12663                        code: None,
12664                        output_tail: reason,
12665                        duration_ms: started.elapsed().as_millis() as u64,
12666                        resource_blocked: true,
12667                    });
12668                    break;
12669                }
12670                let mut body = agent::collect(&stdout, out_reader, Duration::from_secs(2)).await;
12671                body.push_str(&agent::collect(&stderr, err_reader, Duration::from_secs(2)).await);
12672                if let Some(failure) = failure {
12673                    body.push('\n');
12674                    body.push_str(&failure);
12675                }
12676                (code, body)
12677            }
12678            Err(e) if isolated => {
12679                let e = anyhow::Error::new(e)
12680                    .context(format!("could not start managed build `{}`", shell[0]));
12681                record_cache_error(state, node, &e);
12682                out.push(CommandOutcome {
12683                    command: command.clone(),
12684                    code: None,
12685                    output_tail: format!("{e:#}"),
12686                    duration_ms: 0,
12687                    resource_blocked: true,
12688                });
12689                break;
12690            }
12691            Err(e) => (None, format!("failed to spawn `{}`: {e}", shell[0])),
12692        };
12693        let mut summary = summarize_verify(&body, crate::run::VERIFY_SUMMARY);
12694        if !body.is_empty() {
12695            // The full text is kept whatever the summary dropped. A fresh
12696            // name per command so a resume or retry never overwrites an
12697            // earlier run's output. A failed write changes no verdict.
12698            match crate::run::write_verification_artifact(state, task, &body) {
12699                Ok(name) if summary != body => {
12700                    summary = format!("[full output: artifacts/{name}]\n{summary}");
12701                }
12702                Ok(_) => {}
12703                Err(e) => {
12704                    let warning = format!("could not save the full {task} output: {e:#}");
12705                    tracing::warn!("{warning}");
12706                    state.event(node, warning);
12707                    if summary != body {
12708                        summary = format!("[full output could not be saved: {e:#}]\n{summary}");
12709                    }
12710                }
12711            }
12712        }
12713        let resource_blocked = code != Some(0) && body.contains(crate::incremental::BLOCKED);
12714        out.push(CommandOutcome {
12715            command: command.clone(),
12716            code,
12717            output_tail: summary,
12718            duration_ms: started.elapsed().as_millis() as u64,
12719            resource_blocked,
12720        });
12721        if resource_blocked {
12722            state.resource_block = Some(crate::run::ResourceBlock {
12723                cause: crate::run::ResourceBlockCause::Other,
12724                node: node.to_owned(),
12725                kind: "incremental cache admission".into(),
12726                detail: body,
12727                at: Timestamp::now(),
12728            });
12729            break;
12730        }
12731    }
12732    state.task_finished(task);
12733    if let Err(e) = state.save() {
12734        tracing::warn!("could not persist the end of {task}: {e:#}");
12735    }
12736    (out, timed_out_pids)
12737}
12738
12739/// The shell command line `mode = "none"` prints — in `magi show`'s `merge`
12740/// section (`report::run`) and in the `merge` event this node records — for
12741/// the operator to run by hand.
12742///
12743/// Built from [`MergeStyle`] rather than always `git merge --no-ff`: a base
12744/// branch whose ruleset forbids merge commits (GitHub's "must not contain
12745/// merge commits", or "require linear history") rejects the push a `--no-ff`
12746/// merge would produce, which is exactly the guidance this function replaces.
12747/// `message`'s first line becomes the squash commit's subject, matching the
12748/// note `report::run` prints alongside this command — see that function for
12749/// why an explicit subject is not optional there.
12750fn manual_merge_command(style: MergeStyle, repo: &Path, branch: &str, message: &str) -> String {
12751    let repo = repo.display();
12752    match style {
12753        MergeStyle::Merge => format!("git -C {repo} merge --no-ff {branch}"),
12754        MergeStyle::Squash => {
12755            // The subject sits inside double quotes, and a title an agent
12756            // wrote may carry the characters that break out of them.
12757            let subject = message
12758                .lines()
12759                .next()
12760                .unwrap_or(branch)
12761                .replace(['\\', '"', '$', '`'], "");
12762            format!(
12763                "git -C {repo} merge --squash {branch} && git -C {repo} commit -m \"{subject}\""
12764            )
12765        }
12766        MergeStyle::Rebase => format!("git -C {repo} merge --ff-only {branch}"),
12767    }
12768}
12769
12770/// GitHub's `createPullRequest` GraphQL mutation, which `gh pr create` calls
12771/// under the hood, rejects a `title` over 256 characters and the whole
12772/// command fails — no PR at all, for a run whose body was otherwise fine
12773/// (this is what happened to run 2963; see AGENTS.md). 240 leaves room below
12774/// that limit: titles are counted in `chars()` (Unicode scalars), which is not
12775/// always how GitHub counts. [`english_title`] keeps its trailing `...` inside
12776/// this bound. It is a margin, not a guarantee — a title packed
12777/// with multi-unit characters could still in principle land close to the
12778/// edge, but a real task title's occasional emoji or accented letter fits
12779/// comfortably inside it.
12780const PR_TITLE_MAX: usize = 240;
12781
12782/// A pull request title from the opening line of `text`, or `None` when that
12783/// line is not English (GitHub text is) or has no letters.
12784///
12785/// A line within `max` is kept as is. A longer one is cut at the end of its
12786/// first sentence when that falls inside `max`, else at a word boundary with a
12787/// plain `...` (ASCII, unlike the `…` `queue::title_from` appends, which would
12788/// make every merely-truncated title look non-English). The language check
12789/// runs on the kept text before any mark is added, so only what GitHub will
12790/// show is judged: an English opening followed by non-ASCII far past the cut
12791/// still passes.
12792fn english_title(text: &str, max: usize, ascii_only: bool) -> Option<String> {
12793    let line = queue::first_line(text)?;
12794    let chars: Vec<char> = line.chars().collect();
12795    let (kept, mark) = if chars.len() <= max {
12796        (line.to_owned(), "")
12797    } else if let Some(end) = sentence_end(&chars, max) {
12798        (chars[..end].iter().collect::<String>(), "")
12799    } else {
12800        let room = max.saturating_sub(3);
12801        // Cut at the last space inside the room; when the char just past the
12802        // room is a space the room already ends on a word.
12803        let cut = if chars[room].is_whitespace() {
12804            room
12805        } else {
12806            chars[..room]
12807                .iter()
12808                .rposition(|c| c.is_whitespace())
12809                .unwrap_or(room)
12810        };
12811        let head: String = chars[..cut].iter().collect();
12812        let head = head.trim_end_matches(|c: char| c.is_whitespace() || ",;:-".contains(c));
12813        (head.to_owned(), "...")
12814    };
12815    if kept.is_empty() {
12816        return None;
12817    }
12818    if ascii_only && (!kept.is_ascii() || !kept.chars().any(|c| c.is_ascii_alphabetic())) {
12819        return None;
12820    }
12821    if !ascii_only && !kept.chars().any(char::is_alphabetic) {
12822        return None;
12823    }
12824    Some(format!("{kept}{mark}"))
12825}
12826
12827/// The char length of the first sentence of `chars` when it ends within `max`
12828/// (the closing `.`/`!`/`?` dropped), skipping very short stubs and common
12829/// abbreviations so `e.g. foo` does not end a title early.
12830fn sentence_end(chars: &[char], max: usize) -> Option<usize> {
12831    const MIN: usize = 20;
12832    for i in MIN..max.min(chars.len()) {
12833        if !matches!(chars[i], '.' | '!' | '?') {
12834            continue;
12835        }
12836        let Some(&next) = chars.get(i + 1) else {
12837            continue;
12838        };
12839        if !next.is_whitespace() {
12840            continue;
12841        }
12842        let after = chars[i + 1..].iter().find(|c| !c.is_whitespace());
12843        if after.is_some_and(|c| c.is_ascii_lowercase()) {
12844            continue;
12845        }
12846        let word: String = chars[..i]
12847            .iter()
12848            .rev()
12849            .take_while(|c| !c.is_whitespace())
12850            .collect::<Vec<_>>()
12851            .into_iter()
12852            .rev()
12853            .collect();
12854        let word = word.to_ascii_lowercase();
12855        if matches!(word.as_str(), "e.g" | "i.e" | "etc" | "vs" | "cf") {
12856            continue;
12857        }
12858        let end = chars[..i]
12859            .iter()
12860            .rposition(|c| !c.is_whitespace())
12861            .map_or(i, |p| p + 1);
12862        return Some(end);
12863    }
12864    None
12865}
12866
12867/// What `merge = "pr"` (and the merge commit of the other modes) says about a
12868/// change: a title and a body describing what was *implemented*, not the task
12869/// that asked for it. A task reads as a request; a reader of the merged
12870/// history wants the change.
12871struct PrMessage {
12872    title: String,
12873    body: String,
12874}
12875
12876impl PrMessage {
12877    /// Title, blank line, body. The first line is the squash/merge commit
12878    /// subject (`manual_merge_command` takes it via `lines().next()`), so it
12879    /// has to stay one sensible line.
12880    fn commit_message(&self) -> String {
12881        format!("{}\n\n{}", self.title, self.body)
12882    }
12883}
12884
12885/// The text after a leading `TITLE:` (any case) on `line`.
12886fn title_marker(line: &str) -> Option<&str> {
12887    let line = line.trim();
12888    let head = line.get(..6)?;
12889    head.eq_ignore_ascii_case("title:")
12890        .then(|| line[6..].trim())
12891}
12892
12893/// The implementer's own one-line title: the `TITLE:` line the implement
12894/// prompt asks for at the top of its SUMMARY. Candidate commits are all
12895/// `magi: candidate X (uncommitted work)`, so a commit subject is never a
12896/// source, and a title that says as much is refused here too.
12897fn summary_title(summary: &str) -> Option<String> {
12898    let first = summary.lines().find(|l| !l.trim().is_empty())?;
12899    let raw = title_marker(first)?;
12900    if raw.is_empty() {
12901        return None;
12902    }
12903    let title = queue::title_from(raw, PR_TITLE_MAX);
12904    let lower = title.to_ascii_lowercase();
12905    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
12906        return None;
12907    }
12908    Some(title)
12909}
12910
12911/// How `open_review`'s instruction begins; see [`landing_title`].
12912const REVIEW_PROMPT_OPENING: &str = "Review the work already on branch";
12913
12914/// Marker `open_review` gives a candidate that nothing in the roster wrote.
12915pub(crate) const EXISTING_BRANCH: &str = "(existing branch)";
12916
12917/// Does this run review work that already existed, rather than implement a
12918/// task? Runs recorded before `reviewed_commits` existed carry only the
12919/// candidate marker.
12920pub(crate) fn is_review_run(state: &RunState) -> bool {
12921    state.reviewed_commits.is_some() || state.candidates.iter().any(|c| c.agent == EXISTING_BRANCH)
12922}
12923
12924/// The title of a review-only run: the subject of the oldest commit under
12925/// review. Later commits are usually fixups, and `instruction` is the review
12926/// prompt, which says nothing about the change. GitHub text is English, so a
12927/// non-ASCII or blank subject yields `None` and the caller's neutral title.
12928fn review_title(state: &RunState) -> Option<String> {
12929    english_subject(
12930        state.reviewed_commits.as_ref()?.first()?,
12931        state.config.graph.github_english(),
12932    )
12933}
12934
12935/// `raw` as a pull request title, or `None` when it is blank, not English
12936/// (GitHub text is), or one of magi's own candidate commit subjects.
12937fn english_subject(raw: &str, ascii_only: bool) -> Option<String> {
12938    let raw = raw.trim();
12939    if raw.is_empty() {
12940        return None;
12941    }
12942    if ascii_only && (!raw.is_ascii() || !raw.chars().any(|c| c.is_ascii_alphabetic())) {
12943        return None;
12944    }
12945    if !ascii_only && !raw.chars().any(char::is_alphabetic) {
12946        return None;
12947    }
12948    let title = queue::title_from(raw, PR_TITLE_MAX);
12949    let lower = title.to_ascii_lowercase();
12950    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
12951        return None;
12952    }
12953    Some(title)
12954}
12955
12956/// What a review-only run's branch says about itself, read at the moment the
12957/// pull request is opened.
12958#[derive(Debug, Clone, PartialEq, Eq)]
12959struct BranchFacts {
12960    /// `(subject, body)` of each commit, oldest first.
12961    commits: Vec<(String, String)>,
12962    /// Trimmed `git diff --stat`.
12963    stat: String,
12964}
12965
12966/// Longest diff stat shown: this many file lines plus the summary line.
12967const STAT_FILE_LINES: usize = 25;
12968/// Cap on the commit list, well inside GitHub's 65536-character body limit.
12969const COMMITS_MAX_CHARS: usize = 20_000;
12970
12971/// Read the commits and diff stat of `base..branch`. `None` when git cannot
12972/// say or finds nothing, so the caller falls back to what the run recorded.
12973async fn branch_facts(repo: &Path, base: &str, branch: &str) -> Option<BranchFacts> {
12974    let commits = git::commit_log(repo, base, branch).await.ok()?;
12975    if commits.is_empty() {
12976        return None;
12977    }
12978    let stat = git::diff_stat(repo, base, branch).await.unwrap_or_default();
12979    let lines: Vec<&str> = stat.lines().collect();
12980    let stat = if lines.len() > STAT_FILE_LINES + 1 {
12981        let omitted = lines.len() - 1 - STAT_FILE_LINES;
12982        let more = format!(" ... {omitted} more file(s)");
12983        let mut kept: Vec<&str> = lines[..STAT_FILE_LINES].to_vec();
12984        kept.push(&more);
12985        kept.push(lines[lines.len() - 1]);
12986        kept.join("\n")
12987    } else {
12988        lines.join("\n")
12989    };
12990    Some(BranchFacts { commits, stat })
12991}
12992
12993/// Defang what would break the surrounding markdown: a closing `</details>`
12994/// and a code fence.
12995fn markdown_safe(text: &str) -> String {
12996    text.replace("</details>", "&lt;/details&gt;")
12997        .replace("\x60\x60\x60", "~~~")
12998}
12999
13000fn neutral_title(state: &RunState, winner: char) -> String {
13001    format!(
13002        "chore: land candidate {} of run {}",
13003        winner.to_ascii_uppercase(),
13004        state.id
13005    )
13006}
13007
13008/// Reuse the graph's bounded fixer without starting another graph or driver.
13009/// Copy the working state back even on errors so spent rounds remain visible.
13010pub(crate) async fn repair_landing_gate(
13011    state: &mut RunState,
13012    winner: &Candidate,
13013    outcomes: &[CommandOutcome],
13014) -> Result<GateFix> {
13015    if state.gate_fixes.len() >= state.config.graph.gate_fix_rounds || !gate_fixable(outcomes) {
13016        return Ok(GateFix::Stop);
13017    }
13018    let mut runner = Runner {
13019        roles: state.config.resolve_roles()?,
13020        sem: Arc::new(Semaphore::new(state.config.graph.max_parallel.max(1))),
13021        state: state.clone(),
13022        pause: Pause::new(),
13023        interrupt: Pause::new(),
13024    };
13025    let result = runner.gate_fix_round(winner, outcomes).await;
13026    *state = runner.state;
13027    result
13028}
13029
13030/// Review judgment survives a clean rebase; command evidence belongs to a SHA.
13031/// A completed failure is terminal on that SHA. Resource waits remain retryable.
13032pub(crate) async fn verify_current_head(
13033    state: &mut RunState,
13034    winner: &Candidate,
13035    wait: &crate::repo_lock::WaitPolicy,
13036) -> Result<bool> {
13037    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13038    // Preserve the previous record before replacing it, including on crash recovery.
13039    if state.head_e2e.as_ref().is_some_and(|e| e.head != head) {
13040        state
13041            .verification_history
13042            .push(crate::run::VerificationEvidence {
13043                superseded_by: Some(head.clone()),
13044                archived_at: Some(Timestamp::now()),
13045                fixes_spent: Some(state.gate_fixes.len()),
13046                gate_head: None,
13047                gate_ran: false,
13048                gate: Vec::new(),
13049                e2e: state.head_e2e.take(),
13050            });
13051    }
13052    if let Some(e) = &state.head_e2e
13053        && e.head == head
13054    {
13055        if e.passed {
13056            return Ok(true);
13057        }
13058        if !e.outcomes.is_empty() && !verify_inconclusive(&e.outcomes) {
13059            state.status = RunStatus::Blocked;
13060            state.save()?;
13061            return Ok(false);
13062        }
13063    } else if state.reviews.last().is_some_and(|r| {
13064        r.verified_head.as_deref() == Some(head.as_str())
13065            && (r.e2e_status() == E2eStatus::Passed
13066                || (r.e2e_status() == E2eStatus::NotConfigured
13067                    && state.config.verify.e2e.is_empty()))
13068    }) || state
13069        .gate_repair_e2e
13070        .as_ref()
13071        .is_some_and(|e| e.head == head && e.passed)
13072    {
13073        return Ok(true);
13074    }
13075    if let Some(e) = &state.gate_repair_e2e
13076        && e.head == head
13077        && !e.passed
13078        && !e.outcomes.is_empty()
13079        && !verify_inconclusive(&e.outcomes)
13080    {
13081        state.status = RunStatus::Blocked;
13082        state.save()?;
13083        return Ok(false);
13084    }
13085    state.head_e2e = Some(crate::run::GateRepairE2e {
13086        head: head.clone(),
13087        passed: false,
13088        outcomes: Vec::new(),
13089    });
13090    state.save()?;
13091    let commands = state.config.verify.e2e.clone();
13092    let shell = state.config.shell();
13093    let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13094    let cache_dir = state.config.cache_dir();
13095    let outcomes = if commands.is_empty() {
13096        Vec::new()
13097    } else {
13098        let (outcomes, _) = with_cache_lease(
13099            state,
13100            cache_dir.as_deref(),
13101            "e2e",
13102            "e2e",
13103            &winner.worktree,
13104            &head,
13105            timeout,
13106            "current head e2e",
13107            wait,
13108            |state, budget| async move {
13109                run_e2e_with_retry(
13110                    state,
13111                    &shell,
13112                    &commands,
13113                    &winner.worktree,
13114                    budget,
13115                    "current head e2e",
13116                    None,
13117                )
13118                .await
13119            },
13120        )
13121        .await?;
13122        outcomes
13123    };
13124    let unresolved = verify_inconclusive(&outcomes);
13125    let passed = !unresolved
13126        && outcomes.iter().all(CommandOutcome::ok)
13127        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
13128    if !outcomes.is_empty() && !unresolved {
13129        state.record_base_progress(&head);
13130    }
13131    state.head_e2e = Some(crate::run::GateRepairE2e {
13132        head: head.clone(),
13133        passed,
13134        outcomes,
13135    });
13136    if !passed && !unresolved {
13137        state.status = RunStatus::Blocked;
13138        state.event(
13139            "e2e",
13140            format!("verify.e2e failed on head {head}; nothing published"),
13141        );
13142    }
13143    state.save()?;
13144    Ok(passed)
13145}
13146
13147/// Recheck a repair's e2e requirement across failures, resource deferrals and
13148/// process interruptions. A successful result only applies to its exact SHA.
13149pub(crate) async fn check_gate_repair_e2e(
13150    state: &mut RunState,
13151    winner: &Candidate,
13152    wait: &crate::repo_lock::WaitPolicy,
13153) -> Result<GateFix> {
13154    if state.gate_repair_e2e.is_none() && state.gate_fixes.is_empty() {
13155        return Ok(GateFix::Retry);
13156    }
13157    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13158    if state
13159        .gate_repair_e2e
13160        .as_ref()
13161        .is_some_and(|r| r.head == head && r.passed)
13162    {
13163        return Ok(GateFix::Retry);
13164    }
13165    state.gate_repair_e2e = Some(crate::run::GateRepairE2e {
13166        head: head.clone(),
13167        passed: false,
13168        outcomes: Vec::new(),
13169    });
13170    state.save()?;
13171    let commands = state.config.verify.e2e.clone();
13172    let outcomes = if commands.is_empty() {
13173        Vec::new()
13174    } else {
13175        let shell = state.config.shell();
13176        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13177        let cache_dir = state.config.cache_dir();
13178        let (outcomes, _) = with_cache_lease(
13179            state,
13180            cache_dir.as_deref(),
13181            "e2e",
13182            "e2e",
13183            &winner.worktree,
13184            &head,
13185            timeout,
13186            "gate repair e2e",
13187            wait,
13188            |state, budget| async move {
13189                run_e2e_with_retry(
13190                    state,
13191                    &shell,
13192                    &commands,
13193                    &winner.worktree,
13194                    budget,
13195                    "gate repair e2e",
13196                    None,
13197                )
13198                .await
13199            },
13200        )
13201        .await?;
13202        outcomes
13203    };
13204    let deferred = verify_inconclusive(&outcomes);
13205    let passed = outcomes.iter().all(CommandOutcome::ok)
13206        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
13207    state.gate_repair_e2e = Some(crate::run::GateRepairE2e {
13208        head,
13209        passed,
13210        outcomes,
13211    });
13212    state.save()?;
13213    if deferred {
13214        Ok(GateFix::Defer)
13215    } else if !passed {
13216        state.event(
13217            "gate",
13218            "verify.e2e failed after gate repair; nothing published",
13219        );
13220        Ok(GateFix::Stop)
13221    } else {
13222        Ok(GateFix::Retry)
13223    }
13224}
13225
13226/// Run the same configured gate for a landing head and a fresh graph.
13227pub(crate) async fn run_landing_gate(
13228    state: &mut RunState,
13229    winner: &Candidate,
13230    wait: &crate::repo_lock::WaitPolicy,
13231) -> Result<Vec<CommandOutcome>> {
13232    let shell = state.config.shell();
13233    let gate_commands = state.config.verify.gate.clone();
13234    let has_pre_gate = !state.config.verify.pre_gate.is_empty();
13235    let outcomes = if gate_commands.is_empty() && !has_pre_gate {
13236        state.gate_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
13237        Vec::new()
13238    } else {
13239        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13240        let cache_dir = state.config.cache_dir();
13241        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13242        let (outcomes, _) = with_cache_lease(
13243            state,
13244            cache_dir.as_deref(),
13245            "gate",
13246            "gate",
13247            &winner.worktree,
13248            &head,
13249            timeout,
13250            "final gate",
13251            wait,
13252            |state, budget| {
13253                let shell = shell.clone();
13254                let gate_commands = gate_commands.clone();
13255                let winner = winner.clone();
13256                async move {
13257                    Runner::run_pre_gate(state, &winner).await;
13258                    // Bind command evidence after mechanical fixes, before commands start.
13259                    state.gate_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
13260                    let (outcomes, timed_out_pids) = run_commands(
13261                        state,
13262                        "gate",
13263                        "gate",
13264                        0,
13265                        &shell,
13266                        &gate_commands,
13267                        &winner.worktree,
13268                        budget,
13269                    )
13270                    .await;
13271                    (outcomes, false, timed_out_pids)
13272                }
13273            },
13274        )
13275        .await?;
13276        outcomes
13277    };
13278    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
13279    if !verify_inconclusive(&outcomes) && state.gate_head.as_deref() != Some(current.as_str()) {
13280        let mut outcomes = outcomes;
13281        outcomes.push(CommandOutcome {
13282            command: "gate head stability".into(), code: None,
13283            output_tail: "winner changed during gate, or checked head is unknown; fresh verification required".into(),
13284            duration_ms: 0, resource_blocked: false,
13285        });
13286        return Ok(outcomes);
13287    }
13288    if outcomes.is_empty() {
13289        // Nothing configured to check — distinct from every other
13290        // silence in this run's event log, since an empty `gate` alone
13291        // no longer says whether the gate ran at all (see
13292        // `RunState::gate_ran`'s own doc).
13293        state.event("gate", "no gate commands configured; not tested");
13294    }
13295    for o in &outcomes {
13296        state.event(
13297            "gate",
13298            format!(
13299                "`{}` -> {}",
13300                o.command,
13301                if o.ok() {
13302                    "pass".to_owned()
13303                } else {
13304                    format!(
13305                        "FAIL ({:?})\n{}",
13306                        o.code,
13307                        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
13308                    )
13309                }
13310            ),
13311        );
13312    }
13313    Ok(outcomes)
13314}
13315
13316/// The pull request title to hand to `land::merge_subject`. A review-only run
13317/// opened by an earlier build titled its pull request with the review prompt;
13318/// that title is dropped (empty, so the fallback applies) rather than landed.
13319/// Any other title, including an operator's rename, passes through untouched,
13320/// and so does every title of a run that implements a task.
13321pub fn landing_title<'a>(state: &RunState, pr_title: &'a str) -> &'a str {
13322    if is_review_run(state) && pr_title.trim_start().starts_with(REVIEW_PROMPT_OPENING) {
13323        ""
13324    } else {
13325        pr_title
13326    }
13327}
13328
13329/// What the squash subject falls back to when the pull request title is empty
13330/// or candidate-shaped: for a review-only run the derived title, never the
13331/// review prompt held in `instruction`.
13332pub fn landing_subject_source(state: &RunState) -> String {
13333    if is_review_run(state) {
13334        let winner = state.candidates.first().map_or('A', |c| c.label);
13335        return review_title(state).unwrap_or_else(|| neutral_title(state, winner));
13336    }
13337    state.instruction.clone()
13338}
13339
13340/// `summary` without its `TITLE:` line, which the pull request title already
13341/// carries.
13342fn summary_without_title(summary: &str) -> String {
13343    let mut lines = summary.trim().lines().peekable();
13344    if lines.peek().is_some_and(|l| title_marker(l).is_some()) {
13345        lines.next();
13346    }
13347    lines.collect::<Vec<_>>().join("\n").trim().to_owned()
13348}
13349
13350/// The pull request title and body for the winning candidate.
13351///
13352/// Title: the implementer's `TITLE:` line ([`summary_title`]), falling back to
13353/// the task's own opening line via [`queue::title_from`] when there is none.
13354/// `state.instruction` can open with blank lines (`task_text` only rejects a
13355/// body that is blank *entirely*), which `title_from` skips.
13356///
13357/// Publishing uses an independent description generated from the final diff
13358/// and structured evidence. Internal summaries and reports remain local.
13359/// Non-publishing previews may display the original task and candidate summary.
13360/// The footer retains the run and candidate provenance.
13361#[cfg(test)]
13362fn pr_message(state: &RunState, winner: char) -> PrMessage {
13363    pr_message_with(state, winner, None)
13364}
13365
13366/// [`pr_message`] with what the branch of a review-only run says about itself.
13367/// `facts` is ignored for a run that implements a task.
13368#[cfg(test)]
13369fn pr_message_with(state: &RunState, winner: char, facts: Option<&BranchFacts>) -> PrMessage {
13370    let raw = pr_message_raw(
13371        state,
13372        winner,
13373        facts,
13374        crate::pr_outcome::FinalHead::Unreported,
13375        ChangeNote::NotAsked,
13376    );
13377    let id = crate::scrub::Identity::current();
13378    PrMessage {
13379        title: crate::scrub::scrub(&raw.title, &id),
13380        body: crate::scrub::scrub(&raw.body, &id),
13381    }
13382}
13383
13384/// What the public description may say about the change itself.
13385#[derive(Debug, Clone, Copy)]
13386enum ChangeNote<'a> {
13387    /// A local preview or non-publishing merge mode: no public generation needed.
13388    NotAsked,
13389    /// A summary written from the final diff.
13390    Summary(&'a crate::run::ChangeSummary),
13391    /// A summary was asked for and could not be produced; the text says why.
13392    Unavailable(&'a str),
13393}
13394
13395fn pr_message_raw(
13396    state: &RunState,
13397    winner: char,
13398    facts: Option<&BranchFacts>,
13399    head: crate::pr_outcome::FinalHead<'_>,
13400    change: ChangeNote<'_>,
13401) -> PrMessage {
13402    if !matches!(change, ChangeNote::NotAsked) {
13403        let (title, mut body) = match change {
13404            ChangeNote::Summary(c) => (
13405                c.title.clone(),
13406                format!("## Summary\n\n{}\n\n", c.body.trim()),
13407            ),
13408            ChangeNote::Unavailable(why) => (
13409                neutral_title(state, winner),
13410                format!(
13411                    "## 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"
13412                ),
13413            ),
13414            ChangeNote::NotAsked => unreachable!(),
13415        };
13416        body.push_str(&public_pr_evidence(state, head));
13417        body.push_str(&format!(
13418            "\n---\nmagi:run/{} magi:candidate-{}\n",
13419            state.id,
13420            winner.to_ascii_lowercase()
13421        ));
13422        return PrMessage { title, body };
13423    }
13424    pr_preview(state, winner, facts, head)
13425}
13426
13427/// Append public facts from the run records after every prose generation,
13428/// including posting-gate rewrites. The agent cannot drop this provenance.
13429fn public_pr_evidence(state: &RunState, head: crate::pr_outcome::FinalHead<'_>) -> String {
13430    let mut body = crate::pr_outcome::review_rounds(state);
13431    body.push_str(&crate::pr_outcome::final_verification(state, head));
13432    let open = state.last_round_findings();
13433    if !open.is_empty() {
13434        body.push_str("## Open review findings\n\n");
13435        for f in open {
13436            body.push_str(&format!("- `{}` [{:?}]\n", f.id, f.severity));
13437        }
13438        body.push('\n');
13439    }
13440    if let Some(c) = state.change_summary.as_ref()
13441        && head == crate::pr_outcome::FinalHead::At(&c.head)
13442    {
13443        body.push_str(&format!(
13444            "Evidence: final diff `{}`..`{}`; review and verification records from this run.\n",
13445            c.base, c.head
13446        ));
13447    }
13448    body
13449}
13450
13451/// Local-only preview of the operator's task and candidate summary.
13452fn pr_preview(
13453    state: &RunState,
13454    winner: char,
13455    facts: Option<&BranchFacts>,
13456    head: crate::pr_outcome::FinalHead<'_>,
13457) -> PrMessage {
13458    let summary = state
13459        .candidates
13460        .iter()
13461        .find(|c| c.label == winner)
13462        .map(|c| c.summary.as_str())
13463        .unwrap_or_default();
13464    // The fallback is the operator's own words and may not be English; GitHub
13465    // text always is, so a non-English task gets a neutral title instead.
13466    let review = is_review_run(state);
13467    let title = if review {
13468        facts
13469            .and_then(|f| {
13470                english_subject(&f.commits.first()?.0, state.config.graph.github_english())
13471            })
13472            .or_else(|| review_title(state))
13473            .or_else(|| {
13474                state
13475                    .candidates
13476                    .iter()
13477                    .find(|c| c.label == winner)
13478                    .filter(|c| !c.branch.starts_with("magi/"))
13479                    .and_then(|c| english_subject(&c.branch, state.config.graph.github_english()))
13480            })
13481            .unwrap_or_else(|| neutral_title(state, winner))
13482    } else {
13483        summary_title(summary).unwrap_or_else(|| {
13484            english_title(
13485                &state.instruction,
13486                PR_TITLE_MAX,
13487                state.config.graph.github_english(),
13488            )
13489            .unwrap_or_else(|| neutral_title(state, winner))
13490        })
13491    };
13492
13493    let mut body = String::new();
13494    let what = summary_without_title(summary);
13495    if !what.is_empty() {
13496        body.push_str("## Summary\n\n");
13497        body.push_str(&what);
13498        body.push_str("\n\n");
13499    }
13500
13501    // Review history uses structured facts across all rounds, never reports.
13502    body.push_str(&crate::pr_outcome::review_rounds(state));
13503    body.push_str(&crate::pr_outcome::final_verification(state, head));
13504    let fix = state.reviews.iter().rev().find_map(|r| r.fix.as_ref());
13505
13506    let open = state.open_findings();
13507    if !open.is_empty() {
13508        body.push_str("## Open review findings\n\n");
13509        for f in &open {
13510            body.push_str(&format!(
13511                "- `{}` [{:?}] {}\n",
13512                f.id, f.severity, "Context retained in local review records."
13513            ));
13514        }
13515        body.push('\n');
13516    }
13517
13518    if let Some(fix) = fix
13519        && !fix.rejected.is_empty()
13520    {
13521        body.push_str("## Declined by the fixer\n\n");
13522        for r in &fix.rejected {
13523            body.push_str(&format!(
13524                "- `{}`: {}\n",
13525                r.id, "Reason retained in local review records."
13526            ));
13527        }
13528        body.push('\n');
13529    }
13530
13531    if review {
13532        // The review prompt is not the task; list what the branch carries.
13533        body.push_str("## Commits under review\n\n");
13534        if let Some(facts) = facts {
13535            let mut left = COMMITS_MAX_CHARS;
13536            for (i, (subject, text)) in facts.commits.iter().enumerate() {
13537                let mut entry = format!("- {}\n", markdown_safe(subject));
13538                for l in markdown_safe(text).lines() {
13539                    entry.push_str(format!("  {l}\n").trim_end_matches(' '));
13540                }
13541                if left == 0 {
13542                    body.push_str(&format!(
13543                        "- ... {} more commit(s)\n",
13544                        facts.commits.len() - i
13545                    ));
13546                    break;
13547                }
13548                if entry.len() > left {
13549                    // Even the first commit is cut: one huge body must not
13550                    // push the whole description past GitHub's limit.
13551                    let mut end = left;
13552                    while !entry.is_char_boundary(end) {
13553                        end -= 1;
13554                    }
13555                    entry.truncate(end);
13556                    entry.push_str("\n  ... (truncated)\n");
13557                    left = 0;
13558                } else {
13559                    left -= entry.len();
13560                }
13561                body.push_str(&entry);
13562            }
13563            if !facts.stat.trim().is_empty() {
13564                body.push_str(&format!(
13565                    "\n## Diff stat\n\n```\n{}\n```\n",
13566                    markdown_safe(facts.stat.trim())
13567                ));
13568            }
13569        } else {
13570            match &state.reviewed_commits {
13571                Some(subjects) => {
13572                    for s in subjects {
13573                        body.push_str(&format!("- {}\n", s.trim()));
13574                    }
13575                }
13576                None => {
13577                    // An older run kept only the prompt, with the commit list
13578                    // after its first paragraph.
13579                    let rest = state.instruction.split_once("\n\n").map_or("", |(_, r)| r);
13580                    body.push_str(rest.trim());
13581                    body.push('\n');
13582                }
13583            }
13584        }
13585    } else {
13586        let task = state.instruction.trim();
13587        let task = if task.is_empty() {
13588            "(empty task)"
13589        } else {
13590            task
13591        };
13592        body.push_str(&format!(
13593            "<details>\n<summary>Original task</summary>\n\n{}\n\n</details>\n",
13594            task.replace("</details>", "&lt;/details&gt;")
13595        ));
13596    }
13597
13598    body.push_str(&format!(
13599        "\n---\nmagi:run/{} magi:candidate-{}\n",
13600        state.id,
13601        winner.to_ascii_lowercase()
13602    ));
13603
13604    PrMessage { title, body }
13605}
13606
13607/// Source imports have already been prepared from structured inputs. Legacy
13608/// inferred references must never instruct a seat to reconstruct those imports.
13609fn seeded_instruction(state: &RunState) -> String {
13610    let mut inputs = Vec::new();
13611    if let Some(start) = &state.sources.start_from {
13612        inputs.push(format!(
13613            "Start from `{}` at `{}` (including ancestry).",
13614            start.token, start.sha
13615        ));
13616    }
13617    for pick in &state.sources.pick_commits {
13618        inputs.push(format!(
13619            "Pick `{}` at `{}` (single commit).",
13620            pick.token, pick.sha
13621        ));
13622    }
13623    if inputs.is_empty() {
13624        state.instruction.clone()
13625    } else {
13626        format!(
13627            "{}\n\n# Explicit source inputs already prepared\n\n{}",
13628            state.instruction,
13629            inputs.join("\n")
13630        )
13631    }
13632}
13633
13634/// Does the winner have no commits ahead of the base it would land on?
13635/// Any failure to find out reads as "not empty": the merge then behaves as it
13636/// always did rather than refusing on a guess.
13637async fn merge_is_empty(repo: &Path, state: &RunState, branch: &str, mode: MergeMode) -> bool {
13638    let base = &state.base_branch;
13639    let mut against = base.clone();
13640    if mode == MergeMode::Pr {
13641        // A pull request lands on the remote's base, never the local branch
13642        // of the same name: if that cannot be read, "not empty" is the safe
13643        // answer.
13644        let remote = &state.config.merge.remote;
13645        let tracking = format!("{remote}/{base}");
13646        let fetched = git::fetch(repo, remote, base).await;
13647        if fetched.is_ok_and(|o| o.ok()) && git::rev_exists(repo, &tracking).await {
13648            against = tracking;
13649        } else {
13650            return false;
13651        }
13652    }
13653    matches!(git::commits_ahead(repo, &against, branch).await, Ok(0))
13654}
13655
13656/// Why nothing was opened for an empty winner, with what the task's own
13657/// references resolved to.
13658fn empty_candidate_detail(_state: &RunState, base: &str) -> String {
13659    let mut detail = format!(
13660        "empty candidate: the winning branch has 0 commits ahead of {base}, so there is \
13661         nothing to open a pull request for"
13662    );
13663    detail.push_str(
13664        "\nSource imports require explicit --start-from or --pick-commit options on a new task.",
13665    );
13666    detail
13667}
13668
13669/// What the `Pr` merge does once it knows whether the branch already has an
13670/// open pull request.
13671#[derive(Debug, PartialEq, Eq)]
13672enum PrPlan {
13673    Create,
13674    Adopt { url: String, title: String },
13675    Stop(String),
13676}
13677
13678/// Pure decision behind the `Pr` merge: none -> create, one -> adopt, many or
13679/// a failed lookup -> stop with the real reason. Never guesses.
13680fn pr_merge_plan(found: Result<land::OpenPr>) -> PrPlan {
13681    match found {
13682        Ok(land::OpenPr::None) => PrPlan::Create,
13683        Ok(land::OpenPr::One { url, title }) => PrPlan::Adopt { url, title },
13684        Ok(land::OpenPr::Many(urls)) => PrPlan::Stop(format!(
13685            "several open pull requests exist for this branch, not picking one: {}",
13686            urls.join(" ")
13687        )),
13688        Err(e) => PrPlan::Stop(format!("could not look up open pull requests: {e:#}")),
13689    }
13690}
13691
13692/// `gh pr create`, returning the PR url.
13693pub(crate) async fn gh_pr_create(
13694    cwd: &Path,
13695    base: &str,
13696    head: &str,
13697    title: &str,
13698    body: &str,
13699) -> Result<String> {
13700    let out = tokio::process::Command::new("gh")
13701        .args([
13702            "pr", "create", "--base", base, "--head", head, "--title", title, "--body", body,
13703        ])
13704        .current_dir(cwd)
13705        .quiet()
13706        .stdin(std::process::Stdio::null())
13707        .output()
13708        .await
13709        .context("spawn gh")?;
13710    if out.status.success() {
13711        Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
13712    } else {
13713        bail!("{}", String::from_utf8_lossy(&out.stderr).trim().to_owned())
13714    }
13715}
13716
13717/// Never force deletion of uncommitted work, including unknown legacy trees.
13718async fn remove_preserved_worktree(repo: &Path, path: &Path) -> Result<()> {
13719    match std::fs::symlink_metadata(path) {
13720        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
13721            // A previous cleanup may have removed the tree before a branch
13722            // deletion or state save failed. Unregister it if still present.
13723            git::worktree_remove_clean(repo, path).await?;
13724            return Ok(());
13725        }
13726        Err(e) => return Err(e.into()),
13727        Ok(_) => {}
13728    }
13729    if !git::is_clean(path).await? {
13730        bail!(
13731            "worktree has uncommitted work; refusing removal: {}",
13732            path.display()
13733        );
13734    }
13735    if !git::worktree_remove_clean(repo, path).await? {
13736        bail!("worktree removal refused: {}", path.display());
13737    }
13738    Ok(())
13739}
13740
13741/// Read seats return replies, not working-tree changes. Only registered,
13742/// detached seats directly inside this run's root may discard those changes.
13743async fn remove_read_seat_worktree(state: &mut RunState, path: &Path) -> Result<()> {
13744    if !crate::retention::read_seat(path) || !path.exists() {
13745        return remove_preserved_worktree(&state.repo, path).await;
13746    }
13747    let owned = std::fs::symlink_metadata(path)?.is_dir()
13748        && path.parent().map(Path::canonicalize).transpose()?
13749            == Some(state.worktree_root().canonicalize()?)
13750        && crate::retention::worktrees(state)
13751            .await?
13752            .contains(&path.canonicalize()?);
13753    let common = crate::repo_lock::common_dir(&state.repo).await?;
13754    if !owned
13755        || common.is_none()
13756        || crate::repo_lock::common_dir(path).await? != common
13757        || git::git_raw(path, &["symbolic-ref", "-q", "HEAD"])
13758            .await?
13759            .ok()
13760        || state.candidates.iter().any(|c| c.worktree == path)
13761    {
13762        return remove_preserved_worktree(&state.repo, path).await;
13763    }
13764    let changes = git::status_porcelain(path).await?;
13765    if !git::worktree_remove(&state.repo, path).await? {
13766        bail!(
13767            "read-only seat worktree removal refused: {}",
13768            path.display()
13769        );
13770    }
13771    if !changes.is_empty() {
13772        let paths = changes.lines().take(20).collect::<Vec<_>>().join("; ");
13773        let paths: String = paths.chars().take(1024).collect();
13774        state.event(
13775            "fold",
13776            format!(
13777                "discarded read-only seat {} changes ({} status entries; first 20, at most 1024 chars): {paths}",
13778                path.file_name().unwrap_or_default().to_string_lossy(),
13779                changes.lines().count()
13780            ),
13781        );
13782    }
13783    Ok(())
13784}
13785
13786fn fold_target(
13787    home: &Path,
13788    root: &Path,
13789    path: &Path,
13790    isolated: bool,
13791) -> Option<crate::build_target::FoldTarget> {
13792    if !isolated {
13793        return None;
13794    }
13795    match crate::build_target::FoldTarget::for_checkout(home, path, root) {
13796        Ok(target) => target,
13797        Err(error) => {
13798            tracing::warn!(checkout = %path.display(), %error, "isolated target binding not proved at fold");
13799            None
13800        }
13801    }
13802}
13803
13804fn reclaim_fold_target(home: &Path, target: Option<crate::build_target::FoldTarget>) {
13805    if let Some(target) = target
13806        && let Err(error) = target.reclaim_orphaned_target(home)
13807    {
13808        tracing::warn!(%error, "isolated target retained after fold");
13809    }
13810}
13811
13812/// Tear a run's worktrees and branches down.
13813///
13814/// `home` is where the updated `run.json` is saved (via
13815/// [`RunState::save_under`]), never the process-global [`crate::run::home`]:
13816/// a housekeeping pass already has its own honest `home` handed to it, and
13817/// falling through to the global here would write back through whichever
13818/// directory some other process or test pinned into that `OnceLock` first,
13819/// not the one the caller actually resolved its `runs` and `state` from.
13820pub async fn fold_run(state: &mut RunState, drop_winner: bool, home: &Path) -> Result<Vec<String>> {
13821    fold_run_with_policy(state, drop_winner, home, false).await
13822}
13823
13824/// Explicit CLI-only retention override; automatic callers use [`fold_run`].
13825pub async fn fold_run_overriding_recovery_retention(
13826    state: &mut RunState,
13827    drop_winner: bool,
13828    home: &Path,
13829) -> Result<Vec<String>> {
13830    fold_run_with_policy(state, drop_winner, home, true).await
13831}
13832
13833async fn fold_run_with_policy(
13834    state: &mut RunState,
13835    drop_winner: bool,
13836    home: &Path,
13837    override_recovery_retention: bool,
13838) -> Result<Vec<String>> {
13839    if let Some(reason) = crate::pr_recovery::source_retention_reason(home, state)
13840        && !override_recovery_retention
13841    {
13842        bail!("refusing fold: {reason}");
13843    }
13844    if !state.candidate_preservation.is_empty() || !state.interrupted_implementations.is_empty() {
13845        bail!("candidate preservation incomplete; refusing cleanup");
13846    }
13847    // Serialize ordinary folding with the same starts/resumes as target-only
13848    // eviction. Otherwise a second janitor could remove the whole worktree
13849    // around a live output borrower even though target eviction was fenced.
13850    std::fs::create_dir_all(home.join("runs").join(&state.id))?;
13851    let _owner = crate::pr_head::owner_lock(home, &state.id)?;
13852    // An override must use current durable ownership, not a pre-lock snapshot.
13853    if override_recovery_retention {
13854        *state = RunState::load_under(&state.id, home)?;
13855        anyhow::ensure!(
13856            state.status.done() && !state.status.resumable(),
13857            "recovery retention override requires a finished, non-resumable run"
13858        );
13859        let claimed = crate::daemon::is_working_on_other(home, &state.id, Timestamp::now())?;
13860        anyhow::ensure!(
13861            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
13862            "run is live or its ownership is unknown"
13863        );
13864        anyhow::ensure!(
13865            state.candidate_preservation.is_empty() && state.interrupted_implementations.is_empty(),
13866            "candidate preservation incomplete; refusing cleanup"
13867        );
13868    }
13869    let retention_reason = crate::pr_recovery::source_retention_reason(home, state);
13870    if let Some(reason) = &retention_reason
13871        && !override_recovery_retention
13872    {
13873        bail!("refusing fold: {reason}");
13874    }
13875    let _driver = crate::driver::maintenance(home, &state.id)?;
13876    let mut output_guards = Vec::new();
13877    for entry in std::fs::read_dir(state.worktree_root())
13878        .into_iter()
13879        .flatten()
13880        .flatten()
13881    {
13882        if entry.path().join(".git").is_file() {
13883            output_guards.push(crate::retention::OutputLease::take(&entry.path(), true)?);
13884        }
13885    }
13886    let repo = state.repo.clone();
13887    // CLI, Web and automatic cleanup all enter here, independently of
13888    // Runner::fold_losers. Protect deletion and shared config release too.
13889    let wait = repository_wait(state, None);
13890    let _coordination = match coordinate_operation(state, &repo, &wait).await {
13891        Ok(lease) => lease,
13892        Err(e) => {
13893            state.save_under(home)?;
13894            return Err(e);
13895        }
13896    };
13897    // Confirmed merges dispose of their owned sources after durable evidence
13898    // capture. Preflight every source before removing anything.
13899    let _source_outputs = if retention_reason.is_some()
13900        || (state.status == RunStatus::Merged && state.merge.as_ref().is_some_and(|merge| merge.ok))
13901    {
13902        verify_merged_fold_sources(state, drop_winner, home).await?
13903    } else {
13904        Vec::new()
13905    };
13906    if let Some(reason) = retention_reason {
13907        state.event(
13908            "fold",
13909            format!(
13910                "operator CLI --override-recovery-retention authorized deletion for run {}: bypassed {reason}",
13911                state.id
13912            ),
13913        );
13914        state.save_under(home)?;
13915    }
13916    let root = state.worktree_root();
13917    let winner = state.tally.as_ref().map(|t| t.winner);
13918    let mut removed = Vec::new();
13919    let isolated = crate::build_target::isolated(&state.config);
13920
13921    for i in 0..state.candidates.len() {
13922        let c = state.candidates[i].clone();
13923        let is_winner = Some(c.label) == winner;
13924        if is_winner && !drop_winner {
13925            continue;
13926        }
13927        let existed = c.worktree.exists();
13928        let target = fold_target(home, &root, &c.worktree, isolated);
13929        // A vanished directory can still have a Git registration that keeps
13930        // its branch checked out. Remove that registration before the branch.
13931        remove_preserved_worktree(&repo, &c.worktree).await?;
13932        reclaim_fold_target(home, target);
13933        if existed {
13934            removed.push(c.worktree.to_string_lossy().into_owned());
13935        }
13936        // A branch handed to a later run (and its pull request) is not this
13937        // run's to delete.
13938        let handed_over = state.released_branches.contains(&c.branch);
13939        if !handed_over && git::branch_exists(&repo, &c.branch).await? {
13940            if !git::branch_delete(&repo, &c.branch).await? {
13941                bail!("candidate branch removal refused");
13942            }
13943            removed.push(c.branch.clone());
13944        }
13945        state.candidates[i].folded = true;
13946    }
13947
13948    for name in std::fs::read_dir(&root).into_iter().flatten().flatten() {
13949        let path = name.path();
13950        let keep = !drop_winner
13951            && winner.is_some_and(|w| {
13952                path.file_name()
13953                    .is_some_and(|n| n == format!("cand-{w}").as_str())
13954            });
13955        if keep {
13956            continue;
13957        }
13958        let target = fold_target(home, &root, &path, isolated);
13959        remove_read_seat_worktree(state, &path).await?;
13960        reclaim_fold_target(home, target);
13961        removed.push(path.to_string_lossy().into_owned());
13962    }
13963
13964    // `root` (`wt/<...>/<short>/`) held nothing but this run's candidate and
13965    // judge worktrees, so once the loop above has cleared all of them out,
13966    // the parent is a bare directory nobody else was ever going to remove -
13967    // git only ever managed what was inside it. Left alone, one of these
13968    // accumulates per fully-folded run; the operator's own machine had 74.
13969    // `remove_if_empty` re-checks rather than assuming: a run whose winner
13970    // was kept (`!drop_winner`) leaves its directory behind on purpose, and
13971    // so does anything a run never claimed that happens to share the bay.
13972    remove_if_empty(&root);
13973
13974    if state.enabled_worktree_config && drop_winner {
13975        // A release, not a raw disable: some sibling run in this repository
13976        // may still hold its own reference (see `git::acquire_worktree_config`),
13977        // and only the last release actually turns the setting back off.
13978        git::release_worktree_config(&repo).await.ok();
13979        state.enabled_worktree_config = false;
13980    }
13981    state.save_under(home)?;
13982    Ok(removed)
13983}
13984
13985async fn verify_merged_fold_sources(
13986    state: &RunState,
13987    drop_winner: bool,
13988    home: &Path,
13989) -> Result<Vec<std::fs::File>> {
13990    let winner = state.tally.as_ref().map(|t| t.winner);
13991    let mut heads = BTreeSet::new();
13992    for candidate in &state.candidates {
13993        if Some(candidate.label) == winner && !drop_winner {
13994            continue;
13995        }
13996        anyhow::ensure!(
13997            candidate.worktree.parent() == Some(state.worktree_root().as_path()),
13998            "candidate recovery source is outside the inventoried run root: {}",
13999            candidate.worktree.display()
14000        );
14001        match std::fs::symlink_metadata(&candidate.worktree) {
14002            Ok(_) => {}
14003            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
14004            Err(error) => return Err(error.into()),
14005        }
14006        if !state.released_branches.contains(&candidate.branch)
14007            && git::branch_exists(&state.repo, &candidate.branch).await?
14008        {
14009            heads.insert(git::rev_parse(&state.repo, &candidate.branch).await?);
14010        }
14011    }
14012    let mut cargo_guards = Vec::new();
14013    let entries = match std::fs::read_dir(state.worktree_root()) {
14014        Ok(entries) => Some(entries),
14015        Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
14016        Err(error) => return Err(error.into()),
14017    };
14018    for entry in entries.into_iter().flatten() {
14019        let path = entry?.path();
14020        let metadata = std::fs::symlink_metadata(&path)?;
14021        anyhow::ensure!(
14022            metadata.is_dir() && !metadata.file_type().is_symlink(),
14023            "non-directory or symlink recovery source retained: {}",
14024            path.display()
14025        );
14026        if !drop_winner
14027            && winner.is_some_and(|w| {
14028                path.file_name()
14029                    .is_some_and(|name| name == format!("cand-{w}").as_str())
14030            })
14031        {
14032            continue;
14033        }
14034        anyhow::ensure!(
14035            path.join(".git").is_file(),
14036            "unregistered recovery source retained: {}",
14037            path.display()
14038        );
14039        anyhow::ensure!(
14040            git::git(
14041                &path,
14042                &[
14043                    "status",
14044                    "--porcelain",
14045                    "--untracked-files=all",
14046                    "--ignored",
14047                    "--",
14048                    ".",
14049                    ":(exclude)target"
14050                ]
14051            )
14052            .await?
14053            .is_empty(),
14054            "source changes or ignored recovery files retained: {}",
14055            path.display()
14056        );
14057        match std::fs::symlink_metadata(path.join("target")) {
14058            Ok(_) => {
14059                cargo_guards.extend(crate::retention::verify_residue(home, &state.id, &path).await?)
14060            }
14061            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
14062            Err(error) => return Err(error.into()),
14063        }
14064        for checkpoint in [
14065            "rebase-merge",
14066            "rebase-apply",
14067            "sequencer",
14068            "CHERRY_PICK_HEAD",
14069            "MERGE_HEAD",
14070            "REBASE_HEAD",
14071            "REVERT_HEAD",
14072            "BISECT_LOG",
14073            "AUTO_MERGE",
14074            "MERGE_MSG",
14075        ] {
14076            let location = git::git(
14077                &path,
14078                &[
14079                    "rev-parse",
14080                    "--path-format=absolute",
14081                    "--git-path",
14082                    checkpoint,
14083                ],
14084            )
14085            .await?;
14086            anyhow::ensure!(
14087                matches!(std::fs::symlink_metadata(location.trim()), Err(ref e)
14088                if e.kind() == std::io::ErrorKind::NotFound),
14089                "Git recovery checkpoint retained: {checkpoint}"
14090            );
14091        }
14092        heads.insert(git::rev_parse(&path, "HEAD").await?);
14093    }
14094    crate::fold_evidence::preserve(state, home, &heads).await?;
14095
14096    Ok(cargo_guards)
14097}
14098
14099/// Remove `dir` if it exists and has nothing in it.
14100///
14101/// Best-effort and silent by design: a directory that is not empty (a run
14102/// whose winner is still parked there, a stray file some other process left)
14103/// is exactly the case this must refuse, and a directory that is already gone
14104/// is not a failure worth reporting either. `std::fs::remove_dir` itself
14105/// already refuses a non-empty directory, so the emptiness check below is
14106/// belt, not suspenders - it is what keeps this from ever attempting the
14107/// removal in the case that matters, rather than trusting `remove_dir`'s
14108/// error path to have no side effects if it ever changed.
14109fn remove_if_empty(dir: &Path) {
14110    if dir.is_dir() && std::fs::read_dir(dir).is_ok_and(|mut entries| entries.next().is_none()) {
14111        std::fs::remove_dir(dir).ok();
14112    }
14113}
14114
14115/// Severity of the worst open finding in the last review round, for reporting.
14116pub fn worst_open(state: &RunState) -> Option<Severity> {
14117    state
14118        .reviews
14119        .last()?
14120        .reviews
14121        .iter()
14122        .flat_map(|r| r.findings.iter())
14123        .map(|f| f.severity)
14124        .max()
14125}
14126
14127/// `[worktree] setup` hides its products per worktree, which needs
14128/// `extensions.worktreeConfig`. Taken once per run and released with the run's
14129/// worktrees, like the hook's; every place that runs setup calls this first.
14130async fn ensure_setup_config(state: &mut RunState, repo: &Path) -> Result<()> {
14131    if !state.config.worktree.setup.is_empty() && !state.enabled_worktree_config {
14132        git::acquire_worktree_config(repo).await?;
14133        state.enabled_worktree_config = true;
14134    }
14135    Ok(())
14136}
14137
14138#[cfg(test)]
14139mod tests {
14140    #[tokio::test]
14141    async fn launcher_base_fetch_requires_remote_success() {
14142        let tmp = tempfile::tempdir().unwrap();
14143        let repo = tmp.path().join("repo");
14144        let remote = tmp.path().join("remote");
14145        std::fs::create_dir(&repo).unwrap();
14146        std::fs::create_dir(&remote).unwrap();
14147        git::git(&remote, &["init", "--bare", "-b", "main"])
14148            .await
14149            .unwrap();
14150        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
14151        git::git(
14152            &repo,
14153            &[
14154                "-c",
14155                "user.name=Fixture",
14156                "-c",
14157                "user.email=fixture@example.invalid",
14158                "commit",
14159                "--allow-empty",
14160                "-m",
14161                "fixture",
14162            ],
14163        )
14164        .await
14165        .unwrap();
14166        git::git(
14167            &repo,
14168            &["remote", "add", "origin", remote.to_str().unwrap()],
14169        )
14170        .await
14171        .unwrap();
14172        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
14173        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
14174        assert_eq!(
14175            resolve_base(&repo, "main", "origin", None)
14176                .await
14177                .unwrap()
14178                .commit,
14179            head
14180        );
14181        #[cfg(unix)]
14182        {
14183            let policy: crate::config::Coordination = toml::from_str(
14184                "contract_file='fixture.contract'\ncontract_token='fixture-v1'\nlock_file='fixture.lock'",
14185            ).unwrap();
14186            std::fs::write(repo.join(".git/fixture.contract"), "fixture-v1").unwrap();
14187            std::fs::remove_file(repo.join(".git/FETCH_HEAD")).unwrap();
14188            let held = crate::repo_lock::SeatLease::operation_with(
14189                &repo,
14190                Some(&policy),
14191                &crate::repo_lock::WaitPolicy::default(),
14192            )
14193            .await
14194            .unwrap();
14195            assert!(held.is_some());
14196            let fetch = resolve_base(&repo, "main", "origin", Some(&policy));
14197            tokio::pin!(fetch);
14198            assert!(
14199                tokio::time::timeout(Duration::from_millis(50), &mut fetch)
14200                    .await
14201                    .is_err()
14202            );
14203            assert!(
14204                !repo.join(".git/FETCH_HEAD").exists(),
14205                "no fetch before admission"
14206            );
14207            drop(held);
14208            let fetched = fetch.await.unwrap();
14209            assert_eq!(fetched.commit, head);
14210            assert_eq!(fetched.remote, "origin");
14211            assert_eq!(fetched.branch, "main");
14212        }
14213        // A surviving tracking ref is not successful fetch evidence.
14214        git::git(
14215            &repo,
14216            &[
14217                "remote",
14218                "set-url",
14219                "origin",
14220                tmp.path().join("missing").to_str().unwrap(),
14221            ],
14222        )
14223        .await
14224        .unwrap();
14225        let error = resolve_base(&repo, "main", "origin", None)
14226            .await
14227            .unwrap_err()
14228            .to_string();
14229        assert!(error.contains("cannot read origin/main"));
14230        assert!(error.contains("refusing to branch off"));
14231    }
14232
14233    #[test]
14234    fn should_retitle_only_replaces_magi_shaped_or_leaked_titles() {
14235        let leaked = vec!["chore(deps): update a crate".to_owned()];
14236        let own = "fix(daemon): apply a chosen action";
14237        assert!(should_retitle("", own, &leaked));
14238        assert!(should_retitle(
14239            &format!("{REVIEW_PROMPT_OPENING} `x`"),
14240            own,
14241            &leaked
14242        ));
14243        assert!(should_retitle(
14244            "chore: land candidate A of run 1",
14245            own,
14246            &leaked
14247        ));
14248        assert!(should_retitle(
14249            "magi: candidate A (uncommitted work)",
14250            own,
14251            &leaked
14252        ));
14253        assert!(should_retitle("chore(deps): update a crate", own, &leaked));
14254        assert!(!should_retitle("feat: renamed by hand", own, &leaked));
14255        assert!(!should_retitle("", "chore(deps): update a crate", &leaked));
14256    }
14257
14258    #[test]
14259    fn pr_merge_plan_creates_adopts_or_stops() {
14260        assert_eq!(pr_merge_plan(Ok(land::OpenPr::None)), PrPlan::Create);
14261        assert_eq!(
14262            pr_merge_plan(Ok(land::OpenPr::One {
14263                url: "u".into(),
14264                title: "t".into()
14265            })),
14266            PrPlan::Adopt {
14267                url: "u".into(),
14268                title: "t".into()
14269            }
14270        );
14271        let PrPlan::Stop(many) =
14272            pr_merge_plan(Ok(land::OpenPr::Many(vec!["a".into(), "b".into()])))
14273        else {
14274            panic!("many must stop");
14275        };
14276        assert!(many.contains('a') && many.contains('b'));
14277        let PrPlan::Stop(err) = pr_merge_plan(Err(anyhow::anyhow!("bad token"))) else {
14278            panic!("a failed lookup must stop");
14279        };
14280        assert!(err.contains("bad token"));
14281    }
14282
14283    use super::*;
14284    use crate::run::GateStatus;
14285    use std::collections::BTreeMap;
14286    use std::time::Duration;
14287
14288    fn conductor() -> AgentSpec {
14289        AgentSpec {
14290            id: "conductor".to_owned(),
14291            kind: crate::config::AgentKind::Command,
14292            model: None,
14293            command: vec!["true".to_owned()],
14294            extra_args: Vec::new(),
14295            env: BTreeMap::new(),
14296            prompt_delivery: None,
14297            max_turn_secs: None,
14298        }
14299    }
14300
14301    fn spec(id: &str) -> AgentSpec {
14302        AgentSpec {
14303            id: id.to_owned(),
14304            kind: crate::config::AgentKind::Command,
14305            model: None,
14306            command: vec!["true".to_owned()],
14307            extra_args: Vec::new(),
14308            env: BTreeMap::new(),
14309            prompt_delivery: None,
14310            max_turn_secs: None,
14311        }
14312    }
14313
14314    fn ids(xs: &[&str]) -> BTreeSet<String> {
14315        xs.iter().map(|s| (*s).to_owned()).collect()
14316    }
14317
14318    #[test]
14319    fn pick_successor_skips_an_agent_another_seat_holds() {
14320        // Seats a and b of roster [a, b, c]; a fails, b holds the other seat.
14321        let roster = [spec("a"), spec("b"), spec("c")];
14322        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
14323        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
14324    }
14325
14326    #[test]
14327    fn pick_successor_respects_the_occupant_after_an_earlier_handover() {
14328        // The other seat started on c but was handed to d; c is free again.
14329        let roster = [spec("a"), spec("b"), spec("c"), spec("d")];
14330        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
14331        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
14332        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b", "c"]));
14333        assert_eq!(next.map(|s| s.id.as_str()), Some("d"));
14334    }
14335
14336    #[test]
14337    fn pick_successor_falls_back_to_a_duplicate_when_no_distinct_agent_remains() {
14338        let roster = [spec("a"), spec("b")];
14339        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
14340        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14341        let carried = ids(&["b"]);
14342        let next = pick_successor(&roster, 0, &ids(&["a"]), Some(&carried), &ids(&["b"]));
14343        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14344    }
14345
14346    #[test]
14347    fn pick_successor_returns_none_without_any_untried_successor() {
14348        let roster = [spec("a"), spec("b")];
14349        assert!(pick_successor(&roster, 1, &ids(&["b"]), None, &ids(&["a"])).is_none());
14350        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), None, &ids(&[])).is_none());
14351        let carried = ids(&["a"]);
14352        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), Some(&carried), &ids(&[])).is_none());
14353    }
14354
14355    #[test]
14356    fn pick_successor_rescue_avoids_another_seats_occupant() {
14357        // b is a carried failure and free; a is held by the other seat.
14358        let roster = [spec("a"), spec("b"), spec("c")];
14359        let carried = ids(&["b", "c"]);
14360        let next = pick_successor(&roster, 2, &ids(&["c"]), Some(&carried), &ids(&["a"]));
14361        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14362    }
14363
14364    #[test]
14365    fn next_for_seat_prefers_an_agent_that_has_not_failed() {
14366        let roster = [spec("a"), spec("b"), spec("c")];
14367        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["b"]));
14368        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
14369    }
14370
14371    #[test]
14372    fn next_for_seat_rescues_a_failed_agent_only_when_nothing_else_is_left() {
14373        let roster = [spec("a"), spec("b"), spec("c")];
14374        let failed = ids(&["a", "b", "c"]);
14375        // Rescue looks at the whole roster, once per id, then runs out.
14376        let mut tried = ids(&["b"]);
14377        let first = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
14378        assert_eq!(first.id, "a");
14379        tried.insert(first.id.clone());
14380        let second = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
14381        assert_eq!(second.id, "c");
14382        tried.insert(second.id.clone());
14383        assert!(next_for_seat(&roster, 1, &tried, &failed).is_none());
14384    }
14385
14386    #[test]
14387    fn next_for_seat_ignores_failed_ids_no_longer_on_the_roster() {
14388        let roster = [spec("a"), spec("b")];
14389        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["gone"]));
14390        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14391    }
14392
14393    #[test]
14394    fn pick_start_spec_starts_on_the_last_answerer_when_still_eligible() {
14395        let roster = [spec("a"), spec("b"), spec("c")];
14396        let h = SeatHistory {
14397            failed: ids(&["a"]),
14398            last_ok: Some("b".to_owned()),
14399            last_fail: None,
14400        };
14401        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&h)).id, "b");
14402        // A last answerer that left the roster, or later failed, is ignored.
14403        let gone = SeatHistory {
14404            last_ok: Some("zzz".to_owned()),
14405            ..h.clone()
14406        };
14407        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&gone)).id, "b");
14408        let failed = SeatHistory {
14409            failed: ids(&["a", "b"]),
14410            last_ok: Some("b".to_owned()),
14411            last_fail: None,
14412        };
14413        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&failed)).id, "c");
14414    }
14415
14416    #[test]
14417    fn handover_seat_mints_a_session_id_distinct_from_the_previous_agents() {
14418        let first = SeatState::new("review-1", "alpha", 7);
14419        let next = handover_seat("review-1", "gamma", 7);
14420        assert_ne!(first.claude_session, next.claude_session);
14421    }
14422
14423    #[test]
14424    fn re_handing_a_seat_to_the_same_agent_mints_a_new_session_id() {
14425        let mut state = state_with_summary("x", "y");
14426        let a = handover_seat("review-1", "beta", state.next_seat_seed());
14427        let b = handover_seat("review-1", "beta", state.next_seat_seed());
14428        assert_ne!(a.claude_session, b.claude_session);
14429    }
14430
14431    #[test]
14432    fn pick_start_spec_falls_back_to_the_spec_when_the_whole_roster_failed() {
14433        let roster = [spec("a"), spec("b")];
14434        let h = SeatHistory {
14435            failed: ids(&["a", "b"]),
14436            ..SeatHistory::default()
14437        };
14438        assert_eq!(pick_start_spec(&roster, spec("b"), Some(&h)).id, "b");
14439        assert_eq!(pick_start_spec(&roster, spec("b"), None).id, "b");
14440        assert_eq!(pick_start_spec(&[], spec("b"), Some(&h)).id, "b");
14441    }
14442
14443    // `next_untried_in_roster` is the property `resume_seat_handovers`'s own
14444    // fallback loop depends on to terminate: it must walk forward from the
14445    // seat's own position, never restart at the front of the roster, and it
14446    // must never hand back an id already tried, however many times that id
14447    // happens to appear.
14448
14449    #[test]
14450    fn failure_signature_ignores_numbers_and_paths() {
14451        assert_eq!(
14452            failure_signature("exited with Some(2) and no usable output"),
14453            failure_signature("exited with Some(137) and no usable output")
14454        );
14455        assert_eq!(
14456            failure_signature("process exited with no usable output (exit code 2)"),
14457            failure_signature("process exited with no usable output (exit code 137)")
14458        );
14459        for (old, new) in [
14460            (
14461                "exited with Some(2) and no usable output",
14462                "process exited with no usable output (exit code 2)",
14463            ),
14464            (
14465                "exited with None and no usable output",
14466                "process exited with no usable output (exit code unavailable)",
14467            ),
14468        ] {
14469            let previous = FailClass::Other(failure_signature(old));
14470            let current = FailClass::Other(failure_signature(new));
14471            assert_eq!(previous, current, "resumption retains the failure class");
14472            assert!(!should_hand_over(Some(&previous), &current));
14473        }
14474        assert_eq!(
14475            failure_signature("cannot open /tmp/a/b.txt: denied\nsecond line"),
14476            failure_signature("cannot open /var/x.txt: denied")
14477        );
14478        assert_ne!(failure_signature("boom"), failure_signature("bang"));
14479    }
14480
14481    #[test]
14482    fn quota_and_timeout_always_hand_over_other_failures_stop_on_a_repeat() {
14483        let other = FailClass::Other("x".into());
14484        assert!(should_hand_over(None, &FailClass::Quota));
14485        assert!(should_hand_over(Some(&other), &FailClass::Quota));
14486        assert!(should_hand_over(
14487            Some(&FailClass::Timeout),
14488            &FailClass::Timeout
14489        ));
14490        assert!(should_hand_over(None, &other));
14491        assert!(!should_hand_over(Some(&other), &other));
14492        assert!(should_hand_over(
14493            Some(&other),
14494            &FailClass::Other("y".into())
14495        ));
14496        // A quota or timeout in between ends the run of identical failures.
14497        assert!(should_hand_over(Some(&FailClass::Timeout), &other));
14498        assert!(should_hand_over(Some(&FailClass::Quota), &other));
14499    }
14500
14501    #[test]
14502    fn a_handover_seat_never_reuses_the_previous_agents_session_id() {
14503        let a = SeatState::new("judge-1", "alpha", 7);
14504        let b = handover_seat("judge-1", "beta", 7);
14505        assert_ne!(a.claude_session, b.claude_session);
14506        assert_eq!(b.turns, 0);
14507    }
14508
14509    #[test]
14510    fn a_timeout_is_classified_apart_from_other_failures() {
14511        assert_eq!(
14512            FailClass::of(&AgentOutcome::Failed(TIMED_OUT.to_owned())),
14513            Some(FailClass::Timeout)
14514        );
14515        assert!(matches!(
14516            FailClass::of(&AgentOutcome::Failed("boom".to_owned())),
14517            Some(FailClass::Other(_))
14518        ));
14519    }
14520
14521    #[test]
14522    fn next_untried_in_roster_walks_forward_from_the_seats_own_position() {
14523        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
14524        let tried = BTreeSet::from(["beta".to_owned()]);
14525        // beta sits at index 1; the next candidate is gamma, never alpha —
14526        // which is very likely a different candidate slot's own agent.
14527        let next = next_untried_in_roster(&roster, 1, &tried);
14528        assert_eq!(next.map(|s| s.id.as_str()), Some("gamma"));
14529    }
14530
14531    #[test]
14532    fn next_untried_in_roster_does_not_wrap_back_past_its_own_start() {
14533        let roster = vec![spec("alpha"), spec("beta")];
14534        let tried = BTreeSet::from(["beta".to_owned()]);
14535        // beta is the roster's last entry: nothing follows it, and alpha —
14536        // earlier in the roster, almost certainly a different candidate
14537        // slot's own agent — must not be reached by wrapping back to it.
14538        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
14539    }
14540
14541    #[test]
14542    fn next_untried_in_roster_stops_once_the_tail_is_exhausted_even_if_earlier_ids_are_untried() {
14543        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
14544        let tried = BTreeSet::from(["beta".to_owned(), "gamma".to_owned()]);
14545        // beta (index 1) and gamma (index 2, the only entry after it) have
14546        // both been tried; alpha (index 0) never has, but it comes before
14547        // beta's own position, so there is nothing further for this seat.
14548        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
14549    }
14550
14551    #[test]
14552    fn next_untried_in_roster_skips_ids_already_tried_even_when_duplicated() {
14553        let roster = vec![spec("a"), spec("a"), spec("b")];
14554        let tried = BTreeSet::from(["a".to_owned()]);
14555        let next = next_untried_in_roster(&roster, 0, &tried);
14556        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14557    }
14558
14559    #[test]
14560    fn next_untried_in_roster_returns_none_once_every_id_is_tried() {
14561        let roster = vec![spec("a"), spec("b")];
14562        let tried = BTreeSet::from(["a".to_owned(), "b".to_owned()]);
14563        assert!(next_untried_in_roster(&roster, 0, &tried).is_none());
14564    }
14565
14566    #[test]
14567    fn remove_if_empty_only_ever_takes_a_bare_directory() {
14568        let dir = tempfile::tempdir().unwrap();
14569        let bay = dir.path().join("ffff");
14570
14571        // Not there yet: nothing to do, nothing to panic on.
14572        remove_if_empty(&bay);
14573        assert!(!bay.exists());
14574
14575        // Something still inside - the winner's worktree, or a stray file -
14576        // keeps the directory standing.
14577        std::fs::create_dir_all(bay.join("cand-A")).unwrap();
14578        remove_if_empty(&bay);
14579        assert!(bay.exists(), "non-empty directory must survive");
14580
14581        // Once the last entry is gone, so is the directory itself.
14582        std::fs::remove_dir(bay.join("cand-A")).unwrap();
14583        remove_if_empty(&bay);
14584        assert!(!bay.exists(), "an empty bay is a leftover, not a record");
14585    }
14586
14587    // `round_is_clean` is the exact decision this task fixed: a round with a
14588    // seat that never answered must not read the same as a round every seat
14589    // actually reviewed. These are deterministic and process-free by design —
14590    // the equivalent end-to-end check (a real reviewer timing out under a
14591    // live graph run) is a genuine race against wall-clock contention, and a
14592    // spawn slow enough to blow even a generous budget under a loaded test
14593    // run must not turn this specific regression check flaky.
14594
14595    #[test]
14596    fn a_full_panel_that_found_nothing_is_clean() {
14597        assert!(round_is_clean(
14598            0,
14599            true,
14600            2,
14601            2,
14602            0,
14603            IncompleteReviewPolicy::Block
14604        ));
14605    }
14606
14607    #[test]
14608    fn a_missing_seat_is_never_clean_under_the_default_policy() {
14609        assert!(!round_is_clean(
14610            0,
14611            true,
14612            1,
14613            2,
14614            0,
14615            IncompleteReviewPolicy::Block
14616        ));
14617    }
14618
14619    #[test]
14620    fn warn_policy_still_refuses_a_missing_seat_with_open_findings() {
14621        assert!(!round_is_clean(
14622            1,
14623            true,
14624            1,
14625            2,
14626            0,
14627            IncompleteReviewPolicy::Warn
14628        ));
14629    }
14630
14631    #[test]
14632    fn warn_policy_gates_a_missing_seat_once_what_answered_is_clean() {
14633        assert!(round_is_clean(
14634            0,
14635            true,
14636            1,
14637            2,
14638            0,
14639            IncompleteReviewPolicy::Warn
14640        ));
14641    }
14642
14643    #[test]
14644    fn a_full_panel_with_an_open_finding_is_not_clean() {
14645        assert!(!round_is_clean(
14646            1,
14647            true,
14648            2,
14649            2,
14650            0,
14651            IncompleteReviewPolicy::Block
14652        ));
14653    }
14654
14655    #[test]
14656    fn a_full_panel_with_a_red_e2e_is_not_clean() {
14657        assert!(!round_is_clean(
14658            0,
14659            false,
14660            2,
14661            2,
14662            0,
14663            IncompleteReviewPolicy::Block
14664        ));
14665    }
14666
14667    // The stall this task closes: under the default `block` policy, a seat
14668    // missing only because it was rate limited must not force a wait for a
14669    // session limit that will not lift by the next round. `round_is_clean`
14670    // is where that quorum carve-out lives; the review loop around it never
14671    // changes what a reviewer's vote or a finding's severity means.
14672
14673    #[test]
14674    fn a_seat_missing_only_to_its_own_quota_is_clean_under_the_default_policy() {
14675        // 1 of 2 answered, and the one missing was quota'd — the exact
14676        // "review-2 rate limited (quota)" shape from the field report.
14677        assert!(round_is_clean(
14678            0,
14679            true,
14680            1,
14681            2,
14682            1,
14683            IncompleteReviewPolicy::Block
14684        ));
14685    }
14686
14687    #[test]
14688    fn a_seat_missing_for_a_reason_other_than_quota_still_waits() {
14689        // 1 of 2 answered, but the miss was a crash/timeout/parse failure,
14690        // not a quota loss (`quota_missing` stays 0) — worth another try.
14691        assert!(!round_is_clean(
14692            0,
14693            true,
14694            1,
14695            2,
14696            0,
14697            IncompleteReviewPolicy::Block
14698        ));
14699    }
14700
14701    #[test]
14702    fn a_quota_loss_does_not_excuse_an_open_finding_or_a_red_e2e() {
14703        assert!(!round_is_clean(
14704            1,
14705            true,
14706            1,
14707            2,
14708            1,
14709            IncompleteReviewPolicy::Block
14710        ));
14711        assert!(!round_is_clean(
14712            0,
14713            false,
14714            1,
14715            2,
14716            1,
14717            IncompleteReviewPolicy::Block
14718        ));
14719    }
14720
14721    #[test]
14722    fn a_panel_lost_entirely_to_quota_still_waits_rather_than_deciding_on_nobody() {
14723        // Every seat quota'd, nobody answered: there is no panel to decide
14724        // on, so this must fall through to the existing block-and-retry
14725        // fallback rather than call an unreviewed patch clean.
14726        assert!(!round_is_clean(
14727            0,
14728            true,
14729            0,
14730            2,
14731            2,
14732            IncompleteReviewPolicy::Block
14733        ));
14734    }
14735
14736    fn outcome(code: Option<i32>, resource_blocked: bool) -> CommandOutcome {
14737        CommandOutcome {
14738            command: "test".to_owned(),
14739            code,
14740            output_tail: String::new(),
14741            duration_ms: 0,
14742            resource_blocked,
14743        }
14744    }
14745
14746    #[cfg(unix)]
14747    #[tokio::test]
14748    async fn incremental_admission_is_a_resource_hold_without_a_build_retry() {
14749        ask_test_home();
14750        let temp = tempfile::tempdir().unwrap();
14751        let mut runner = runner_at(RunStatus::Gating);
14752        let shell = vec!["sh".to_owned(), "-c".to_owned()];
14753        let commands = vec![
14754            "printf '%s\\n' 'incremental cache admission blocked: budget exhausted' 'error: could not compile fixture'; exit 101".to_owned(),
14755            "touch must-not-run".to_owned(),
14756        ];
14757        let (outcomes, retried, pids) = run_e2e_with_retry(
14758            &mut runner.state,
14759            &shell,
14760            &commands,
14761            temp.path(),
14762            Duration::from_secs(5),
14763            "fixture",
14764            None,
14765        )
14766        .await;
14767        assert_eq!(outcomes.len(), 1);
14768        assert!(outcomes[0].resource_blocked);
14769        assert!(!outcomes[0].build_failed());
14770        assert!(!retried);
14771        assert!(pids.is_empty());
14772        assert!(!temp.path().join("must-not-run").exists());
14773        assert_eq!(
14774            runner.state.resource_block.as_ref().unwrap().kind,
14775            "incremental cache admission"
14776        );
14777    }
14778
14779    #[test]
14780    fn verify_is_inconclusive_only_when_a_resource_blocked_outcome_is_present() {
14781        assert!(!verify_inconclusive(&[outcome(Some(0), false)]));
14782        assert!(
14783            !verify_inconclusive(&[outcome(Some(1), false)]),
14784            "an ordinary failure is still evidence about the patch"
14785        );
14786        assert!(verify_inconclusive(&[outcome(None, true)]));
14787        assert!(
14788            verify_inconclusive(&[outcome(Some(0), false), outcome(None, true)]),
14789            "one inconclusive outcome taints the whole batch"
14790        );
14791        assert!(!verify_inconclusive(&[]));
14792    }
14793
14794    #[tokio::test]
14795    async fn timed_out_pid_waiting_returns_as_soon_as_every_pid_is_confirmed_dead() {
14796        // Alive for the first two checks, then dead - confirms the loop
14797        // actually re-polls rather than deciding once and sleeping out the
14798        // ceiling regardless.
14799        let calls = std::sync::atomic::AtomicUsize::new(0);
14800        let started = Instant::now();
14801        wait_for_pids_with(
14802            &[123],
14803            |_| calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 2,
14804            Duration::from_millis(5),
14805            Duration::from_secs(5),
14806        )
14807        .await;
14808        assert!(
14809            calls.load(std::sync::atomic::Ordering::SeqCst) >= 3,
14810            "must keep checking rather than deciding on the first answer"
14811        );
14812        assert!(
14813            started.elapsed() < Duration::from_secs(1),
14814            "must return the moment it is confirmed dead, not wait out the ceiling"
14815        );
14816    }
14817
14818    #[tokio::test]
14819    async fn timed_out_pid_waiting_gives_up_at_its_ceiling_if_never_confirmed_dead() {
14820        let started = Instant::now();
14821        wait_for_pids_with(
14822            &[123],
14823            |_| true, // never reports dead
14824            Duration::from_millis(5),
14825            Duration::from_millis(30),
14826        )
14827        .await;
14828        let elapsed = started.elapsed();
14829        assert!(
14830            elapsed >= Duration::from_millis(30),
14831            "must not give up before its own ceiling: {elapsed:?}"
14832        );
14833        assert!(
14834            elapsed < Duration::from_secs(1),
14835            "must not wait past its own ceiling either: {elapsed:?}"
14836        );
14837    }
14838
14839    #[tokio::test]
14840    async fn timed_out_pid_waiting_is_a_no_op_when_nothing_was_still_running() {
14841        let started = Instant::now();
14842        wait_for_pids_with(
14843            &[],
14844            |_| true,
14845            Duration::from_secs(5),
14846            Duration::from_secs(5),
14847        )
14848        .await;
14849        assert!(
14850            started.elapsed() < Duration::from_millis(200),
14851            "an empty pid list has nothing to confirm"
14852        );
14853    }
14854
14855    // `review_conclusion` is the exact decision the review hand-off task
14856    // fixed: a round budget spent (or a tree that stopped moving) must not
14857    // collapse into `Blocked` regardless of what verification actually
14858    // said. Deterministic and process-free for the same reason the
14859    // `round_is_clean` family above is.
14860    fn review_round(
14861        clean: bool,
14862        blocking: usize,
14863        answered: usize,
14864        expected: usize,
14865        progressed: bool,
14866        e2e_ok: bool,
14867    ) -> ReviewRound {
14868        ReviewRound {
14869            round: 1,
14870            head: "h".to_owned(),
14871            verified_head: None,
14872            verified_at: None,
14873            reviews: Vec::new(),
14874            e2e: vec![CommandOutcome {
14875                command: "test".to_owned(),
14876                code: Some(if e2e_ok { 0 } else { 1 }),
14877                output_tail: String::new(),
14878                duration_ms: 0,
14879                resource_blocked: false,
14880            }],
14881            verify_retried: false,
14882            e2e_deferred: false,
14883            e2e_defer_reason: None,
14884            fix: None,
14885            blocking,
14886            answered,
14887            expected,
14888            clean,
14889            progressed,
14890            vote_split: false,
14891            reconsideration: Vec::new(),
14892            verdict: None,
14893        }
14894    }
14895
14896    #[test]
14897    fn review_conclusion_is_none_when_nothing_has_run() {
14898        assert_eq!(review_conclusion(&[], 3), None);
14899    }
14900
14901    #[test]
14902    fn review_conclusion_is_none_while_rounds_remain() {
14903        let rounds = vec![review_round(false, 1, 2, 2, true, true)];
14904        assert_eq!(review_conclusion(&rounds, 3), None);
14905    }
14906
14907    #[test]
14908    fn review_conclusion_is_gating_once_a_round_is_clean() {
14909        let rounds = vec![review_round(true, 0, 2, 2, false, true)];
14910        assert_eq!(review_conclusion(&rounds, 3), Some(RunStatus::Gating));
14911    }
14912
14913    #[test]
14914    fn review_conclusion_hands_off_when_the_budget_is_spent_and_e2e_is_green() {
14915        let rounds = vec![
14916            review_round(false, 1, 2, 2, true, true),
14917            review_round(false, 1, 2, 2, true, true),
14918        ];
14919        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Gating));
14920    }
14921
14922    #[test]
14923    fn review_conclusion_blocks_when_the_budget_is_spent_and_e2e_is_red() {
14924        let rounds = vec![
14925            review_round(false, 1, 2, 2, true, true),
14926            review_round(false, 1, 2, 2, true, false),
14927        ];
14928        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Blocked));
14929    }
14930
14931    #[test]
14932    fn review_conclusion_stays_none_when_the_budget_is_spent_but_the_last_round_could_not_run() {
14933        // Magi never got a command to run against this round's own head — a
14934        // resource-blocked attempt, not a red one — so this must never
14935        // settle on `Blocked` the way a genuine e2e failure would. `None`
14936        // here is what tells `Runner::review_loop` to retry the check
14937        // itself rather than trust this cheap recomputation with a verdict
14938        // it cannot actually produce.
14939        let mut blocked = review_round(false, 1, 2, 2, true, false);
14940        blocked.e2e[0].resource_blocked = true;
14941        let rounds = vec![review_round(false, 1, 2, 2, true, true), blocked];
14942        assert_eq!(review_conclusion(&rounds, 2), None);
14943    }
14944
14945    #[test]
14946    fn review_conclusion_blocks_an_incomplete_panel_that_raised_nothing_even_with_green_e2e() {
14947        // Missing input, not a verified tree — never a hand-off candidate.
14948        let rounds = vec![review_round(false, 0, 1, 2, false, true)];
14949        assert_eq!(review_conclusion(&rounds, 1), Some(RunStatus::Blocked));
14950    }
14951
14952    #[test]
14953    fn review_conclusion_hands_off_when_the_tree_stagnates_before_the_budget_is_spent() {
14954        let rounds = vec![
14955            review_round(false, 1, 2, 2, false, true),
14956            review_round(false, 1, 2, 2, false, true),
14957        ];
14958        assert_eq!(review_conclusion(&rounds, 10), Some(RunStatus::Gating));
14959    }
14960
14961    fn secs(n: u64) -> Duration {
14962        Duration::from_secs(n)
14963    }
14964
14965    /// A throwaway repo with one commit on `main`, for tests that need `merge`
14966    /// to make real (and, if it runs at all, real*ly fail*) git calls.
14967    #[tokio::test]
14968    async fn selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync() {
14969        const CHILD: &str = "MAGI_SELECTED_PUBLIC_ANCESTRY_TEST";
14970        if std::env::var_os(CHILD).is_none() {
14971            // Other tests reconcile every run in the process-global home,
14972            // briefly taking owner locks. This ancestry test expects an idle
14973            // predecessor, so give it its own process and pinned test home.
14974            let output = std::process::Command::new(std::env::current_exe().unwrap())
14975                .args([
14976                    "--exact",
14977                    "graph::tests::selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync",
14978                    "--nocapture",
14979                ])
14980                .env(CHILD, "1")
14981                .env_remove("MAGI_WORKER_HOME")
14982                .env_remove("MAGI_WORKER_ID")
14983                .output()
14984                .unwrap();
14985            assert!(
14986                output.status.success()
14987                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
14988                "{}\n{}",
14989                String::from_utf8_lossy(&output.stdout),
14990                String::from_utf8_lossy(&output.stderr)
14991            );
14992            return;
14993        }
14994        ask_test_home();
14995        let tmp = tempfile::tempdir().unwrap();
14996        let repo = tmp.path().join("repo");
14997        std::fs::create_dir_all(&repo).unwrap();
14998        init_repo(&repo);
14999        let g = |args: &[&str]| {
15000            let out = std::process::Command::new("git")
15001                .args(args)
15002                .current_dir(&repo)
15003                .quiet()
15004                .output()
15005                .unwrap();
15006            assert!(
15007                out.status.success(),
15008                "{}",
15009                String::from_utf8_lossy(&out.stderr)
15010            );
15011        };
15012        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
15013        g(&["checkout", "-b", "historical"]);
15014        std::fs::write(repo.join("implementation"), "incompatible alternative").unwrap();
15015        g(&["add", "."]);
15016        g(&["commit", "-m", "old alternative"]);
15017        let obsolete = git::rev_parse(&repo, "HEAD").await.unwrap();
15018        g(&["checkout", "-b", "magi/task-selected", &base]);
15019        std::fs::write(repo.join("infrastructure"), "prerequisite").unwrap();
15020        g(&["add", "."]);
15021        g(&["commit", "-m", "measurement infrastructure"]);
15022        let prerequisite = git::rev_parse(&repo, "HEAD").await.unwrap();
15023        std::fs::write(repo.join("implementation"), "measured implementation").unwrap();
15024        g(&["add", "."]);
15025        g(&["commit", "-m", "dependent implementation"]);
15026        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
15027        g(&["checkout", "main"]);
15028        std::fs::write(repo.join("unrelated"), "current main change").unwrap();
15029        g(&["add", "."]);
15030        g(&["commit", "-m", "unrelated base change"]);
15031        let current = git::rev_parse(&repo, "HEAD").await.unwrap();
15032        let origin = tmp.path().join("origin.git");
15033        g(&[
15034            "clone",
15035            "--bare",
15036            repo.to_str().unwrap(),
15037            origin.to_str().unwrap(),
15038        ]);
15039        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
15040        g(&["fetch", "origin"]);
15041        let selection = crate::pr_recovery::Selection {
15042            url: "https://example.test/project/pull/1".into(),
15043            branch: "magi/task-selected".into(),
15044            head: head.clone(),
15045            source_head: None,
15046            source_run: None,
15047            source_proof: None,
15048            disposition: Some(crate::pr_recovery::Disposition::Review),
15049            instruction: "preserve measured behavior".into(),
15050            approved_at: jiff::Timestamp::now(),
15051        };
15052        let mut template = runner_at(RunStatus::Reviewing);
15053        template.state.repo = repo.clone();
15054        template.state.base_commit = current.clone();
15055        template.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
15056        template.state.origin = Some(crate::run::Origin::queue("selected"));
15057        template.state.pr_head = Some(selection.branch.clone());
15058        template.state.pr_recovery = Some(selection.clone());
15059        let mut runner =
15060            Runner::open_selected(&repo, template.state, template.roles, 1, current, selection)
15061                .await
15062                .unwrap();
15063        let wt = runner.state.winner().unwrap().worktree.clone();
15064        assert_eq!(git::rev_parse(&wt, "HEAD").await.unwrap(), head);
15065        assert!(git::is_ancestor(&wt, &prerequisite, "HEAD").await);
15066        assert!(!git::is_ancestor(&wt, &obsolete, "HEAD").await);
15067        assert!(runner.state.seeds.is_empty());
15068        assert_eq!(runner.state.instruction, "preserve measured behavior");
15069        runner.sync_to_base().await.unwrap();
15070        assert_eq!(
15071            std::fs::read_to_string(wt.join("infrastructure")).unwrap(),
15072            "prerequisite"
15073        );
15074        assert_eq!(
15075            std::fs::read_to_string(wt.join("implementation")).unwrap(),
15076            "measured implementation"
15077        );
15078        assert_eq!(
15079            std::fs::read_to_string(wt.join("unrelated")).unwrap(),
15080            "current main change"
15081        );
15082        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
15083        assert_eq!(
15084            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
15085            head
15086        );
15087
15088        // A failed selected-source setup stays inspectable, never resumable as a new competition.
15089        let mut partial = runner_at(RunStatus::Reviewing);
15090        partial.state.repo = repo.clone();
15091        partial.state.config.graph.worktree_root = Some(tmp.path().join("failed-worktrees"));
15092        partial.state.config.worktree.setup = vec![crate::config::SetupStep {
15093            run: Some("exit 1".into()),
15094            ..Default::default()
15095        }];
15096        let selection = runner.state.pr_recovery.clone().unwrap();
15097        partial.state.pr_recovery = Some(selection.clone());
15098        partial.state.pr_head = Some(selection.branch.clone());
15099        partial.state.origin = Some(crate::run::Origin::queue("selected"));
15100        let id = partial.state.id.clone();
15101        let error = match Runner::open_selected(
15102            &repo,
15103            partial.state,
15104            partial.roles,
15105            1,
15106            runner.state.base_commit.clone(),
15107            selection,
15108        )
15109        .await
15110        {
15111            Ok(_) => panic!("setup must fail"),
15112            Err(e) => e,
15113        };
15114        assert_eq!(
15115            error
15116                .downcast_ref::<crate::run::StartupFailure>()
15117                .unwrap()
15118                .run,
15119            id
15120        );
15121        let failed = RunState::load(&id).unwrap();
15122        assert_eq!(failed.status, RunStatus::Failed);
15123        assert_eq!(failed.liveness(false), crate::run::Liveness::Dead);
15124        assert!(Runner::resume(&id).is_err());
15125        runner.state.status = RunStatus::Ready;
15126        runner.state.driver_exited = true;
15127        runner.state.save().unwrap();
15128        let mut retry = runner_at(RunStatus::Reviewing);
15129        retry.state.repo = repo.clone();
15130        retry.state.config.graph.worktree_root = Some(tmp.path().join("retry-worktrees"));
15131        let mut reselected = runner.state.pr_recovery.clone().unwrap();
15132        reselected.approved_at = jiff::Timestamp::now();
15133        retry.state.origin = Some(crate::run::Origin::queue("selected"));
15134        retry.state.pr_head = Some(reselected.branch.clone());
15135        retry.state.pr_recovery = Some(reselected.clone());
15136        crate::pr_head::check_predecessors(&retry.state, &reselected.branch)
15137            .await
15138            .unwrap();
15139        let restarted = Runner::open_selected(
15140            &repo,
15141            retry.state,
15142            retry.roles,
15143            1,
15144            runner.state.base_commit.clone(),
15145            reselected,
15146        )
15147        .await
15148        .unwrap();
15149        assert_eq!(
15150            git::rev_parse(&restarted.state.winner().unwrap().worktree, "HEAD")
15151                .await
15152                .unwrap(),
15153            head
15154        );
15155        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
15156        assert_eq!(
15157            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
15158            head
15159        );
15160    }
15161
15162    #[tokio::test]
15163    #[cfg(unix)]
15164    async fn fallback_and_interrupted_restoration_require_coordination() {
15165        use std::os::fd::AsRawFd as _;
15166        ask_test_home();
15167        let tmp = tempfile::tempdir().unwrap();
15168        let mut runner = registered_runner(tmp.path()).await;
15169        runner.state.config.graph.timeout_resource_wait = 1;
15170        let winner = runner.state.candidates[0].clone();
15171        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
15172        let leftover = winner.worktree.join("leftover");
15173        std::fs::write(&leftover, "untrusted edits").unwrap();
15174        let next = tmp.path().join("next-fixer");
15175        let mut failed = spec("first");
15176        failed.command = vec!["sh".into(), "-c".into(), "exit 1".into()];
15177        let mut successor = spec("second");
15178        successor.command = vec![
15179            "sh".into(),
15180            "-c".into(),
15181            format!("touch '{}'; echo done", next.display()),
15182        ];
15183        let attempts = vec![
15184            (failed.clone(), "first".into()),
15185            (successor.clone(), "second".into()),
15186        ];
15187        let lock_path = runner.state.repo.join(".git/updater.lock");
15188        let external = std::fs::File::create(&lock_path).unwrap();
15189        assert_eq!(
15190            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15191            0
15192        );
15193        let artifacts = tmp.path().join("artifacts");
15194        let build = |spec, seat| SeatJob {
15195            spec,
15196            seat,
15197            cwd: winner.worktree.clone(),
15198            prompt: "fixture".into(),
15199            timeout: Duration::from_secs(10),
15200            allow_write: true,
15201            sessions: false,
15202            artifacts: artifacts.clone(),
15203            stem: "fix".into(),
15204            handover: None,
15205        };
15206        let (_, _, out) = runner
15207            .ask_fixer_among(
15208                attempts.clone(),
15209                "graft",
15210                None,
15211                Some((&winner.worktree, &head)),
15212                build,
15213            )
15214            .await;
15215        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
15216        assert!(leftover.exists(), "contention must prevent clean");
15217        assert!(!next.exists());
15218        assert!(runner.state.handovers.is_empty());
15219        // Early interrupted-repair rollback uses the same protected route.
15220        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
15221            from_run: "earlier".into(),
15222            generation: 1,
15223            mode: crate::recovery::Mode::VerifyRepair,
15224            reasons: Vec::new(),
15225            reviewed_head: None,
15226            rounds: Vec::new(),
15227            open_findings: Vec::new(),
15228            evidence: None,
15229            criteria_inherited: true,
15230            repair: crate::recovery::Repair::Started {
15231                before: head.clone(),
15232            },
15233        });
15234        assert!(
15235            runner
15236                .recovery_repair(&winner)
15237                .await
15238                .unwrap_err()
15239                .is::<crate::repo_lock::ResourceBlocked>()
15240        );
15241        assert!(matches!(
15242            runner.state.recovery.as_ref().unwrap().repair,
15243            crate::recovery::Repair::Started { .. }
15244        ));
15245        assert!(leftover.exists());
15246        drop(external);
15247        runner.recovery_repair(&winner).await.unwrap();
15248        assert!(!leftover.exists());
15249        assert!(matches!(
15250            runner.state.recovery.as_ref().unwrap().repair,
15251            crate::recovery::Repair::Done { .. }
15252        ));
15253        // A hard lock-open failure also leaves HEAD and untracked work intact.
15254        std::fs::remove_file(&lock_path).unwrap();
15255        std::fs::create_dir(&lock_path).unwrap();
15256        std::fs::write(&leftover, "untrusted edits").unwrap();
15257        let (_, _, out) = runner
15258            .ask_fixer_among(
15259                attempts,
15260                "graft",
15261                None,
15262                Some((&winner.worktree, &head)),
15263                build,
15264            )
15265            .await;
15266        assert!(matches!(out, AgentOutcome::Failed(_)));
15267        assert!(leftover.exists());
15268        assert!(!next.exists());
15269        assert_eq!(
15270            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15271            head
15272        );
15273    }
15274
15275    #[cfg(unix)]
15276    async fn registered_runner(root: &Path) -> Runner {
15277        repository_runner(root, crate::config::test_coordination()).await
15278    }
15279
15280    async fn repository_runner(
15281        root: &Path,
15282        coordination: Option<crate::config::Coordination>,
15283    ) -> Runner {
15284        ask_test_home();
15285        let repo = root.join("repo");
15286        std::fs::create_dir_all(&repo).unwrap();
15287        init_repo(&repo);
15288        if coordination.is_some() {
15289            std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
15290        }
15291        let mut runner = runner_at(RunStatus::Prep);
15292        runner.state.repo = repo.clone();
15293        runner.state.config.coordination = coordination;
15294        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
15295        runner.state.config.graph.worktree_root = Some(root.join("wt"));
15296        runner.state.config.graph.advise = false;
15297        runner.roles.implementers = vec![spec("implement")];
15298        runner.roles.judges = vec![spec("judge")];
15299        runner.prep().await.unwrap();
15300        runner
15301    }
15302
15303    const AUTH_OUTAGE: &str = r#"{"is_error":true,"terminal_reason":"api_error","result":"Failed to authenticate: OAuth session expired and could not be refreshed"}"#;
15304
15305    #[tokio::test]
15306    async fn all_unauthenticated_wave_stops_the_node_without_nudges() {
15307        let tmp = tempfile::tempdir().unwrap();
15308        let mut runner = repository_runner(tmp.path(), None).await;
15309        let prompts = runner.state.config.prompts.clone();
15310        let run = runner.state.id.clone();
15311        let ctx = WaveCtx {
15312            carry_seats: false,
15313            pauses: None,
15314            run: &run,
15315            node: "advise",
15316            prompts: &prompts,
15317            cache: None,
15318            round: None,
15319        };
15320        let jobs: Vec<_> = ["alpha", "beta"]
15321            .into_iter()
15322            .map(|id| SeatJob {
15323                spec: scripted(id, AUTH_OUTAGE),
15324                seat: SeatState::new(id, id, 7),
15325                prompt: "propose".into(),
15326                cwd: runner.state.candidates[0].worktree.clone(),
15327                timeout: Duration::from_secs(10),
15328                allow_write: false,
15329                sessions: false,
15330                artifacts: agent::artifacts_dir(&runner.state.dir()),
15331                stem: id.into(),
15332                handover: None,
15333            })
15334            .collect();
15335        let mut losses = Vec::new();
15336        let results = ask_wave_with(
15337            jobs.clone(),
15338            runner.sem.clone(),
15339            2,
15340            &[],
15341            &ctx,
15342            &mut losses,
15343            &mut runner.state,
15344            &|_: &str| Ok(()),
15345        )
15346        .await;
15347        assert!(
15348            results
15349                .iter()
15350                .all(|(seat, result, nudges)| seat.turns == 1 && result.is_err() && *nudges == 0)
15351        );
15352        assert_eq!(runner.state.quota.len(), 2);
15353        assert!(
15354            runner
15355                .state
15356                .quota
15357                .iter()
15358                .all(|q| q.cause == agent::QuotaCause::Authentication && !q.agent.is_empty())
15359        );
15360        assert!(!runner.state.advise_attempted);
15361        runner.stop_for_resource().unwrap();
15362        assert_eq!(runner.state.status, RunStatus::Blocked);
15363        assert_eq!(runner.state.resource_block.as_ref().unwrap().node, "advise");
15364        assert_eq!(
15365            runner.state.resource_block.as_ref().unwrap().kind,
15366            "agent authentication"
15367        );
15368        // A machine loss followed by an ordinary failure is not evidence
15369        // that the whole node was unavailable, and must not earn a refund.
15370        runner.state.resource_block = None;
15371        runner.state.quota.clear();
15372        let mut mixed = jobs;
15373        mixed[1].spec.command = vec!["false".into()];
15374        let results = ask_wave_with(
15375            mixed,
15376            runner.sem.clone(),
15377            0,
15378            &[],
15379            &ctx,
15380            &mut losses,
15381            &mut runner.state,
15382            &|_: &str| Ok(()),
15383        )
15384        .await;
15385        assert!(results.iter().all(|(_, res, _)| res.is_err()));
15386        assert!(runner.state.resource_block.is_none());
15387        assert_eq!(losses.len(), 1);
15388    }
15389
15390    #[tokio::test]
15391    async fn unauthenticated_implementation_keeps_its_candidate_pending() {
15392        let tmp = tempfile::tempdir().unwrap();
15393        let mut runner = repository_runner(tmp.path(), None).await;
15394        let implementer = scripted("implement", AUTH_OUTAGE);
15395        runner.roles.implementers = vec![implementer.clone()];
15396        runner.state.config.agents = vec![implementer];
15397        runner.implement().await.unwrap();
15398        assert_eq!(runner.state.status, RunStatus::Blocked);
15399        assert_eq!(runner.state.quota.len(), 1);
15400        assert_eq!(
15401            runner.state.quota[0].cause,
15402            agent::QuotaCause::Authentication
15403        );
15404        let candidate = &runner.state.candidates[0];
15405        assert!(candidate.failed.is_none() && !candidate.empty && candidate.commits == 0);
15406        assert_eq!(runner.state.seats["impl-A"].turns, 1);
15407    }
15408
15409    #[tokio::test]
15410    #[cfg(unix)]
15411    async fn parked_implementer_persists_completed_work() {
15412        for registered in [false, true] {
15413            let tmp = tempfile::tempdir().unwrap();
15414            let mut runner = registered_runner(tmp.path()).await;
15415            if !registered {
15416                std::fs::remove_file(runner.state.repo.join(".git/updater.contract")).unwrap();
15417            }
15418            let marker = tmp.path().join("started");
15419            let release = tmp.path().join("release");
15420            let mut implementer = spec("implement");
15421            implementer.command = vec![
15422                "sh".into(),
15423                "-c".into(),
15424                format!(
15425                    "touch '{}'; while [ ! -f '{}' ]; do sleep 0.01; done; echo completed > completed; echo saved-result",
15426                    marker.display(),
15427                    release.display()
15428                ),
15429            ];
15430            runner.roles.implementers = vec![implementer.clone()];
15431            runner.state.config.agents = vec![implementer];
15432            let pause = runner.pause.clone();
15433            let (result, ()) = tokio::join!(runner.implement(), async {
15434                tokio::time::timeout(Duration::from_secs(10), async {
15435                    while !marker.exists() {
15436                        tokio::time::sleep(Duration::from_millis(10)).await;
15437                    }
15438                })
15439                .await
15440                .unwrap();
15441                pause.park();
15442                std::fs::write(&release, "go").unwrap();
15443            });
15444            result.unwrap();
15445            let candidate = &runner.state.candidates[0];
15446            assert!(candidate.commits > 0, "{candidate:?}");
15447            assert!(candidate.summary.contains("saved-result"));
15448            assert_eq!(candidate.files, 1);
15449            let before = candidate.commits;
15450            runner.implement().await.unwrap();
15451            assert_eq!(runner.state.candidates[0].commits, before);
15452        }
15453    }
15454
15455    #[tokio::test]
15456    #[cfg(unix)]
15457    async fn resource_blocked_recovery_retries_the_unstarted_fixer() {
15458        let tmp = tempfile::tempdir().unwrap();
15459        let mut runner = registered_runner(tmp.path()).await;
15460        let winner = runner.state.candidates[0].clone();
15461        let cache = tmp.path().join("cache");
15462        runner.state.config.verify.e2e = vec![format!("CARGO_TARGET_DIR={} true", cache.display())];
15463        runner.state.config.graph.timeout_resource_wait = 0;
15464        let owner = crate::cache::Owner::here("other", "e2e", "e2e", &cache, "abc");
15465        let crate::cache::AcquireOutcome::Acquired(held) =
15466            crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap()
15467        else {
15468            panic!("cache must be free")
15469        };
15470        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
15471            from_run: "earlier".into(),
15472            generation: 1,
15473            mode: crate::recovery::Mode::VerifyRepair,
15474            reasons: Vec::new(),
15475            reviewed_head: None,
15476            rounds: Vec::new(),
15477            open_findings: Vec::new(),
15478            evidence: None,
15479            criteria_inherited: true,
15480            repair: crate::recovery::Repair::NotStarted,
15481        });
15482        runner.recovery_repair(&winner).await.unwrap();
15483        assert!(matches!(
15484            runner.state.recovery.as_ref().unwrap().repair,
15485            crate::recovery::Repair::WaitingForRestore { .. }
15486        ));
15487        drop(held);
15488        runner.state.resource_block = None;
15489        runner.state.config.graph.timeout_resource_wait = 1;
15490        runner.recovery_repair(&winner).await.unwrap();
15491        assert!(matches!(
15492            runner.state.recovery.as_ref().unwrap().repair,
15493            crate::recovery::Repair::Done { .. }
15494        ));
15495        assert!(runner.state.seats.values().any(|seat| seat.turns > 0));
15496    }
15497
15498    #[tokio::test]
15499    #[cfg(unix)]
15500    async fn repository_blocked_graft_and_recovery_retry_after_deferred_restore() {
15501        use std::os::fd::AsRawFd as _;
15502        for graft in [false, true] {
15503            let tmp = tempfile::tempdir().unwrap();
15504            let mut runner = registered_runner(tmp.path()).await;
15505            runner.state.config.graph.timeout_resource_wait = 1;
15506            let winner = runner.state.candidates[0].clone();
15507            let marker = tmp.path().join("fixer-started");
15508            let mut fixer = spec("fixer");
15509            fixer.command = vec![
15510                "sh".into(),
15511                "-c".into(),
15512                format!("echo started >> '{}'; echo done", marker.display()),
15513            ];
15514            runner.roles.fixer = Some(vec![fixer]);
15515            if graft {
15516                let mut loser = winner.clone();
15517                loser.label = 'B';
15518                loser.index = 1;
15519                runner.state.candidates.push(loser);
15520                runner.state.config.graph.graft_runner_up = true;
15521                runner.state.tally = Some(Tally {
15522                    first_choice: BTreeMap::new(),
15523                    borda: BTreeMap::new(),
15524                    winner: winner.label,
15525                    rankings: 1,
15526                    unanimous_initial: true,
15527                    deliberated: false,
15528                    changed_votes: 0,
15529                    unanimous_final: true,
15530                    tie_break: None,
15531                    judges: 1,
15532                    present: 1,
15533                    quorum: 1,
15534                    met_quorum: true,
15535                    uncontested: None,
15536                });
15537                runner.state.judgements.push(crate::run::Judgement {
15538                    judge: 1,
15539                    seat: "judge-1".into(),
15540                    agent: "judge".into(),
15541                    ranking: vec![winner.label, 'B'],
15542                    reasons: BTreeMap::new(),
15543                    confidence: None,
15544                    strengths: BTreeMap::from([("B".into(), vec!["handles empty input".into()])]),
15545                    order: vec![0, 1],
15546                    failed: None,
15547                    duration_ms: 0,
15548                });
15549            } else {
15550                runner.state.recovery = Some(crate::recovery::RecoveryRecord {
15551                    from_run: "earlier".into(),
15552                    generation: 1,
15553                    mode: crate::recovery::Mode::VerifyRepair,
15554                    reasons: Vec::new(),
15555                    reviewed_head: None,
15556                    rounds: Vec::new(),
15557                    open_findings: Vec::new(),
15558                    evidence: None,
15559                    criteria_inherited: true,
15560                    repair: crate::recovery::Repair::NotStarted,
15561                });
15562            }
15563            let reader = crate::repo_lock::SeatLease::for_checkout(
15564                &winner.worktree,
15565                false,
15566                crate::config::test_coordination().as_ref(),
15567            )
15568            .await
15569            .unwrap();
15570            let pause = runner.pause.clone();
15571            let (result, ()) = tokio::join!(
15572                async {
15573                    if graft {
15574                        runner.graft().await
15575                    } else {
15576                        runner.recovery_repair(&winner).await
15577                    }
15578                },
15579                async {
15580                    tokio::time::sleep(Duration::from_millis(100)).await;
15581                    pause.park();
15582                }
15583            );
15584            result.unwrap();
15585            assert!(!marker.exists(), "a blocked seat must not spawn");
15586            // Exercise the persisted state, as a binary replacement/resume does.
15587            runner.state = RunState::load(&runner.state.id).unwrap();
15588            if graft {
15589                assert_eq!(
15590                    runner.state.graft.as_ref().unwrap().outcome,
15591                    GraftOutcome::WaitingForRestore
15592                );
15593            } else {
15594                assert!(matches!(
15595                    runner.state.recovery.as_ref().unwrap().repair,
15596                    crate::recovery::Repair::WaitingForRestore { .. }
15597                ));
15598            }
15599            drop(reader);
15600            runner.pause = Pause::new();
15601            runner.state.resource_block = None;
15602            // Deferred restoration must still respect an external lock owner.
15603            let external =
15604                std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
15605            assert_eq!(
15606                unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15607                0
15608            );
15609            let leftover = winner.worktree.join("leftover");
15610            std::fs::write(&leftover, "earlier fallback edits").unwrap();
15611            let result = if graft {
15612                runner.graft().await
15613            } else {
15614                runner.recovery_repair(&winner).await
15615            };
15616            assert!(
15617                result
15618                    .unwrap_err()
15619                    .is::<crate::repo_lock::ResourceBlocked>()
15620            );
15621            assert!(leftover.exists());
15622            assert!(!marker.exists());
15623            drop(external);
15624            runner.state.resource_block = None;
15625            let result = if graft {
15626                runner.graft().await
15627            } else {
15628                runner.recovery_repair(&winner).await
15629            };
15630            result.unwrap();
15631            assert!(!leftover.exists(), "restore must precede retry");
15632            assert_eq!(std::fs::read_to_string(&marker).unwrap(), "started\n");
15633            if graft {
15634                assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
15635            } else {
15636                assert!(matches!(
15637                    runner.state.recovery.as_ref().unwrap().repair,
15638                    crate::recovery::Repair::Done { .. }
15639                ));
15640            }
15641        }
15642    }
15643
15644    #[tokio::test]
15645    #[cfg(unix)]
15646    async fn interrupted_graft_restore_waits_and_preserves_its_record() {
15647        use std::os::fd::AsRawFd as _;
15648        let tmp = tempfile::tempdir().unwrap();
15649        let mut runner = registered_runner(tmp.path()).await;
15650        runner.state.config.graph.timeout_resource_wait = 1;
15651        let winner = runner.state.candidates[0].clone();
15652        let pre = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
15653        runner.state.tally = Some(Tally {
15654            first_choice: BTreeMap::new(),
15655            borda: BTreeMap::new(),
15656            winner: winner.label,
15657            rankings: 0,
15658            unanimous_initial: false,
15659            deliberated: false,
15660            changed_votes: 0,
15661            unanimous_final: false,
15662            tie_break: None,
15663            judges: 0,
15664            present: 0,
15665            quorum: 0,
15666            met_quorum: true,
15667            uncontested: Some("fixture".into()),
15668        });
15669        runner.state.graft = Some(GraftRecord {
15670            pre: pre.clone(),
15671            post: None,
15672            lines: None,
15673            limit: None,
15674            agent: None,
15675            outcome: GraftOutcome::Running,
15676            requested: Vec::new(),
15677            adoption: None,
15678            adoption_error: None,
15679        });
15680        std::fs::write(winner.worktree.join("README.md"), "unfinished graft\n").unwrap();
15681        git::commit_all(&winner.worktree, "unfinished graft")
15682            .await
15683            .unwrap();
15684        let unfinished = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
15685        let leftover = winner.worktree.join("leftover");
15686        std::fs::write(&leftover, "untrusted edits").unwrap();
15687        let path = runner.state.repo.join(".git/updater.lock");
15688        let external = std::fs::File::create(&path).unwrap();
15689        assert_eq!(
15690            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15691            0
15692        );
15693        assert!(
15694            runner
15695                .graft()
15696                .await
15697                .unwrap_err()
15698                .is::<crate::repo_lock::ResourceBlocked>()
15699        );
15700        assert!(matches!(
15701            runner.state.graft.as_ref().unwrap().outcome,
15702            GraftOutcome::Running
15703        ));
15704        assert_eq!(
15705            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15706            unfinished
15707        );
15708        assert!(leftover.exists());
15709        drop(external);
15710        std::fs::remove_file(&path).unwrap();
15711        std::fs::create_dir(&path).unwrap();
15712        assert!(runner.graft().await.is_err());
15713        assert!(matches!(
15714            runner.state.graft.as_ref().unwrap().outcome,
15715            GraftOutcome::Running
15716        ));
15717        assert_eq!(
15718            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15719            unfinished
15720        );
15721        assert!(leftover.exists());
15722        std::fs::remove_dir(&path).unwrap();
15723        runner.graft().await.unwrap();
15724        assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
15725        assert_eq!(git::rev_parse(&winner.worktree, "HEAD").await.unwrap(), pre);
15726        assert!(!leftover.exists());
15727    }
15728
15729    #[tokio::test]
15730    #[cfg(unix)]
15731    async fn repository_contention_blocks_and_parks_without_poisoning_preparation() {
15732        use std::os::fd::AsRawFd as _;
15733        let tmp = tempfile::tempdir().unwrap();
15734        let mut runner = registered_runner(tmp.path()).await;
15735        runner.state.prep_complete = Some(false);
15736        runner.state.config.graph.timeout_resource_wait = 1;
15737        runner.state.save().unwrap();
15738        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
15739        assert_eq!(
15740            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15741            0
15742        );
15743        runner.execute().await.unwrap();
15744        let disk = RunState::load(&runner.state.id).unwrap();
15745        assert!(disk.driver_exited);
15746        assert_eq!(disk.driver_pid, None);
15747        assert_eq!(runner.state.status, RunStatus::Blocked);
15748        assert_eq!(
15749            runner.state.resource_block.as_ref().unwrap().kind,
15750            "repository coordination"
15751        );
15752        assert!(runner.state.prep_failure.is_none());
15753        assert!(runner.state.seats.is_empty());
15754        runner.pause.park();
15755        // Include headroom for Git subprocesses under parallel test load;
15756        // the repository contention deadline itself remains one second.
15757        tokio::time::timeout(Duration::from_secs(10), runner.execute())
15758            .await
15759            .unwrap()
15760            .unwrap();
15761        assert!(runner.state.parked);
15762        assert!(runner.state.prep_failure.is_none());
15763        let disk = RunState::load(&runner.state.id).unwrap();
15764        assert!(disk.driver_exited);
15765        assert_eq!(disk.driver_pid, None);
15766    }
15767
15768    #[tokio::test]
15769    #[cfg(unix)]
15770    async fn dropping_execute_during_a_repository_wait_releases_the_driver() {
15771        use std::os::fd::AsRawFd as _;
15772        let tmp = tempfile::tempdir().unwrap();
15773        let mut runner = registered_runner(tmp.path()).await;
15774        runner.state.prep_complete = Some(false);
15775        runner.state.config.graph.timeout_resource_wait = 30;
15776        runner.state.save().unwrap();
15777        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
15778        assert_eq!(
15779            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15780            0
15781        );
15782        assert!(
15783            tokio::time::timeout(Duration::from_millis(100), runner.execute())
15784                .await
15785                .is_err()
15786        );
15787        let disk = RunState::load(&runner.state.id).unwrap();
15788        assert!(disk.driver_exited);
15789        assert_eq!(disk.driver_pid, None);
15790        assert!(disk.status.resumable());
15791        assert!(runner.state.driver_exited);
15792        assert_eq!(runner.state.driver_pid, None);
15793        runner.state.save().unwrap();
15794        assert_eq!(RunState::load(&runner.state.id).unwrap().driver_pid, None);
15795    }
15796
15797    #[tokio::test]
15798    #[cfg(unix)]
15799    async fn gate_takes_cache_before_repository_so_an_editing_wave_can_finish() {
15800        let tmp = tempfile::tempdir().unwrap();
15801        let mut runner = registered_runner(tmp.path()).await;
15802        let winner = runner.state.candidates[0].clone();
15803        let cache = tmp.path().join("cache");
15804        let started = tmp.path().join("pre-gate-started");
15805        runner.state.config.verify.pre_gate = vec![format!("touch '{}'", started.display())];
15806        runner.state.config.verify.gate =
15807            vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
15808        let home = crate::run::home();
15809        let owner =
15810            crate::cache::Owner::here("editing-wave", "implement", "*", &winner.worktree, "HEAD");
15811        let guard = match crate::cache::try_acquire(&home, &cache, &owner).unwrap() {
15812            crate::cache::AcquireOutcome::Acquired(g) => g,
15813            crate::cache::AcquireOutcome::Busy(busy) => panic!("cache must be free: {busy:?}"),
15814        };
15815        let mut gate = Box::pin(runner.run_gate(&winner));
15816        assert!(
15817            tokio::time::timeout(Duration::from_millis(150), &mut gate)
15818                .await
15819                .is_err()
15820        );
15821        assert!(!started.exists(), "pre-gate must wait for the cache too");
15822        // Simulate the wave that already owns the cache entering invoke.
15823        // It must obtain the editor reservation and finish without waiting
15824        // for the gate that is queued behind its cache.
15825        let wait = crate::repo_lock::WaitPolicy::new(Duration::from_millis(200), || false);
15826        let editor = crate::repo_lock::SeatLease::checkout_with(
15827            &winner.worktree,
15828            true,
15829            crate::config::test_coordination().as_ref(),
15830            &wait,
15831        )
15832        .await
15833        .unwrap();
15834        drop(editor);
15835        guard.release();
15836        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
15837            .await
15838            .unwrap()
15839            .unwrap();
15840        drop(gate);
15841        assert!(outcomes.iter().all(CommandOutcome::ok));
15842        assert!(started.exists());
15843    }
15844
15845    #[tokio::test]
15846    #[cfg(unix)]
15847    async fn post_seat_rescue_and_gate_wait_for_shared_lock() {
15848        use std::os::fd::AsRawFd as _;
15849
15850        ask_test_home();
15851        let tmp = tempfile::tempdir().unwrap();
15852        let repo = tmp.path().join("repo");
15853        std::fs::create_dir_all(&repo).unwrap();
15854        init_repo(&repo);
15855        let common = repo.join(".git");
15856        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
15857        let mut runner = runner_at(RunStatus::Prep);
15858        runner.state.repo = repo.clone();
15859        runner.state.config.coordination = crate::config::test_coordination();
15860        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
15861        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
15862        runner.state.config.graph.advise = false;
15863        runner.roles.implementers = vec![spec("implement")];
15864        runner.roles.judges = vec![spec("judge")];
15865        runner.prep().await.unwrap();
15866        let winner = runner.state.candidates[0].clone();
15867        // Emulate edits already left by a completed seat. The fixture CLI
15868        // only reports completion; it performs no repository operations.
15869        std::fs::write(winner.worktree.join("leftover"), "seat work\n").unwrap();
15870        let completed = tmp.path().join("seat-completed");
15871        runner.roles.implementers[0].command = vec![
15872            "sh".into(),
15873            "-c".into(),
15874            format!("touch '{}'; echo completed", completed.display()),
15875        ];
15876        let outsider = std::fs::File::create(common.join("updater.lock")).unwrap();
15877        assert_eq!(
15878            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15879            0
15880        );
15881        let before = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
15882        let mut implement = Box::pin(runner.implement());
15883        tokio::select! {
15884            result = &mut implement => panic!("rescue must wait: {result:?}"),
15885            result = tokio::time::timeout(Duration::from_secs(10), async {
15886                while !completed.exists() {
15887                    tokio::time::sleep(Duration::from_millis(20)).await;
15888                }
15889            }) => result.unwrap(),
15890        }
15891        assert!(
15892            tokio::time::timeout(Duration::from_millis(200), &mut implement)
15893                .await
15894                .is_err()
15895        );
15896        assert_eq!(
15897            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15898            before
15899        );
15900        assert_eq!(
15901            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
15902            0
15903        );
15904        tokio::time::timeout(Duration::from_secs(10), &mut implement)
15905            .await
15906            .unwrap()
15907            .unwrap();
15908        drop(implement);
15909        assert_ne!(
15910            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15911            before
15912        );
15913        assert!(git::is_clean(&winner.worktree).await.unwrap());
15914
15915        let started = tmp.path().join("pre-gate-started");
15916        let proceed = tmp.path().join("pre-gate-proceed");
15917        let checked = tmp.path().join("gate-ran");
15918        runner.state.config.verify.pre_gate = vec![format!(
15919            "echo mechanical >> README.md; touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
15920            started.display(),
15921            proceed.display()
15922        )];
15923        runner.state.config.verify.gate = vec![format!("touch '{}'", checked.display())];
15924        assert_eq!(
15925            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15926            0
15927        );
15928        let mut gate = Box::pin(runner.run_gate(&winner));
15929        assert!(
15930            tokio::time::timeout(Duration::from_millis(200), &mut gate)
15931                .await
15932                .is_err()
15933        );
15934        assert!(!started.exists());
15935        assert!(!checked.exists());
15936        assert!(git::is_clean(&winner.worktree).await.unwrap());
15937        assert_eq!(
15938            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
15939            0
15940        );
15941        tokio::select! {
15942            result = &mut gate => panic!("pre-gate must wait for signal: {result:?}"),
15943            result = tokio::time::timeout(Duration::from_secs(10), async {
15944                while !started.exists() {
15945                    tokio::time::sleep(Duration::from_millis(20)).await;
15946                }
15947            }) => result.unwrap(),
15948        }
15949        assert_eq!(
15950            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15951            -1,
15952            "mechanical edits must hold the real lock"
15953        );
15954        std::fs::write(proceed, "ready").unwrap();
15955        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
15956            .await
15957            .unwrap()
15958            .unwrap();
15959        drop(gate);
15960        assert!(outcomes.iter().all(CommandOutcome::ok));
15961        assert!(checked.exists());
15962        assert!(runner.state.pre_gate_commit.is_some());
15963        assert!(git::is_clean(&winner.worktree).await.unwrap());
15964        assert_eq!(
15965            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15966            0,
15967            "gate completion must release coordination"
15968        );
15969        drop(outsider);
15970        std::fs::remove_file(common.join("updater.lock")).unwrap();
15971        std::fs::create_dir(common.join("updater.lock")).unwrap();
15972        std::fs::remove_file(&started).unwrap();
15973        std::fs::remove_file(&checked).unwrap();
15974        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
15975        let error = runner.run_gate(&winner).await.unwrap_err();
15976        assert!(
15977            error
15978                .to_string()
15979                .contains("acquire mandatory repository lock")
15980        );
15981        assert!(
15982            !started.exists(),
15983            "failed acquisition must prevent pre-gate"
15984        );
15985        assert!(!checked.exists(), "failed acquisition must prevent gate");
15986        assert!(git::is_clean(&winner.worktree).await.unwrap());
15987        assert_eq!(
15988            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15989            head
15990        );
15991    }
15992
15993    #[tokio::test]
15994    #[cfg(unix)]
15995    async fn preparation_waits_for_shared_lock_before_checkout_and_holds_it_through_setup() {
15996        use std::os::fd::AsRawFd as _;
15997        use std::time::Duration;
15998
15999        ask_test_home();
16000        let tmp = tempfile::tempdir().unwrap();
16001        let repo = tmp.path().join("repo");
16002        std::fs::create_dir_all(&repo).unwrap();
16003        init_repo(&repo);
16004        let common = repo.join(".git");
16005        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
16006        let lock = std::fs::File::create(common.join("updater.lock")).unwrap();
16007        assert_eq!(
16008            unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16009            0
16010        );
16011        let mut runner = runner_at(RunStatus::Prep);
16012        runner.state.repo = repo.clone();
16013        runner.state.config.coordination = crate::config::test_coordination();
16014        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16015        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16016        runner.state.config.graph.advise = true;
16017        runner.state.config.graph.advisors = 1;
16018        runner.roles.implementers = vec![spec("implement")];
16019        runner.roles.judges = vec![spec("judge")];
16020        let root = runner.state.worktree_root();
16021        let started = tmp.path().join("setup-started");
16022        let proceed = tmp.path().join("setup-proceed");
16023        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
16024            run: Some(format!(
16025                "touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
16026                started.display(),
16027                proceed.display()
16028            )),
16029            ..Default::default()
16030        }];
16031        let branches = git::git(&repo, &["branch", "--list"]).await.unwrap();
16032        let config = git::git(&repo, &["config", "--local", "--list"])
16033            .await
16034            .unwrap();
16035        let mut prep = Box::pin(runner.prep());
16036        assert!(
16037            tokio::time::timeout(Duration::from_millis(200), &mut prep)
16038                .await
16039                .is_err()
16040        );
16041        assert!(
16042            !root.exists(),
16043            "contention must prevent even checkout creation"
16044        );
16045        assert!(!started.exists(), "contention must prevent setup");
16046        assert_eq!(
16047            git::git(&repo, &["branch", "--list"]).await.unwrap(),
16048            branches
16049        );
16050        assert_eq!(
16051            git::git(&repo, &["config", "--local", "--list"])
16052                .await
16053                .unwrap(),
16054            config
16055        );
16056        drop(lock);
16057        tokio::select! {
16058            result = &mut prep => panic!("setup must wait for its signal: {result:?}"),
16059            result = tokio::time::timeout(Duration::from_secs(10), async {
16060                while !started.exists() {
16061                    tokio::time::sleep(Duration::from_millis(20)).await;
16062                }
16063            }) => result.unwrap(),
16064        }
16065        let outsider = std::fs::File::open(common.join("updater.lock")).unwrap();
16066        assert_eq!(
16067            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16068            -1
16069        );
16070        assert!(
16071            tokio::time::timeout(
16072                Duration::from_millis(100),
16073                crate::repo_lock::SeatLease::for_checkout(
16074                    &repo,
16075                    true,
16076                    crate::config::test_coordination().as_ref()
16077                )
16078            )
16079            .await
16080            .is_err(),
16081            "preparation must also exclude local editors"
16082        );
16083        std::fs::write(proceed, "ready").unwrap();
16084        tokio::time::timeout(Duration::from_secs(10), &mut prep)
16085            .await
16086            .unwrap()
16087            .unwrap();
16088        drop(prep);
16089        assert_eq!(runner.state.prep_complete, Some(true));
16090        assert!(root.join("judge-1").exists());
16091        assert!(root.join("advisor-1").exists());
16092        assert_eq!(
16093            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16094            0
16095        );
16096    }
16097
16098    #[tokio::test]
16099    #[cfg(unix)]
16100    async fn preparation_lock_failure_prevents_repository_changes() {
16101        ask_test_home();
16102        let tmp = tempfile::tempdir().unwrap();
16103        let repo = tmp.path().join("repo");
16104        std::fs::create_dir_all(&repo).unwrap();
16105        init_repo(&repo);
16106        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
16107        // A directory at the required lock path makes opening the real lock
16108        // fail, rather than merely exercising an invalid registration.
16109        std::fs::create_dir(repo.join(".git/updater.lock")).unwrap();
16110        let mut runner = runner_at(RunStatus::Prep);
16111        runner.state.repo = repo.clone();
16112        runner.state.config.coordination = crate::config::test_coordination();
16113        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16114        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16115        runner.roles.implementers = vec![spec("implement")];
16116        let error = runner.prep().await.unwrap_err();
16117        assert!(
16118            error
16119                .to_string()
16120                .contains("acquire mandatory repository lock")
16121        );
16122        assert!(!runner.state.worktree_root().exists());
16123        assert!(runner.state.candidates.is_empty());
16124        assert!(!repo.join(".git/config.worktree").exists());
16125        assert_eq!(
16126            git::git(&repo, &["branch", "--list"]).await.unwrap().trim(),
16127            "* main"
16128        );
16129    }
16130
16131    #[tokio::test]
16132    async fn preparation_records_creation_intent_before_git_can_fail() {
16133        ask_test_home();
16134        let tmp = tempfile::tempdir().unwrap();
16135        let repo = tmp.path().join("repo");
16136        std::fs::create_dir_all(&repo).unwrap();
16137        init_repo(&repo);
16138        let mut runner = runner_at(RunStatus::Prep);
16139        runner.state.repo = repo.clone();
16140        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16141        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16142        runner.state.config.blind.commit_msg_hook = false;
16143        runner.roles.implementers = vec![spec("one")];
16144        let label = blind::assign_labels(1, runner.state.seed)[0];
16145        let branch = runner.state.branch_for(label);
16146        // A conflicting branch makes Git refuse creation before a candidate
16147        // can be registered. The durable intent must still identify it.
16148        git::git(&repo, &["branch", &branch]).await.unwrap();
16149        assert!(runner.prep().await.is_err());
16150        let saved = RunState::load(&runner.state.id).unwrap();
16151        assert!(saved.candidates.is_empty());
16152        let event = saved
16153            .events
16154            .iter()
16155            .find(|e| e.node == "prep-intent")
16156            .unwrap();
16157        let intent: serde_json::Value = serde_json::from_str(&event.message).unwrap();
16158        assert_eq!(intent["branch"], branch);
16159        assert_eq!(intent["start"], runner.state.base_commit);
16160        assert_eq!(
16161            intent["worktree"],
16162            runner
16163                .state
16164                .worktree_root()
16165                .join(format!("cand-{label}"))
16166                .to_string_lossy()
16167                .as_ref()
16168        );
16169        assert_eq!(intent["picks"], serde_json::json!([]));
16170    }
16171
16172    #[tokio::test]
16173    async fn invalid_pinned_sources_create_no_partial_worktrees() {
16174        ask_test_home();
16175        let tmp = tempfile::tempdir().unwrap();
16176        let repo = tmp.path().join("repo");
16177        std::fs::create_dir_all(&repo).unwrap();
16178        init_repo(&repo);
16179        let mut runner = runner_at(RunStatus::Prep);
16180        runner.state.repo = repo.clone();
16181        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16182        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
16183        runner.state.sources.pick_commits.push(refs::Input {
16184            token: "missing".into(),
16185            sha: "0".repeat(40),
16186            provenance: refs::Provenance::ExplicitCli,
16187        });
16188        assert!(runner.prep().await.is_err());
16189        assert!(runner.state.candidates.is_empty());
16190        assert!(!runner.state.worktree_root().exists());
16191    }
16192
16193    #[tokio::test]
16194    async fn prose_and_legacy_inference_never_import_into_candidates() {
16195        ask_test_home();
16196        let tmp = tempfile::tempdir().unwrap();
16197        let repo = tmp.path().join("repo");
16198        std::fs::create_dir_all(&repo).unwrap();
16199        init_repo(&repo);
16200        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
16201        git::git(&repo, &["checkout", "-b", "magi/history/A"])
16202            .await
16203            .unwrap();
16204        std::fs::write(repo.join("unwanted"), "do not import").unwrap();
16205        git::git(&repo, &["add", "."]).await.unwrap();
16206        git::git(&repo, &["commit", "-m", "historical implementation"])
16207            .await
16208            .unwrap();
16209        let source = git::rev_parse(&repo, "HEAD").await.unwrap();
16210        git::git(&repo, &["checkout", "main"]).await.unwrap();
16211        for instruction in [
16212            format!("Example: magi/history/A at {source}"),
16213            format!("Quoted failure: cannot apply referenced commit {source} from magi/history/A"),
16214            format!("Never import magi/history/A or {source}"),
16215            format!("Conversation answer: I mentioned {source} only as background"),
16216        ] {
16217            let mut runner = runner_at(RunStatus::Prep);
16218            runner.state.repo = repo.clone();
16219            runner.state.base_commit = base.clone();
16220            runner.state.instruction = instruction.clone();
16221            runner.state.config.graph.worktree_root = Some(tmp.path().join(&runner.state.id));
16222            runner.state.config.blind.commit_msg_hook = false;
16223            runner.state.seeds = vec![refs::Seed {
16224                token: "magi/history/A".into(),
16225                sha: source.clone(),
16226                kind: refs::SeedKind::Unmerged,
16227                branch: true,
16228                detail: String::new(),
16229            }];
16230            runner.roles.implementers = vec![spec("one")];
16231            assert_eq!(seeded_instruction(&runner.state), instruction);
16232            // Model an old record with inferred seeds but no structured input field.
16233            let mut legacy = serde_json::to_value(&runner.state).unwrap();
16234            legacy.as_object_mut().unwrap().remove("sources");
16235            runner.state = serde_json::from_value(legacy).unwrap();
16236            assert_eq!(runner.state.sources, refs::Sources::default());
16237            runner.state.save().unwrap();
16238            runner.state = RunState::load(&runner.state.id).unwrap();
16239            runner.prep().await.unwrap();
16240            for candidate in &runner.state.candidates {
16241                assert_eq!(
16242                    git::rev_parse(&candidate.worktree, "HEAD").await.unwrap(),
16243                    base
16244                );
16245                assert!(!candidate.worktree.join("unwanted").exists());
16246            }
16247        }
16248    }
16249
16250    #[tokio::test]
16251    async fn preparation_retries_after_explicit_release_and_rebuilds_partial_candidates() {
16252        ask_test_home();
16253        let tmp = tempfile::tempdir().unwrap();
16254        let repo = tmp.path().join("repo");
16255        std::fs::create_dir_all(&repo).unwrap();
16256        init_repo(&repo);
16257        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
16258        git::git(&repo, &["checkout", "-b", "seed"]).await.unwrap();
16259        std::fs::write(repo.join("referenced"), "required commit").unwrap();
16260        git::git(&repo, &["add", "."]).await.unwrap();
16261        git::git(&repo, &["commit", "-m", "required seed"])
16262            .await
16263            .unwrap();
16264        let seed = git::rev_parse(&repo, "HEAD").await.unwrap();
16265        git::git(&repo, &["checkout", "main"]).await.unwrap();
16266        let mut runner = runner_at(RunStatus::Prep);
16267        runner.state.repo = repo.clone();
16268        runner.state.base_commit = base.clone();
16269        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16270        runner.state.config.graph.advise = false;
16271        runner.state.config.blind.commit_msg_hook = false;
16272        runner.state.sources =
16273            refs::Sources::resolve(&repo, "origin", None, std::slice::from_ref(&seed))
16274                .await
16275                .unwrap();
16276        runner.roles.implementers = vec![spec("one"), spec("two")];
16277        runner.roles.judges = vec![spec("judge")];
16278        let label = blind::assign_labels(2, runner.state.seed)[0];
16279        let branch = runner.state.branch_for(label);
16280        let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
16281        git::worktree_add_branch(&repo, &worktree, &branch, &base)
16282            .await
16283            .unwrap();
16284        runner.state.candidates.push(Candidate {
16285            index: 0,
16286            label,
16287            agent: "one".into(),
16288            branch,
16289            worktree,
16290            summary: String::new(),
16291            stat: String::new(),
16292            files: 0,
16293            commits: 0,
16294            empty: false,
16295            failed: None,
16296            verified_noop: None,
16297            duration_ms: 0,
16298            folded: false,
16299        });
16300        runner.state.save().unwrap();
16301        // Reload the checkpoint immediately before its first cherry-pick.
16302        runner.state = RunState::load(&runner.state.id).unwrap();
16303        assert_eq!(runner.state.prep_complete, Some(false));
16304        runner.prep().await.unwrap();
16305        assert_eq!(runner.state.prep_complete, Some(true));
16306        assert_eq!(runner.state.candidates.len(), 2);
16307        for candidate in &runner.state.candidates {
16308            assert_eq!(
16309                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
16310                git::tree_of(&repo, &seed).await.unwrap()
16311            );
16312            assert_eq!(
16313                std::fs::read_to_string(candidate.worktree.join("referenced")).unwrap(),
16314                "required commit"
16315            );
16316        }
16317        assert!(runner.state.worktree_root().join("judge-1").exists());
16318        let heads: Vec<String> = candidate_heads(&runner.state.candidates).await;
16319        runner.prep().await.unwrap();
16320        assert_eq!(candidate_heads(&runner.state.candidates).await, heads);
16321
16322        runner.state.prep_complete = Some(false);
16323        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
16324            run: Some(format!(
16325                "test -f '{}'",
16326                tmp.path().join("dependency-ready").display()
16327            )),
16328            ..Default::default()
16329        }];
16330        assert!(runner.prep().await.is_err());
16331        assert!(runner.state.prep_failure.is_some());
16332        std::fs::write(tmp.path().join("dependency-ready"), "available").unwrap();
16333        runner.state = RunState::load(&runner.state.id).unwrap();
16334        assert!(
16335            runner.prep().await.is_err(),
16336            "correcting the cause alone must not auto-retry"
16337        );
16338        let failed_at = runner.state.events.last().unwrap().at;
16339        assert!(
16340            runner.retry_preparation(failed_at).is_err(),
16341            "old approvals cannot unlock the hold"
16342        );
16343        let mut task = crate::queue::Task::new(
16344            "retry".into(),
16345            "retry setup".into(),
16346            repo.clone(),
16347            crate::queue::Source::Human,
16348        );
16349        task.start(runner.state.id.clone());
16350        task.hold_machine(Some("setup failed".into()));
16351        task.release_operator("cli", None);
16352        runner
16353            .retry_preparation(task.resumption.as_ref().unwrap().at)
16354            .unwrap();
16355        runner.prep().await.unwrap();
16356        assert!(runner.state.prep_failure.is_none());
16357        assert_eq!(runner.state.prep_complete, Some(true));
16358        assert_eq!(runner.state.candidates.len(), 2);
16359        assert!(runner.state.worktree_root().join("judge-1").exists());
16360        for candidate in &runner.state.candidates {
16361            assert_eq!(
16362                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
16363                git::tree_of(&repo, &seed).await.unwrap()
16364            );
16365        }
16366    }
16367
16368    async fn candidate_heads(candidates: &[Candidate]) -> Vec<String> {
16369        let mut heads = Vec::new();
16370        for candidate in candidates {
16371            heads.push(git::rev_parse(&candidate.worktree, "HEAD").await.unwrap());
16372        }
16373        heads
16374    }
16375
16376    async fn preservation_resume_fixture() -> (tempfile::TempDir, Runner) {
16377        ask_test_home();
16378        let tmp = tempfile::tempdir().unwrap();
16379        let repo = tmp.path().join("repo");
16380        std::fs::create_dir(&repo).unwrap();
16381        init_repo(&repo);
16382        let mut runner = runner_at(RunStatus::Reviewing);
16383        runner.state.repo = repo.clone();
16384        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16385        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16386        for (index, label) in ['A', 'B'].into_iter().enumerate() {
16387            let branch = format!("candidate-{label}");
16388            let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
16389            git::worktree_add_branch(&repo, &worktree, &branch, "main")
16390                .await
16391                .unwrap();
16392            if label == 'B' {
16393                std::fs::write(worktree.join("change"), "winner").unwrap();
16394                git::rescue_commit(&worktree, "candidate change")
16395                    .await
16396                    .unwrap();
16397            }
16398            runner.state.candidates.push(Candidate {
16399                index,
16400                label,
16401                agent: "alpha".into(),
16402                branch,
16403                worktree,
16404                summary: "completed reply".into(),
16405                stat: String::new(),
16406                files: usize::from(label == 'B'),
16407                commits: usize::from(label == 'B'),
16408                empty: label == 'A',
16409                failed: None,
16410                verified_noop: None,
16411                duration_ms: 1,
16412                folded: false,
16413            });
16414        }
16415        runner.state.judge_skipped = true;
16416        runner.state.tally = Some(Tally {
16417            first_choice: BTreeMap::new(),
16418            borda: BTreeMap::new(),
16419            winner: 'B',
16420            rankings: 0,
16421            unanimous_initial: false,
16422            deliberated: false,
16423            changed_votes: 0,
16424            unanimous_final: false,
16425            tie_break: None,
16426            judges: 0,
16427            present: 0,
16428            quorum: 0,
16429            met_quorum: true,
16430            uncontested: Some("only B produced a change".into()),
16431        });
16432        runner.state.save().unwrap();
16433        (tmp, runner)
16434    }
16435
16436    #[tokio::test]
16437    async fn fold_losers_reclaims_isolated_outputs_without_a_pool_limit() {
16438        let (_tmp, mut runner) = preservation_resume_fixture().await;
16439        runner.state.config.verify.build_cache = crate::config::BuildCache::Isolated;
16440        runner.state.config.disk.cache_limit_bytes = 0;
16441        runner.state.config.graph.advise = true;
16442        runner.state.config.graph.advisors = 1;
16443        let advisor = runner.state.worktree_root().join("advisor-1");
16444        git::worktree_add_detached(&runner.state.repo, &advisor, "main")
16445            .await
16446            .unwrap();
16447        let home = crate::run::home();
16448        let loser =
16449            crate::build_target::resolve(&home, &runner.state.candidates[0].worktree).unwrap();
16450        let winner =
16451            crate::build_target::resolve(&home, &runner.state.candidates[1].worktree).unwrap();
16452        let advisor = crate::build_target::resolve(&home, &advisor).unwrap();
16453        for target in [&loser, &winner, &advisor] {
16454            std::fs::write(target.join("build-output"), "compiled").unwrap();
16455        }
16456
16457        runner.fold_losers().await.unwrap();
16458
16459        assert!(!loser.join("build-output").exists());
16460        assert!(!advisor.join("build-output").exists());
16461        assert!(winner.join("build-output").is_file());
16462    }
16463
16464    #[tokio::test]
16465    async fn fold_losers_persists_discard_before_later_teardown_failure() {
16466        let (_tmp, mut runner) = preservation_resume_fixture().await;
16467        runner.state.candidates[0].folded = true;
16468        runner.state.config.graph.advise = true;
16469        runner.state.config.graph.advisors = 2;
16470        let repo = runner.state.repo.clone();
16471        let root = runner.state.worktree_root();
16472        let discarded = root.join("advisor-1");
16473        git::worktree_add_detached(&repo, &discarded, "main")
16474            .await
16475            .unwrap();
16476        std::fs::write(discarded.join("design_proposal.json"), "{}").unwrap();
16477        let protected = root.join("advisor-2");
16478        git::worktree_add_branch(&repo, &protected, "attached-advisor", "main")
16479            .await
16480            .unwrap();
16481        std::fs::write(protected.join("keep"), "uncommitted").unwrap();
16482        runner.state.save().unwrap();
16483
16484        assert!(runner.fold_losers().await.is_err());
16485        assert!(!discarded.exists());
16486        assert!(protected.join("keep").exists());
16487        let saved = RunState::load(&runner.state.id).unwrap();
16488        assert!(saved.events.iter().any(|event| {
16489            event.message.contains("advisor-1") && event.message.contains("design_proposal.json")
16490        }));
16491    }
16492
16493    #[tokio::test]
16494    async fn read_seat_teardown_discards_only_owned_detached_seats() {
16495        let (tmp, mut runner) = preservation_resume_fixture().await;
16496        let repo = runner.state.repo.clone();
16497        let root = runner.state.worktree_root();
16498        for name in ["advisor-3", "judge-1", "review-2"] {
16499            let path = root.join(name);
16500            git::worktree_add_detached(&repo, &path, "main")
16501                .await
16502                .unwrap();
16503            std::fs::write(path.join("README.md"), "uncommitted edit").unwrap();
16504            std::fs::write(path.join("design_proposal.json"), "{}").unwrap();
16505            remove_read_seat_worktree(&mut runner.state, &path)
16506                .await
16507                .unwrap();
16508            assert!(!path.exists());
16509        }
16510        let outside = tmp.path().join("advisor-1");
16511        let unknown = root.join("unknown");
16512        let attached = root.join("advisor-4");
16513        git::worktree_add_detached(&repo, &outside, "main")
16514            .await
16515            .unwrap();
16516        git::worktree_add_detached(&repo, &unknown, "main")
16517            .await
16518            .unwrap();
16519        git::worktree_add_branch(&repo, &attached, "attached-advisor", "main")
16520            .await
16521            .unwrap();
16522        let foreign = tmp.path().join("foreign");
16523        std::fs::create_dir(&foreign).unwrap();
16524        init_repo(&foreign);
16525        let wrong_repo = root.join("judge-2");
16526        git::worktree_add_detached(&foreign, &wrong_repo, "main")
16527            .await
16528            .unwrap();
16529        let candidate = runner.state.candidates[0].worktree.clone();
16530        for path in [outside, unknown, attached, wrong_repo, candidate] {
16531            std::fs::write(path.join("uncommitted"), "keep").unwrap();
16532            assert!(
16533                remove_read_seat_worktree(&mut runner.state, &path)
16534                    .await
16535                    .is_err()
16536            );
16537            assert_eq!(
16538                std::fs::read_to_string(path.join("uncommitted")).unwrap(),
16539                "keep"
16540            );
16541        }
16542    }
16543
16544    #[tokio::test]
16545    #[cfg(unix)]
16546    async fn disk_interrupted_empty_implementation_retries_after_reload_and_failed_checkpoint() {
16547        for (solo, failed_checkpoint) in
16548            [(true, false), (false, false), (true, true), (false, true)]
16549        {
16550            let (_tmp, mut runner) = preservation_resume_fixture().await;
16551            if solo {
16552                runner.state.candidates.retain(|c| c.label == 'A');
16553            }
16554            runner.state.candidates[0].empty = false;
16555            runner.state.candidates[0].summary.clear();
16556            runner.state.tally = None;
16557            runner.state.judge_skipped = false;
16558            runner.state.status = RunStatus::Implementing;
16559            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
16560            let mut implementer = spec("alpha");
16561            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
16562            runner.roles.implementers = vec![implementer];
16563            let patch = runner.state.dir().join("artifacts/cand-A.patch");
16564            if failed_checkpoint {
16565                std::fs::create_dir_all(&patch).unwrap();
16566            }
16567            runner.state.save().unwrap();
16568            assert_eq!(runner.implement().await.is_err(), failed_checkpoint);
16569            drop(pressure);
16570            runner.state = RunState::load(&runner.state.id).unwrap();
16571            assert_eq!(runner.state.status, RunStatus::Blocked);
16572            assert!(runner.state.interrupted_implementations.contains(&'A'));
16573            assert_eq!(runner.state.candidates[0].commits, 0);
16574            assert!(!runner.state.candidates[0].empty);
16575            assert!(runner.state.candidates[0].failed.is_none());
16576            if failed_checkpoint {
16577                assert!(runner.state.candidate_preservation.contains_key(&'A'));
16578                std::fs::remove_dir(patch).unwrap();
16579            }
16580            runner.state.resource_block = None;
16581            runner.state.config.disk.min_free_bytes = 0;
16582            runner.roles.implementers[0].command = vec![
16583                "sh".into(),
16584                "-c".into(),
16585                "printf 'retried empty interrupted seat\\n' > retry-source; echo completed".into(),
16586            ];
16587            runner.implement().await.unwrap();
16588            assert!(runner.state.interrupted_implementations.is_empty());
16589            assert!(runner.state.candidate_preservation.is_empty());
16590            assert_eq!(runner.state.candidates[0].commits, 1);
16591            assert!(!runner.state.candidates[0].empty);
16592            assert!(
16593                std::fs::read_to_string(runner.state.candidates[0].worktree.join("retry-source"))
16594                    .unwrap()
16595                    .contains("retried empty interrupted seat")
16596            );
16597            if !solo {
16598                assert_eq!(runner.state.candidates[1].commits, 1);
16599            }
16600        }
16601    }
16602
16603    #[tokio::test]
16604    #[cfg(unix)]
16605    async fn disk_interrupted_implementation_preserves_edits_and_commits_before_resource_hold() {
16606        for (committed, block_rescue) in [(false, false), (false, true), (true, false)] {
16607            let (_tmp, mut runner) = preservation_resume_fixture().await;
16608            runner.state.candidates.retain(|c| c.label == 'A');
16609            runner.state.candidates[0].empty = false;
16610            runner.state.candidates[0].summary.clear();
16611            runner.state.tally = None;
16612            runner.state.judge_skipped = false;
16613            runner.state.status = RunStatus::Implementing;
16614            // Force only the real post-spawn watchdog, without failing the
16615            // separate admission check. Existing edits predate its measurement.
16616            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
16617            let wt = runner.state.candidates[0].worktree.clone();
16618            std::fs::write(
16619                wt.join("interrupted-source"),
16620                "retain implementation work\n",
16621            )
16622            .unwrap();
16623            if committed {
16624                git::rescue_commit(&wt, "implementation checkpoint")
16625                    .await
16626                    .unwrap();
16627            }
16628            let lock = git::git(
16629                &wt,
16630                &[
16631                    "rev-parse",
16632                    "--path-format=absolute",
16633                    "--git-path",
16634                    "index.lock",
16635                ],
16636            )
16637            .await
16638            .unwrap();
16639            if block_rescue {
16640                std::fs::write(&lock, "fixture-owned lock").unwrap();
16641            }
16642            let mut implementer = spec("alpha");
16643            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
16644            runner.roles.implementers = vec![implementer];
16645            runner.state.save().unwrap();
16646            let result = runner.implement().await;
16647            drop(pressure);
16648            assert_eq!(result.is_err(), block_rescue);
16649            assert_eq!(
16650                runner.state.resource_block.as_ref().unwrap().kind,
16651                "disk pressure"
16652            );
16653            assert!(
16654                runner
16655                    .state
16656                    .events
16657                    .iter()
16658                    .any(|e| e.message.contains("agent execution interrupted"))
16659            );
16660            assert!(
16661                runner
16662                    .state
16663                    .dir()
16664                    .join("artifacts/candidate-A-recovery/staged.patch")
16665                    .exists()
16666            );
16667            if block_rescue {
16668                let saved = RunState::load(&runner.state.id).unwrap();
16669                assert!(saved.candidate_preservation.contains_key(&'A'));
16670                assert!(!saved.candidates[0].empty);
16671                assert_eq!(
16672                    std::fs::read_to_string(wt.join("interrupted-source")).unwrap(),
16673                    "retain implementation work\n"
16674                );
16675                std::fs::remove_file(lock).unwrap();
16676                runner.state = saved;
16677            } else {
16678                assert_eq!(runner.state.status, RunStatus::Blocked);
16679                assert_eq!(runner.state.candidates[0].commits, 1);
16680            }
16681            // Recovery must save the candidate before deciding whether another
16682            // implementation is needed. No implementer is available on retry.
16683            runner.roles.implementers.clear();
16684            runner.state.config.disk.min_free_bytes = 0;
16685            runner.state.resource_block = None;
16686            runner.implement().await.unwrap();
16687            assert!(runner.state.candidate_preservation.is_empty());
16688            assert_eq!(runner.state.candidates[0].commits, 1);
16689            assert!(!runner.state.candidates[0].empty);
16690            assert!(git::is_clean(&wt).await.unwrap());
16691            assert!(
16692                crate::run::read_artifact(&runner.state, "cand-A.patch")
16693                    .unwrap()
16694                    .contains("retain implementation work")
16695            );
16696        }
16697    }
16698
16699    #[tokio::test]
16700    async fn candidate_preservation_does_not_reflag_confirmed_or_folded_empty_candidates() {
16701        let (_tmp, mut runner) = preservation_resume_fixture().await;
16702        // Schema 15 already confirmed the unfolded no-change result.
16703        runner.implement().await.unwrap();
16704        assert!(runner.state.candidate_preservation.is_empty());
16705        assert!(
16706            !runner
16707                .state
16708                .dir()
16709                .join("artifacts/candidate-A-recovery")
16710                .exists()
16711        );
16712        runner.fold_losers().await.unwrap();
16713        assert!(!runner.state.candidates[0].worktree.exists());
16714        for schema in [14, crate::run::SCHEMA] {
16715            runner.state.schema = schema;
16716            runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
16717            runner.state.save().unwrap();
16718            runner.state = RunState::load(&runner.state.id).unwrap();
16719            runner.implement().await.unwrap();
16720            assert!(runner.state.candidate_preservation.is_empty());
16721            assert!(runner.state.candidates[0].folded);
16722            assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
16723        }
16724    }
16725
16726    #[tokio::test]
16727    async fn infrastructure_failure_report_retains_eligible_candidate_edits() {
16728        let (_tmp, mut runner) = preservation_resume_fixture().await;
16729        runner.state.candidates.retain(|c| c.label == 'A');
16730        runner.state.tally = None;
16731        runner.state.judge_skipped = false;
16732        let candidate = &mut runner.state.candidates[0];
16733        candidate.summary = "Reproduction bind denied with EPERM; source repair complete, deployed browser validation remains parent-owned.".into();
16734        candidate.failed = Some("deployment validation unavailable".into());
16735        std::fs::write(
16736            candidate.worktree.join("repair"),
16737            "future launcher policy\n",
16738        )
16739        .unwrap();
16740        runner
16741            .state
16742            .candidate_preservation
16743            .insert('A', "awaiting persistence".into());
16744        runner.persist_candidates().await.unwrap();
16745        let candidate = &runner.state.candidates[0];
16746        assert!(!candidate.empty);
16747        assert_eq!(candidate.commits, 1);
16748        assert_eq!(candidate.files, 1);
16749        assert!(candidate.failed.is_none());
16750        assert!(candidate.summary.contains("EPERM"));
16751        assert!(
16752            crate::run::read_artifact(&runner.state, "cand-A.patch")
16753                .unwrap()
16754                .contains("future launcher policy")
16755        );
16756        assert!(runner.state.candidate_preservation.is_empty());
16757    }
16758
16759    #[tokio::test]
16760    async fn candidate_preservation_legacy_recovery_blocks_stale_verdict_on_every_resume() {
16761        let (_tmp, mut runner) = preservation_resume_fixture().await;
16762        let wt = runner.state.candidates[0].worktree.clone();
16763        std::fs::write(wt.join("recovered"), "owned edits").unwrap();
16764        runner.state.schema = 14;
16765        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
16766        assert!(runner.state.candidate_preservation.contains_key(&'A'));
16767        let tally = serde_json::to_value(&runner.state.tally).unwrap();
16768        for _ in 0..2 {
16769            assert!(runner.implement().await.is_err());
16770            assert_eq!(runner.state.status, RunStatus::Blocked);
16771            assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
16772            assert!(
16773                runner.state.candidates[0].empty,
16774                "old verdict must remain unusable"
16775            );
16776            assert_eq!(serde_json::to_value(&runner.state.tally).unwrap(), tally);
16777            assert!(runner.state.judge_skipped);
16778            assert!(runner.state.judgements.is_empty() && runner.state.votes.is_empty());
16779            assert!(
16780                crate::run::read_artifact(&runner.state, "cand-A.patch")
16781                    .unwrap()
16782                    .contains("owned edits")
16783            );
16784            assert!(wt.exists());
16785            assert_eq!(
16786                git::commits_ahead(&wt, &runner.state.base_commit, "HEAD")
16787                    .await
16788                    .unwrap(),
16789                1
16790            );
16791            runner.state = RunState::load(&runner.state.id).unwrap();
16792        }
16793    }
16794
16795    #[tokio::test]
16796    async fn candidate_preservation_legacy_failed_seat_keeps_edits_before_judging() {
16797        let (_tmp, mut runner) = preservation_resume_fixture().await;
16798        let wt = runner.state.candidates[0].worktree.clone();
16799        runner.state.candidates[0].failed = Some("CLI failed before commit".into());
16800        std::fs::write(wt.join("recovered"), "failed seat edits").unwrap();
16801        let index_lock = PathBuf::from(
16802            git::git(
16803                &wt,
16804                &[
16805                    "rev-parse",
16806                    "--path-format=absolute",
16807                    "--git-path",
16808                    "index.lock",
16809                ],
16810            )
16811            .await
16812            .unwrap(),
16813        );
16814        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
16815        runner.state.schema = 14;
16816        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
16817        assert!(runner.state.candidate_preservation.contains_key(&'A'));
16818        assert!(runner.implement().await.is_err());
16819        assert!(runner.after_implement().is_err());
16820        assert!(runner.fold_losers().await.is_err());
16821        assert_eq!(
16822            std::fs::read_to_string(wt.join("recovered")).unwrap(),
16823            "failed seat edits"
16824        );
16825        assert!(runner.state.candidate_preservation.contains_key(&'A'));
16826        runner.state = RunState::load(&runner.state.id).unwrap();
16827        std::fs::remove_file(index_lock).unwrap();
16828        // Recovery finds changes that the old uncontested result never judged.
16829        assert!(runner.implement().await.is_err());
16830        assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
16831        assert!(runner.state.candidates[0].empty);
16832        assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
16833        assert!(
16834            crate::run::read_artifact(&runner.state, "cand-A.patch")
16835                .unwrap()
16836                .contains("failed seat edits")
16837        );
16838        assert!(wt.exists());
16839    }
16840
16841    #[tokio::test]
16842    async fn candidate_preservation_loser_cleanup_resumes_after_branch_and_judge_failures() {
16843        let (_tmp, mut runner) = preservation_resume_fixture().await;
16844        let repo = runner.state.repo.clone();
16845        let common = git::git(
16846            &repo,
16847            &["rev-parse", "--path-format=absolute", "--git-common-dir"],
16848        )
16849        .await
16850        .unwrap();
16851        let branch_lock = PathBuf::from(common).join("refs/heads/candidate-A.lock");
16852        std::fs::write(&branch_lock, "fixture-owned lock").unwrap();
16853        assert!(runner.fold_losers().await.is_err());
16854        assert!(!runner.state.candidates[0].worktree.exists());
16855        assert!(!runner.state.candidates[0].folded);
16856        assert!(git::branch_exists(&repo, "candidate-A").await.unwrap());
16857        runner.state = RunState::load(&runner.state.id).unwrap();
16858        std::fs::remove_file(branch_lock).unwrap();
16859        let judge = runner.state.worktree_root().join("judge-1");
16860        git::worktree_add_detached(&repo, &judge, "main")
16861            .await
16862            .unwrap();
16863        std::fs::write(judge.join("uncommitted"), "retain").unwrap();
16864        git::git(&repo, &["worktree", "lock", &git::path_arg(&judge)])
16865            .await
16866            .unwrap();
16867        runner.roles.judges = vec![spec("judge")];
16868        assert!(runner.fold_losers().await.is_err());
16869        runner.state = RunState::load(&runner.state.id).unwrap();
16870        assert!(
16871            runner.state.candidates[0].folded,
16872            "candidate progress saved before judge failure"
16873        );
16874        assert!(!git::branch_exists(&repo, "candidate-A").await.unwrap());
16875        assert!(judge.join("uncommitted").exists());
16876        git::git(&repo, &["worktree", "unlock", &git::path_arg(&judge)])
16877            .await
16878            .unwrap();
16879        runner.fold_losers().await.unwrap();
16880        assert!(!judge.exists());
16881        runner.fold_losers().await.unwrap();
16882    }
16883
16884    #[tokio::test]
16885    async fn candidate_preservation_selected_implementer_resumes_through_execute_graph() {
16886        let (_tmp, mut runner) = preservation_resume_fixture().await;
16887        runner.state.candidates.retain(|c| c.label == 'B');
16888        runner.state.tally = None;
16889        runner.state.judge_skipped = false;
16890        runner.state.prep_complete = Some(true);
16891        runner.state.config.graph.advise = false;
16892        runner.state.config.graph.selected_implementer = Some("alpha".into());
16893        let wt = runner.state.candidates[0].worktree.clone();
16894        std::fs::write(wt.join("leftover"), "completed implementation").unwrap();
16895        runner
16896            .state
16897            .candidate_preservation
16898            .insert('B', "awaiting persistence".into());
16899        let index_lock = git::git(
16900            &wt,
16901            &[
16902                "rev-parse",
16903                "--path-format=absolute",
16904                "--git-path",
16905                "index.lock",
16906            ],
16907        )
16908        .await
16909        .unwrap();
16910        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
16911        runner.state.save().unwrap();
16912        assert!(runner.execute_graph().await.is_err());
16913        assert_eq!(runner.state.status, RunStatus::Blocked);
16914        assert!(runner.state.candidate_preservation.contains_key(&'B'));
16915        std::fs::remove_file(index_lock).unwrap();
16916        // Park at the next graph boundary: this tests the real selected-seat
16917        // hold guard without dispatching reviewers or publishing anything.
16918        for _ in 0..2 {
16919            runner.state = RunState::load(&runner.state.id).unwrap();
16920            runner.pause.park();
16921            runner.execute_graph().await.unwrap();
16922            assert_eq!(runner.state.status, RunStatus::Implementing);
16923            assert!(runner.state.candidate_preservation.is_empty());
16924            assert_eq!(runner.state.candidates[0].commits, 2);
16925            assert!(runner.state.tally.is_none());
16926        }
16927        runner.implement().await.unwrap();
16928        assert_eq!(runner.state.status, RunStatus::Judging);
16929        // A genuine selected-implementer hold must still require release.
16930        runner.state.status = RunStatus::Blocked;
16931        runner.state.candidates[0].failed = Some("implementation failed".into());
16932        runner.state.save().unwrap();
16933        let error = runner.execute_graph().await.unwrap_err();
16934        assert!(
16935            error
16936                .to_string()
16937                .contains("selected implementation is held")
16938        );
16939    }
16940
16941    #[tokio::test]
16942    async fn candidate_preservation_cleanup_unregisters_a_vanished_worktree() {
16943        let (_tmp, mut runner) = preservation_resume_fixture().await;
16944        let repo = runner.state.repo.clone();
16945        let candidate = runner.state.candidates[0].clone();
16946        // Remove only the disposable fixture directory, leaving Git's linked
16947        // worktree registration and branch intact, as in a vanished checkout.
16948        let registered = git::worktree_holding(&repo, &candidate.branch)
16949            .await
16950            .unwrap()
16951            .unwrap();
16952        assert_eq!(
16953            registered.canonicalize().unwrap(),
16954            candidate.worktree.canonicalize().unwrap()
16955        );
16956        std::fs::remove_dir_all(&candidate.worktree).unwrap();
16957        assert_eq!(
16958            git::worktree_holding(&repo, &candidate.branch)
16959                .await
16960                .unwrap(),
16961            Some(registered)
16962        );
16963        assert!(
16964            !git::branch_delete(&repo, &candidate.branch).await.unwrap(),
16965            "the stale registration initially keeps the branch checked out"
16966        );
16967        runner.fold_losers().await.unwrap();
16968        assert!(runner.state.candidates[0].folded);
16969        assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
16970        assert_eq!(
16971            git::worktree_holding(&repo, &candidate.branch)
16972                .await
16973                .unwrap(),
16974            None
16975        );
16976        runner.state = RunState::load(&runner.state.id).unwrap();
16977        runner.fold_losers().await.unwrap();
16978    }
16979
16980    #[tokio::test]
16981    async fn fold_run_unregisters_a_vanished_worktree_and_can_retry() {
16982        let (_tmp, mut runner) = preservation_resume_fixture().await;
16983        let repo = runner.state.repo.clone();
16984        let candidate = runner.state.candidates[0].clone();
16985        let winner = runner.state.candidates[1].clone();
16986        let registered = git::worktree_holding(&repo, &candidate.branch)
16987            .await
16988            .unwrap()
16989            .unwrap();
16990        assert_eq!(
16991            registered.canonicalize().unwrap(),
16992            candidate.worktree.canonicalize().unwrap()
16993        );
16994        std::fs::remove_dir_all(&candidate.worktree).unwrap();
16995        assert_eq!(
16996            git::worktree_holding(&repo, &candidate.branch)
16997                .await
16998                .unwrap(),
16999            Some(registered)
17000        );
17001        assert!(!git::branch_delete(&repo, &candidate.branch).await.unwrap());
17002
17003        for _ in 0..2 {
17004            fold_run(&mut runner.state, false, &crate::run::home())
17005                .await
17006                .unwrap();
17007            runner.state = RunState::load(&runner.state.id).unwrap();
17008            assert!(runner.state.candidates[0].folded);
17009            assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
17010            assert_eq!(
17011                git::worktree_holding(&repo, &candidate.branch)
17012                    .await
17013                    .unwrap(),
17014                None
17015            );
17016            assert!(!runner.state.candidates[1].folded);
17017            assert!(winner.worktree.exists());
17018            assert!(git::branch_exists(&repo, &winner.branch).await.unwrap());
17019        }
17020    }
17021    #[tokio::test]
17022    async fn fold_recovery_override_archives_sources_and_keeps_safety_checks() {
17023        for sidecar in [false, true] {
17024            let tmp = tempfile::tempdir().unwrap();
17025            let home = tmp.path().join("home");
17026            let repo = tmp.path().join("repo");
17027            std::fs::create_dir(&repo).unwrap();
17028            init_repo(&repo);
17029            let mut state = runner_at(RunStatus::Superseded).state;
17030            state.repo = repo.clone();
17031            state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17032            state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17033            state.driver_exited = true;
17034            state.reserve_under(&home).unwrap();
17035            git::git(
17036                &repo,
17037                &["update-ref", "refs/remotes/origin/main", &state.base_commit],
17038            )
17039            .await
17040            .unwrap();
17041            let wt = state.worktree_root().join("cand-A");
17042            git::worktree_add_branch(&repo, &wt, "candidate", "main")
17043                .await
17044                .unwrap();
17045            std::fs::write(wt.join("independent"), "retained implementation\n").unwrap();
17046            git::commit_all(&wt, "fixture: independent source")
17047                .await
17048                .unwrap();
17049            let head = git::rev_parse(&wt, "HEAD").await.unwrap();
17050            state.candidates.push(Candidate {
17051                index: 0,
17052                label: 'A',
17053                agent: "fixture".into(),
17054                branch: "candidate".into(),
17055                worktree: wt.clone(),
17056                summary: String::new(),
17057                stat: String::new(),
17058                files: 0,
17059                commits: 0,
17060                empty: false,
17061                failed: None,
17062                verified_noop: None,
17063                duration_ms: 0,
17064                folded: false,
17065            });
17066            let mut task = crate::queue::Task::new(
17067                "task".into(),
17068                "task".into(),
17069                repo.clone(),
17070                crate::queue::Source::Human,
17071            );
17072            task.runs.push(state.id.clone());
17073            crate::queue::Queue::at(home.join("queue"))
17074                .put(&mut task)
17075                .unwrap();
17076            if sidecar {
17077                crate::pr_recovery::retain_sources(&task, &home).unwrap();
17078            }
17079            state.save_under(&home).unwrap();
17080            let reason = crate::pr_recovery::source_retention_reason(&home, &state).unwrap();
17081            assert!(
17082                fold_run(&mut state, true, &home)
17083                    .await
17084                    .unwrap_err()
17085                    .to_string()
17086                    .contains(&reason)
17087            );
17088            let mut disk = state.config.disk.clone();
17089            disk.fold_grace_secs = 0;
17090            assert_eq!(
17091                crate::clean::fold_due(
17092                    &home.join("runs"),
17093                    &home,
17094                    &state.worktree_root(),
17095                    &disk,
17096                    Timestamp::now() + std::time::Duration::from_secs(10),
17097                )
17098                .await
17099                .unwrap(),
17100                (0, 0)
17101            );
17102            assert!(wt.exists());
17103            state.status = RunStatus::Blocked;
17104            state.save_under(&home).unwrap();
17105            assert!(
17106                fold_run_overriding_recovery_retention(&mut state, true, &home)
17107                    .await
17108                    .is_err()
17109            );
17110            state.status = RunStatus::Superseded;
17111            state.driver_exited = false;
17112            state.driver_claimed = None;
17113            state.save_under(&home).unwrap();
17114            assert!(
17115                fold_run_overriding_recovery_retention(&mut state, true, &home)
17116                    .await
17117                    .is_err()
17118            );
17119            state.driver_pid = Some(std::process::id());
17120            state.driver_started_at = crate::proc::process_started_at(std::process::id());
17121            state.save_under(&home).unwrap();
17122            assert!(
17123                fold_run_overriding_recovery_retention(&mut state, true, &home)
17124                    .await
17125                    .is_err()
17126            );
17127            state.driver_exited = true;
17128            state.driver_pid = None;
17129            state.driver_started_at = None;
17130            state.save_under(&home).unwrap();
17131            let lease = crate::driver::maintenance(&home, &state.id).unwrap();
17132            assert!(
17133                fold_run_overriding_recovery_retention(&mut state, true, &home)
17134                    .await
17135                    .is_err()
17136            );
17137            drop(lease);
17138            #[cfg(unix)]
17139            {
17140                let output = crate::retention::OutputLease::take(&wt, false).unwrap();
17141                assert!(
17142                    fold_run_overriding_recovery_retention(&mut state, true, &home)
17143                        .await
17144                        .is_err()
17145                );
17146                drop(output);
17147            }
17148            let owner = crate::pr_head::owner_lock(&home, &state.id).unwrap();
17149            assert!(
17150                fold_run_overriding_recovery_retention(&mut state, true, &home)
17151                    .await
17152                    .is_err()
17153            );
17154            drop(owner);
17155            let checkpoint = git::git(
17156                &wt,
17157                &[
17158                    "rev-parse",
17159                    "--path-format=absolute",
17160                    "--git-path",
17161                    "CHERRY_PICK_HEAD",
17162                ],
17163            )
17164            .await
17165            .unwrap();
17166            std::fs::write(&checkpoint, &head).unwrap();
17167            assert!(
17168                fold_run_overriding_recovery_retention(&mut state, true, &home)
17169                    .await
17170                    .is_err()
17171            );
17172            std::fs::remove_file(checkpoint).unwrap();
17173            std::fs::write(wt.join("dirty"), "keep").unwrap();
17174            assert!(
17175                fold_run_overriding_recovery_retention(&mut state, true, &home)
17176                    .await
17177                    .is_err()
17178            );
17179            assert!(wt.join("dirty").exists());
17180            std::fs::remove_file(wt.join("dirty")).unwrap();
17181            let evidence = home
17182                .join("runs")
17183                .join(&state.id)
17184                .join("artifacts/fold-evidence");
17185            std::fs::create_dir_all(evidence.parent().unwrap()).unwrap();
17186            std::fs::write(&evidence, "blocked archive").unwrap();
17187            assert!(
17188                fold_run_overriding_recovery_retention(&mut state, true, &home)
17189                    .await
17190                    .is_err()
17191            );
17192            assert!(wt.exists());
17193            assert!(
17194                !RunState::load_under(&state.id, &home)
17195                    .unwrap()
17196                    .events
17197                    .iter()
17198                    .any(|event| event.message.contains("--override-recovery-retention"))
17199            );
17200            std::fs::remove_file(&evidence).unwrap();
17201            fold_run_overriding_recovery_retention(&mut state, true, &home)
17202                .await
17203                .unwrap();
17204            assert!(!wt.exists());
17205            assert!(!git::branch_exists(&repo, "candidate").await.unwrap());
17206            assert!(
17207                git::worktree_holding(&repo, "candidate")
17208                    .await
17209                    .unwrap()
17210                    .is_none()
17211            );
17212            assert!(
17213                std::fs::read_to_string(evidence.join(format!("{head}.patch")))
17214                    .unwrap()
17215                    .contains("retained implementation")
17216            );
17217            assert!(evidence.join(format!("{head}.index")).is_file());
17218            let saved = RunState::load_under(&state.id, &home).unwrap();
17219            assert_eq!(saved.status, RunStatus::Superseded);
17220            assert!(saved.candidates[0].folded);
17221            assert!(saved.events.iter().any(|event| {
17222                event.message.contains("--override-recovery-retention")
17223                    && event.message.contains(&state.id)
17224                    && event.message.contains(&reason)
17225            }));
17226            assert_eq!(
17227                crate::pr_recovery::explicit_sources_retained(&home, &state.id),
17228                sidecar
17229            );
17230        }
17231    }
17232
17233    #[tokio::test]
17234    async fn candidate_preservation_retries_after_upgrade_without_rerunning_seats() {
17235        ask_test_home();
17236        let tmp = tempfile::tempdir().unwrap();
17237        let repo = tmp.path().join("repo");
17238        std::fs::create_dir(&repo).unwrap();
17239        init_repo(&repo);
17240        let mut runner = runner_at(RunStatus::Implementing);
17241        runner.state.repo = repo.clone();
17242        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17243        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17244        for (index, label) in ['A', 'B'].into_iter().enumerate() {
17245            let branch = format!("candidate-{label}");
17246            let wt = runner.state.worktree_root().join(format!("cand-{label}"));
17247            git::worktree_add_branch(&repo, &wt, &branch, "main")
17248                .await
17249                .unwrap();
17250            std::fs::write(wt.join("README.md"), "tracked edits\n").unwrap();
17251            git::git(&wt, &["add", "README.md"]).await.unwrap();
17252            std::fs::write(wt.join("README.md"), "later tracked edits\n").unwrap();
17253            std::fs::write(wt.join("new-file"), "untracked edits\n").unwrap();
17254            runner.state.candidates.push(Candidate {
17255                index,
17256                label,
17257                agent: "alpha".to_owned(),
17258                branch,
17259                worktree: wt,
17260                summary: "completed implementation".to_owned(),
17261                stat: String::new(),
17262                files: 0,
17263                commits: 0,
17264                empty: false,
17265                failed: None,
17266                verified_noop: None,
17267                duration_ms: 42,
17268                folded: false,
17269            });
17270            runner
17271                .state
17272                .candidate_preservation
17273                .insert(label, "awaiting persistence".to_owned());
17274        }
17275        let wt = runner.state.candidates[0].worktree.clone();
17276        let index_lock = git::git(
17277            &wt,
17278            &[
17279                "rev-parse",
17280                "--path-format=absolute",
17281                "--git-path",
17282                "index.lock",
17283            ],
17284        )
17285        .await
17286        .unwrap();
17287        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
17288        runner.state.save().unwrap();
17289        assert!(runner.persist_candidates().await.is_err());
17290        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17291        assert!(!runner.state.candidate_preservation.contains_key(&'B'));
17292        assert_eq!(
17293            runner.state.candidates[1].commits, 1,
17294            "other results are still collected"
17295        );
17296        assert!(
17297            !runner.state.candidates[0].empty,
17298            "failed rescue is not no change"
17299        );
17300        assert_eq!(
17301            runner.state.candidates[0].summary,
17302            "completed implementation"
17303        );
17304        assert!(runner.after_implement().is_err());
17305        let home = tmp.path().join("fold-home");
17306        assert!(fold_run(&mut runner.state, true, &home).await.is_err());
17307        assert!(wt.join("new-file").exists());
17308        let recovery = runner.state.dir().join("artifacts/candidate-A-recovery");
17309        assert!(recovery.join("staged.patch").exists());
17310        assert!(recovery.join("unstaged.patch").exists());
17311        assert_eq!(
17312            std::fs::read_to_string(recovery.join("untracked/new-file")).unwrap(),
17313            "untracked edits\n"
17314        );
17315        runner.state.begin_pass();
17316        runner.state.end_pass_parked(ParkCause::Upgrade {
17317            from: "1.0".into(),
17318            to: Some("1.1".into()),
17319        });
17320        runner.state.save().unwrap();
17321        runner.state = RunState::load(&runner.state.id).unwrap();
17322        assert!(matches!(
17323            runner.state.passes.last().unwrap().end,
17324            Some(crate::run::PassEnd::Parked {
17325                cause: ParkCause::Upgrade { .. }
17326            })
17327        ));
17328        std::fs::remove_file(index_lock).unwrap();
17329        // No implementer is configured: a persistence retry cannot dispatch a seat.
17330        runner.implement().await.unwrap();
17331        assert!(runner.state.candidate_preservation.is_empty());
17332        assert!(
17333            runner
17334                .state
17335                .candidates
17336                .iter()
17337                .all(|c| c.commits == 1 && !c.empty)
17338        );
17339        assert!(git::is_clean(&wt).await.unwrap());
17340        assert!(
17341            crate::run::read_artifact(&runner.state, "cand-A.patch")
17342                .unwrap()
17343                .contains("later tracked edits")
17344        );
17345    }
17346
17347    #[tokio::test]
17348    async fn candidate_preservation_git_read_and_cleanup_fail_closed() {
17349        ask_test_home();
17350        let tmp = tempfile::tempdir().unwrap();
17351        let repo = tmp.path().join("repo");
17352        std::fs::create_dir(&repo).unwrap();
17353        init_repo(&repo);
17354        let wt = tmp.path().join("candidate");
17355        git::worktree_add_branch(&repo, &wt, "candidate", "main")
17356            .await
17357            .unwrap();
17358        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
17359        assert!(remove_preserved_worktree(&repo, &wt).await.is_err());
17360        assert!(wt.join("uncommitted").exists());
17361        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
17362        std::fs::remove_file(wt.join("uncommitted")).unwrap();
17363        let mut runner = runner_at(RunStatus::Implementing);
17364        runner.state.repo = repo.clone();
17365        runner.state.base_commit = "missing-base".to_owned();
17366        runner.state.candidates.push(Candidate {
17367            index: 0,
17368            label: 'A',
17369            agent: "alpha".into(),
17370            branch: "candidate".into(),
17371            worktree: wt.clone(),
17372            summary: "completed".into(),
17373            stat: String::new(),
17374            files: 0,
17375            commits: 0,
17376            empty: false,
17377            failed: None,
17378            verified_noop: None,
17379            duration_ms: 1,
17380            folded: false,
17381        });
17382        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
17383        assert!(
17384            fold_run(&mut runner.state, true, &tmp.path().join("home"))
17385                .await
17386                .is_err()
17387        );
17388        assert!(!runner.state.candidates[0].folded);
17389        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
17390        std::fs::remove_file(wt.join("uncommitted")).unwrap();
17391        runner
17392            .state
17393            .candidate_preservation
17394            .insert('A', "pending".into());
17395        assert!(runner.persist_candidates().await.is_err());
17396        assert!(!runner.state.candidates[0].empty);
17397        assert!(!runner.state.candidates[0].folded);
17398        assert!(wt.exists());
17399        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17400        let patch_path = runner.state.dir().join("artifacts/cand-A.patch");
17401        std::fs::create_dir_all(&patch_path).unwrap();
17402        assert!(
17403            runner.persist_candidates().await.is_err(),
17404            "artifact failure stays pending"
17405        );
17406        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17407        assert!(!runner.state.candidates[0].empty);
17408        std::fs::remove_dir(patch_path).unwrap();
17409        runner.persist_candidates().await.unwrap();
17410        assert!(
17411            runner.state.candidates[0].empty,
17412            "only successful inspection confirms no change"
17413        );
17414    }
17415
17416    fn init_repo(dir: &Path) {
17417        let run = |args: &[&str]| {
17418            let out = std::process::Command::new("git")
17419                .args(args)
17420                .current_dir(dir)
17421                .quiet()
17422                .output()
17423                .expect("spawn git");
17424            assert!(
17425                out.status.success(),
17426                "git {args:?} failed: {}",
17427                String::from_utf8_lossy(&out.stderr)
17428            );
17429        };
17430        run(&["init", "-b", "main"]);
17431        run(&["config", "user.name", "magi test"]);
17432        run(&["config", "user.email", "magi@example.com"]);
17433        std::fs::write(dir.join("README.md"), "# fixture\n").unwrap();
17434        run(&["add", "-A"]);
17435        run(&["commit", "-m", "init"]);
17436    }
17437
17438    // `settle_questions` is what closes the ghost the phone showed: a run's
17439    // seat asked something, the run then ended, and nothing was left to
17440    // abandon the question it left `open`. `HOME` is a process-wide
17441    // `OnceLock` (see `run::set_home`'s doc), so this only wins the race the
17442    // first time it runs in the binary — every test below still reaches the
17443    // same directory whichever call won, and each gets its own run id from
17444    // `RunState::new`, so they never collide there.
17445    fn ask_test_home() {
17446        crate::run::pin_test_home();
17447    }
17448
17449    #[test]
17450    fn startup_terminal_save_failure_preserves_original_error_and_reservation() {
17451        ask_test_home();
17452        let mut runner = runner_at(RunStatus::Prep);
17453        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
17454        // A blocked temporary output path makes the terminal save fail while
17455        // preserving the already published reservation.
17456        std::fs::create_dir(runner.state.dir().join("run.json.tmp")).unwrap();
17457        let error = guard
17458            .finish(
17459                &mut runner.state,
17460                Err(
17461                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "original refusal")
17462                        .into(),
17463                ),
17464            )
17465            .unwrap_err();
17466        assert_eq!(
17467            error.downcast_ref::<std::io::Error>().unwrap().kind(),
17468            std::io::ErrorKind::PermissionDenied
17469        );
17470        assert!(error.downcast_ref::<crate::run::StartupFailure>().is_some());
17471        let message = format!("{error:#}");
17472        assert!(message.contains("original refusal"));
17473        assert!(!message.contains("could not save terminal"));
17474        assert_eq!(
17475            error.chain().count(),
17476            2,
17477            "only startup attribution wraps the original error"
17478        );
17479        let saved = RunState::load(&runner.state.id).unwrap();
17480        assert_eq!(saved.status, RunStatus::Blocked);
17481        assert!(!saved.startup.unwrap().complete);
17482    }
17483
17484    #[test]
17485    fn reserved_startup_interruption_is_blocked_and_not_resumable() {
17486        ask_test_home();
17487        let mut runner = runner_at(RunStatus::Prep);
17488        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
17489        let id = runner.state.id.clone();
17490        drop(guard);
17491        let saved = RunState::load(&id).unwrap();
17492        assert_eq!(saved.status, RunStatus::Blocked);
17493        assert!(!saved.startup.as_ref().unwrap().complete);
17494        assert!(
17495            saved
17496                .startup
17497                .unwrap()
17498                .failure
17499                .unwrap()
17500                .contains("interrupted")
17501        );
17502        assert!(Runner::resume(&id).is_err());
17503    }
17504
17505    #[test]
17506    fn startup_failure_keeps_typed_cause_and_separate_task_history() {
17507        ask_test_home();
17508        let mut runner = runner_at(RunStatus::Prep);
17509        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
17510        let error = guard
17511            .finish(
17512                &mut runner.state,
17513                Err(
17514                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "refused startup")
17515                        .into(),
17516                ),
17517            )
17518            .unwrap_err();
17519        assert_eq!(
17520            error.downcast_ref::<std::io::Error>().unwrap().kind(),
17521            std::io::ErrorKind::PermissionDenied
17522        );
17523        let failure = error.downcast_ref::<crate::run::StartupFailure>().unwrap();
17524        let mut task = crate::queue::Task::new(
17525            "review".into(),
17526            "criteria".into(),
17527            runner.state.repo.clone(),
17528            crate::queue::Source::Human,
17529        );
17530        task.record_startup_failure(failure.clone());
17531        task.record_startup_failure(failure.clone());
17532        assert_eq!(task.startup_failures.len(), 1);
17533        assert!(task.runs.is_empty());
17534        assert_eq!(task.attempts, 0);
17535    }
17536
17537    async fn exhausted_base_fixture() -> (tempfile::TempDir, Runner, String, String) {
17538        ask_test_home();
17539        let tmp = tempfile::tempdir().unwrap();
17540        let repo = tmp.path().join("repo");
17541        std::fs::create_dir(&repo).unwrap();
17542        init_repo(&repo);
17543        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
17544        let origin = tmp.path().join("origin.git");
17545        git::git(&repo, &["init", "--bare", origin.to_str().unwrap()])
17546            .await
17547            .unwrap();
17548        git::git(
17549            &repo,
17550            &["remote", "add", "origin", origin.to_str().unwrap()],
17551        )
17552        .await
17553        .unwrap();
17554        git::git(&repo, &["checkout", "-b", "fix/retained"])
17555            .await
17556            .unwrap();
17557        std::fs::write(repo.join("retained"), "retained change").unwrap();
17558        git::git(&repo, &["add", "."]).await.unwrap();
17559        git::git(&repo, &["commit", "-m", "retained implementation"])
17560            .await
17561            .unwrap();
17562        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
17563        git::git(&repo, &["checkout", "main"]).await.unwrap();
17564        std::fs::write(repo.join("base-change"), "new base").unwrap();
17565        git::git(&repo, &["add", "."]).await.unwrap();
17566        git::git(&repo, &["commit", "-m", "base moved"])
17567            .await
17568            .unwrap();
17569        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
17570        git::git(&repo, &["checkout", "fix/retained"])
17571            .await
17572            .unwrap();
17573        let mut runner = runner_at(RunStatus::Voting);
17574        runner.state.repo = repo.clone();
17575        runner.state.base_commit = base;
17576        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
17577        runner.state.config.disk.min_free_bytes = 0;
17578        runner.state.config.graph.review_rounds = 1;
17579        runner.state.config.verify.e2e = vec!["true".into()];
17580        runner.state.config.verify.gate = vec!["true".into()];
17581        runner.state.candidates = vec![Candidate {
17582            index: 0,
17583            label: 'A',
17584            agent: "fixture".into(),
17585            branch: "fix/retained".into(),
17586            worktree: repo.clone(),
17587            summary: String::new(),
17588            stat: String::new(),
17589            files: 1,
17590            commits: 1,
17591            empty: false,
17592            failed: None,
17593            verified_noop: None,
17594            duration_ms: 0,
17595            folded: false,
17596        }];
17597        runner.state.tally = Some(Tally {
17598            first_choice: BTreeMap::new(),
17599            borda: BTreeMap::new(),
17600            winner: 'A',
17601            rankings: 0,
17602            unanimous_initial: true,
17603            deliberated: false,
17604            changed_votes: 0,
17605            unanimous_final: true,
17606            tie_break: None,
17607            judges: 0,
17608            present: 0,
17609            quorum: 0,
17610            met_quorum: true,
17611            uncontested: Some("review-only".into()),
17612        });
17613        let mut task = crate::queue::Task::new(
17614            "fixture".into(),
17615            "fixture".into(),
17616            repo,
17617            crate::queue::Source::Human,
17618        );
17619        task.link_run(&runner.state.id);
17620        crate::queue::Queue::open().put(&mut task).unwrap();
17621        runner.state.origin = Some(crate::run::Origin::queue(&task.id));
17622        runner.state.base_sync = Some(BaseSync {
17623            tip: String::new(),
17624            behind: 1,
17625            attempts: BASE_SYNC_ROUNDS,
17626            conflict: None,
17627            already_in: None,
17628        });
17629        runner.sync_to_base().await.unwrap();
17630        assert_eq!(runner.state.status, RunStatus::Blocked);
17631        (tmp, runner, head, task.id)
17632    }
17633
17634    #[tokio::test]
17635    async fn rebase_preparation_failure_preserves_base_sync_budget_and_resumes() {
17636        let (_tmp, mut runner, head, _task) = exhausted_base_fixture().await;
17637        runner.state.status = RunStatus::Voting;
17638        runner.state.base_sync = None;
17639        runner.state.base_sync_recovery = Default::default();
17640        let scratch = runner.state.dir().join("base-sync");
17641        std::fs::create_dir_all(&scratch).unwrap();
17642        std::fs::write(scratch.join("obstruction"), "keep").unwrap();
17643        runner.sync_to_base().await.unwrap();
17644        assert!(runner.state.resource_block.is_some());
17645        assert!(!runner.state.base_sync_blocked());
17646        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 0);
17647        assert_eq!(runner.state.base_episode_used(), 0);
17648        assert!(runner.state.base_sync_recovery.operations.is_empty());
17649        assert!(runner.state.rebase_fixes.is_empty());
17650        assert_eq!(
17651            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
17652            head
17653        );
17654        std::fs::remove_dir_all(&scratch).unwrap();
17655        runner.state.resource_block = None;
17656        runner.sync_to_base().await.unwrap();
17657        assert!(!runner.state.base_sync_blocked());
17658        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
17659        assert_eq!(runner.state.base_episode_used(), 1);
17660        assert!(runner.state.base_sync_recovery.operations[0].finished);
17661        assert!(runner.state.rebase_fixes.is_empty());
17662        assert!(git::is_ancestor(&runner.state.repo, "origin/main", "HEAD").await);
17663        assert!(git::is_clean(&runner.state.repo).await.unwrap());
17664    }
17665
17666    #[cfg(unix)]
17667    #[tokio::test]
17668    async fn base_recovery_control_rechecks_owner_decision_and_routing_at_consumption() {
17669        for routed in [false, true] {
17670            let (_tmp, mut runner, head, owner) = exhausted_base_fixture().await;
17671            let home = crate::run::home();
17672            let queue = crate::queue::Queue::open();
17673            let task = queue.get(&owner).unwrap();
17674            runner.state.task_instruction = Some(task.instruction.clone());
17675            runner.state.driver_exited = true;
17676            runner.state.save().unwrap();
17677            let questions = crate::ask::Questions::at(home.join("questions"));
17678            let mut q = crate::ask::Question::new(
17679                runner.state.id.clone(),
17680                "base-recovery".into(),
17681                "owner".into(),
17682                "Recover bounded base movement?".into(),
17683                String::new(),
17684                vec!["recover".into()],
17685            );
17686            q.actions.insert(
17687                "recover".into(),
17688                crate::ask::ChoiceAction::RecoverBase {
17689                    run: runner.state.id.clone(),
17690                    stop: runner.state.base_sync_recovery.stop.clone().unwrap(),
17691                    episode: runner.state.base_sync_recovery.episodes.last().unwrap().id,
17692                },
17693            );
17694            q.routed_task = Some(owner.clone());
17695            q.answer(crate::ask::Answer::Choice("recover".into()))
17696                .unwrap();
17697            questions.put(&mut q).unwrap();
17698            crate::base_recovery_control::recover(
17699                &queue,
17700                &home,
17701                crate::base_recovery_control::Request {
17702                    run: runner.state.id.clone(),
17703                    head: head.clone(),
17704                    actor: "decisions".into(),
17705                    request: q.id.clone(),
17706                    decision: Some((owner.clone(), q.answered_at.unwrap())),
17707                    expected_stop: Some((
17708                        runner.state.base_sync_recovery.stop.clone().unwrap(),
17709                        runner.state.base_sync_recovery.episodes.last().unwrap().id,
17710                    )),
17711                },
17712            )
17713            .await
17714            .unwrap();
17715            if routed {
17716                questions
17717                    .update(&q.id, |q| {
17718                        q.routed_task = Some("another-owner".into());
17719                        Ok(())
17720                    })
17721                    .unwrap();
17722            } else {
17723                let mut task = queue.get(&owner).unwrap();
17724                task.hold_manual(Some("new owner decision".into()));
17725                // Keep the generation to exercise the separate owner-decision binding.
17726                task.status = crate::queue::TaskStatus::Queued;
17727                queue.put(&mut task).unwrap();
17728            }
17729            runner.state = RunState::load(&runner.state.id).unwrap();
17730            runner.sync_to_base().await.unwrap();
17731            let approval = runner
17732                .state
17733                .base_sync_recovery
17734                .authorizations
17735                .last()
17736                .unwrap();
17737            assert!(approval.consumed);
17738            assert!(approval.invalidated.as_ref().unwrap().contains(if routed {
17739                "routing"
17740            } else {
17741                "owner decision"
17742            }));
17743            assert_eq!(
17744                runner.state.base_sync.as_ref().unwrap().attempts,
17745                BASE_SYNC_ROUNDS
17746            );
17747            assert_eq!(
17748                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
17749                head
17750            );
17751        }
17752    }
17753
17754    #[cfg(unix)]
17755    #[tokio::test]
17756    async fn base_recovery_authorizes_its_worker_but_rejects_other_workers() {
17757        const CHILD: &str = "MAGI_BASE_RECOVERY_WORKER_TEST";
17758        if std::env::var_os(CHILD).is_none() {
17759            let home = tempfile::tempdir().unwrap();
17760            let output = std::process::Command::new(std::env::current_exe().unwrap())
17761                .args([
17762                    "--exact",
17763                    "graph::tests::base_recovery_authorizes_its_worker_but_rejects_other_workers",
17764                    "--nocapture",
17765                ])
17766                .env(CHILD, "1")
17767                .env("MAGI_HOME", home.path())
17768                .env("MAGI_WORKER_HOME", home.path())
17769                .env("MAGI_WORKER_ID", "abcdef")
17770                .output()
17771                .unwrap();
17772            assert!(
17773                output.status.success()
17774                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
17775                "{}\n{}",
17776                String::from_utf8_lossy(&output.stdout),
17777                String::from_utf8_lossy(&output.stderr)
17778            );
17779            return;
17780        }
17781        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
17782        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
17783        let home = crate::run::home();
17784        let queue = crate::queue::Queue::open();
17785        let mut owner = queue.get(&task).unwrap();
17786        owner.release_operator("test-release", None);
17787        owner.start(runner.state.id.clone());
17788        queue.put(&mut owner).unwrap();
17789        runner.state.driver_exited = true;
17790        runner.state.task_instruction = Some(owner.instruction.clone());
17791        runner.state.save().unwrap();
17792        let _claim = queue.claim(&task).unwrap();
17793        let reserve = |id: &str| {
17794            let directory = home.join("workers/jobs").join(id);
17795            std::fs::create_dir_all(&directory).unwrap();
17796            let job = crate::worker::Job {
17797                id: id.into(),
17798                sequence: 1,
17799                kind: "task".into(),
17800                key: format!("task:{task}"),
17801                payload: serde_json::json!({"opts": crate::daemon::Opts::default(), "queue": queue.root(), "task": task}),
17802                generation: "fixture-generation".into(),
17803                version: None,
17804                status: crate::worker::Status::Running,
17805                result: None,
17806                pid: Some(std::process::id()),
17807                created_at: 0,
17808                finished_at: None,
17809            };
17810            std::fs::write(
17811                directory.join("job.json"),
17812                serde_json::to_vec(&job).unwrap(),
17813            )
17814            .unwrap();
17815            crate::worker::execution_lease_for_test(&directory.join("live.lock"))
17816        };
17817        let _own = reserve("abcdef");
17818        let other = reserve("fedcba");
17819        assert!(
17820            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
17821                .await
17822                .is_err()
17823        );
17824        assert!(
17825            RunState::load(&runner.state.id)
17826                .unwrap()
17827                .base_sync_recovery
17828                .authorizations
17829                .is_empty()
17830        );
17831        drop(other);
17832        assert!(crate::daemon::is_working_on(
17833            &home,
17834            &runner.state.id,
17835            Timestamp::now()
17836        ));
17837        assert!(
17838            !crate::daemon::is_working_on_other(&home, &runner.state.id, Timestamp::now()).unwrap()
17839        );
17840        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
17841            .await
17842            .unwrap();
17843        assert!(
17844            RunState::load(&runner.state.id)
17845                .unwrap()
17846                .base_recovery_pending()
17847        );
17848    }
17849
17850    #[cfg(unix)]
17851    #[tokio::test]
17852    async fn base_recovery_authorizes_a_crashed_driver_with_a_free_matching_lease() {
17853        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
17854        let home = crate::run::home();
17855        runner.state.driver_pid = Some(std::process::id());
17856        runner.state.driver_started_at = crate::proc::process_started_at(std::process::id());
17857        runner.state.driver_exited = false;
17858        runner.state.begin_pass();
17859        runner.state.save().unwrap();
17860        let mut driver = crate::driver::DriverGuard::acquire(&home, &runner.state).unwrap();
17861        driver.record(&runner.state).unwrap();
17862        let saved = std::fs::read(runner.state.dir().join("run.json")).unwrap();
17863        // Preserve the durable claim as if the process died before Drop saved.
17864        drop(driver);
17865        std::fs::write(runner.state.dir().join("run.json"), saved).unwrap();
17866        assert_eq!(
17867            runner.state.liveness_under(&home, false),
17868            crate::run::Liveness::Dead
17869        );
17870        let queue = crate::queue::Queue::open();
17871        let _claim = queue.claim(&task).unwrap();
17872        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
17873            .await
17874            .unwrap();
17875        let disk = RunState::load(&runner.state.id).unwrap();
17876        assert!(!disk.driver_exited);
17877        assert!(disk.base_recovery_pending());
17878    }
17879
17880    #[cfg(unix)]
17881    #[tokio::test]
17882    async fn base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase() {
17883        const CHILD: &str = "MAGI_BASE_RECOVERY_CLOSURE_TEST";
17884        if std::env::var_os(CHILD).is_none() {
17885            use std::os::unix::fs::PermissionsExt;
17886            let tmp = tempfile::tempdir().unwrap();
17887            let gh = tmp.path().join("gh");
17888            std::fs::write(&gh, r#"#!/bin/sh
17889case "$1 $2" in
17890  'pr view') printf '{"headRefName":"fix/retained","headRefOid":"%s","baseRefName":"main","state":"OPEN","isCrossRepository":false}' "$(git rev-parse fix/retained)" ;;
17891  'pr close') if [ ! -f "$MAGI_BASE_CLOSURE_MARKER" ]; then touch "$MAGI_BASE_CLOSURE_MARKER"; echo 'transient closure failure' >&2; exit 1; fi ;;
17892  *) exit 2 ;;
17893esac
17894"#).unwrap();
17895            std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
17896            let mut paths = vec![tmp.path().to_path_buf()];
17897            paths.extend(std::env::split_paths(&std::env::var_os("PATH").unwrap()));
17898            let output = std::process::Command::new(std::env::current_exe().unwrap())
17899                .args(["--exact", "graph::tests::base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase", "--nocapture"])
17900                .env(CHILD, "1")
17901                .env("MAGI_BASE_CLOSURE_MARKER", tmp.path().join("closure-attempted"))
17902                .env("PATH", std::env::join_paths(paths).unwrap())
17903                .env_remove("MAGI_WORKER_HOME").env_remove("MAGI_WORKER_ID")
17904                .output().unwrap();
17905            assert!(
17906                output.status.success()
17907                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
17908                "{}\n{}",
17909                String::from_utf8_lossy(&output.stdout),
17910                String::from_utf8_lossy(&output.stderr)
17911            );
17912            return;
17913        }
17914        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
17915        let repo = runner.state.repo.clone();
17916        git::git(&repo, &["checkout", "main"]).await.unwrap();
17917        git::git(&repo, &["cherry-pick", &head]).await.unwrap();
17918        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
17919        git::git(&repo, &["checkout", "fix/retained"])
17920            .await
17921            .unwrap();
17922        runner.state.pr = Some(crate::run::PrRecord {
17923            url: "https://example.test/project/pull/1".into(),
17924            number: 1,
17925            state: "open".into(),
17926            checks: "unknown".into(),
17927            round: 0,
17928            rounds: 1,
17929            red_at_merge: Vec::new(),
17930        });
17931        runner.sync_to_base().await.unwrap();
17932        assert_eq!(runner.state.status, RunStatus::Blocked);
17933        assert_eq!(
17934            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
17935            crate::base_sync_recovery::StopKind::ClosingIntegratedPr
17936        );
17937        assert!(runner.state.base_sync_closure_pending());
17938        assert!(crate::handover::can_resume(&runner.state));
17939        let queue = crate::queue::Queue::open();
17940        assert!(!crate::base_sync_recovery::held_task(
17941            &queue,
17942            &queue.get(&task).unwrap()
17943        ));
17944        assert!(runner.state.authorize_base_sync(&task).is_err());
17945        // Legacy closure stops have no typed stop but must retain the checkpoint.
17946        runner.state.base_sync_recovery.stop = None;
17947        runner.state.status = RunStatus::Voting;
17948        runner.state.gate_ran = true;
17949        runner.state.config.graph.review_rounds = 0;
17950        runner.state.save().unwrap();
17951        assert!(crate::handover::can_resume(&runner.state));
17952        runner.state = RunState::load(&runner.state.id).unwrap();
17953        runner.execute_graph().await.unwrap();
17954        assert_eq!(runner.state.status, RunStatus::AlreadyInBase);
17955        assert_eq!(runner.state.pr.as_ref().unwrap().state, "closed");
17956        assert_eq!(
17957            runner.state.base_sync.as_ref().unwrap().attempts,
17958            BASE_SYNC_ROUNDS
17959        );
17960        assert!(runner.state.base_sync_recovery.authorizations.is_empty());
17961        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), head);
17962        assert!(runner.state.reviews.is_empty());
17963        assert!(runner.state.gate.is_empty());
17964    }
17965
17966    #[cfg(unix)]
17967    #[tokio::test]
17968    async fn base_recovery_authorization_requires_current_owner_free_lease_and_clean_tree() {
17969        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
17970        runner.state.driver_exited = true;
17971        runner.state.save().unwrap();
17972        let home = crate::run::home();
17973        let queue = crate::queue::Queue::open();
17974        let _claim = queue.claim(&task).unwrap();
17975        let lease = crate::driver::maintenance(&home, &runner.state.id).unwrap();
17976        assert!(
17977            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
17978                .await
17979                .is_err()
17980        );
17981        drop(lease);
17982        std::fs::write(runner.state.repo.join("dirty"), "retained uncommitted work").unwrap();
17983        assert!(
17984            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
17985                .await
17986                .is_err()
17987        );
17988        std::fs::remove_file(runner.state.repo.join("dirty")).unwrap();
17989        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
17990            .await
17991            .unwrap();
17992        let disk = RunState::load(&runner.state.id).unwrap();
17993        assert!(disk.base_recovery_pending());
17994        assert_eq!(disk.base_sync_recovery.authorizations.len(), 1);
17995        assert!(
17996            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
17997                .await
17998                .is_err()
17999        );
18000        assert_eq!(
18001            RunState::load(&runner.state.id)
18002                .unwrap()
18003                .base_sync_recovery
18004                .authorizations
18005                .len(),
18006            1
18007        );
18008        let mut owner = queue.get(&task).unwrap();
18009        owner.runs.push("20260101-000000-ffff".into());
18010        queue.put(&mut owner).unwrap();
18011        let error = Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18012            .await
18013            .unwrap_err();
18014        assert!(error.to_string().contains("run task ownership changed"));
18015    }
18016
18017    #[cfg(unix)]
18018    #[tokio::test]
18019    async fn base_recovery_legacy_voting_and_repeated_resume_stay_blocked() {
18020        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
18021        let mut legacy = serde_json::to_value(&runner.state).unwrap();
18022        legacy.as_object_mut().unwrap().remove("base_sync_recovery");
18023        legacy["status"] = serde_json::json!("voting");
18024        runner.state = serde_json::from_value(legacy).unwrap();
18025        runner.state.save().unwrap();
18026        for _ in 0..3 {
18027            runner.execute_graph().await.unwrap();
18028            assert_eq!(runner.state.status, RunStatus::Blocked);
18029            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18030            assert!(!crate::handover::can_resume(&runner.state));
18031            assert_eq!(
18032                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18033                head
18034            );
18035            assert!(runner.state.reviews.is_empty());
18036            assert!(!runner.state.gate_ran);
18037        }
18038        let notice = crate::notices::run_ended(&runner.state).unwrap();
18039        let stop = runner.state.base_sync_recovery.stop.clone().unwrap();
18040        runner.state.begin_pass();
18041        runner.state.status = RunStatus::Voting;
18042        runner.deliberate().await.unwrap();
18043        runner.vote().await.unwrap();
18044        runner.finish_after_tally().await.unwrap();
18045        assert_eq!(runner.state.status, RunStatus::Blocked);
18046        assert_eq!(runner.state.base_sync_recovery.stop.as_ref(), Some(&stop));
18047        assert_eq!(
18048            crate::notices::run_ended(&runner.state).unwrap().since,
18049            notice.since
18050        );
18051    }
18052
18053    #[cfg(unix)]
18054    #[tokio::test]
18055    async fn base_recovery_never_authorizes_conflicts_publication_or_unknown_stops() {
18056        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18057        for detail in [
18058            "fix/retained conflicts with origin/main and did not rebase: conflict",
18059            "rebased fix/retained locally but origin refused the push",
18060            "unknown failure",
18061        ] {
18062            runner.state.base_sync.as_mut().unwrap().conflict = Some(detail.into());
18063            runner.state.record_base_sync_stop(&head);
18064            assert!(runner.state.authorize_base_sync(&task).is_err());
18065            runner.state.status = RunStatus::Voting;
18066            runner.execute_graph().await.unwrap();
18067            assert_eq!(runner.state.status, RunStatus::Blocked);
18068            assert!(!crate::handover::can_resume(&runner.state));
18069            assert_eq!(
18070                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18071                head
18072            );
18073        }
18074    }
18075
18076    #[cfg(unix)]
18077    #[tokio::test]
18078    async fn base_recovery_consumption_survives_crash_without_another_attempt() {
18079        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18080        runner.state.authorize_base_sync(&task).unwrap();
18081        assert!(runner.state.consume_base_recovery(&head));
18082        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18083        runner.state.reserve_base_operation(&head, &tip);
18084        runner.state.save().unwrap();
18085        runner.state = RunState::load(&runner.state.id).unwrap();
18086        assert!(!runner.state.consume_base_recovery(&head));
18087        runner.sync_to_base().await.unwrap();
18088        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18089        assert_eq!(runner.state.base_episode_used(), 1);
18090        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
18091        assert!(
18092            runner
18093                .state
18094                .base_sync_recovery
18095                .operations
18096                .last()
18097                .unwrap()
18098                .finished
18099        );
18100        assert!(!runner.state.base_sync_blocked());
18101        runner.sync_to_base().await.unwrap();
18102        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18103    }
18104
18105    #[cfg(unix)]
18106    #[tokio::test]
18107    async fn base_recovery_legacy_authorization_and_unrecorded_wait_grant_no_interval() {
18108        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18109        // Both historical diagnostic spellings retain an exhaustion identity.
18110        let original = runner
18111            .state
18112            .base_sync
18113            .as_ref()
18114            .unwrap()
18115            .conflict
18116            .clone()
18117            .unwrap();
18118        runner.state.base_sync.as_mut().unwrap().conflict = Some(
18119            original
18120                .replace("synchronization(s)", "rebase(s)")
18121                .replace("synchronizing", "rebasing"),
18122        );
18123        runner.state.base_sync_recovery = Default::default();
18124        runner.state.record_base_sync_stop(&head);
18125        assert_eq!(
18126            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
18127            crate::base_sync_recovery::StopKind::Exhausted
18128        );
18129        runner.state.authorize_base_sync(&task).unwrap();
18130        let mut legacy = serde_json::to_value(&runner.state).unwrap();
18131        let auth = legacy["base_sync_recovery"]["authorizations"][0]
18132            .as_object_mut()
18133            .unwrap();
18134        auth.remove("interval");
18135        auth.remove("scope");
18136        runner.state = serde_json::from_value(legacy).unwrap();
18137        assert!(runner.state.consume_base_recovery(&head));
18138        assert_eq!(runner.state.base_episode_used(), 3);
18139        runner.sync_to_base().await.unwrap();
18140        assert_eq!(runner.state.base_episode_used(), 4);
18141        runner.state.resource_block = Some(crate::run::ResourceBlock {
18142            node: "gate".into(),
18143            kind: "cache".into(),
18144            detail: "legacy wait".into(),
18145            at: Timestamp::now(),
18146            cause: crate::run::ResourceBlockCause::Unrecorded,
18147        });
18148        runner.state.save().unwrap();
18149        assert!(
18150            runner
18151                .state
18152                .base_sync_recovery
18153                .episodes
18154                .last()
18155                .unwrap()
18156                .boundary
18157                .is_none()
18158        );
18159        runner.state.resource_block = None;
18160        advance_base_fixture(&runner).await;
18161        runner.sync_to_base().await.unwrap();
18162        assert!(runner.state.base_sync_blocked());
18163        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18164    }
18165
18166    #[cfg(unix)]
18167    async fn advance_base_fixture(runner: &Runner) {
18168        let repo = &runner.state.repo;
18169        for args in [
18170            vec!["checkout", "main"],
18171            vec!["commit", "--allow-empty", "-m", "base advanced"],
18172            vec!["push", "origin", "main"],
18173            vec!["checkout", "fix/retained"],
18174        ] {
18175            git::git(repo, &args).await.unwrap();
18176        }
18177    }
18178
18179    #[cfg(unix)]
18180    fn fresh_base_interval_fixture(runner: &mut Runner) {
18181        runner.state.base_sync.as_mut().unwrap().attempts = 0;
18182        runner.state.base_sync.as_mut().unwrap().conflict = None;
18183        runner.state.base_sync_recovery = Default::default();
18184        runner.state.status = RunStatus::Voting;
18185    }
18186
18187    #[cfg(unix)]
18188    #[tokio::test]
18189    async fn base_recovery_resource_boundary_requires_new_owner_and_is_single_use() {
18190        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
18191        fresh_base_interval_fixture(&mut runner);
18192        runner.state.begin_pass();
18193        runner.sync_to_base().await.unwrap();
18194        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
18195        runner.state.resource_block = Some(crate::run::ResourceBlock {
18196            node: "gate".into(),
18197            kind: "build cache".into(),
18198            detail: "busy".into(),
18199            at: Timestamp::now(),
18200            cause: crate::run::ResourceBlockCause::Timeout {
18201                waited_secs: 1,
18202                limit_secs: 1,
18203            },
18204        });
18205        runner.state.save().unwrap();
18206        let queue = crate::queue::Queue::open();
18207        let mut owner = queue.get(&task).unwrap();
18208        runner.state.task_instruction = Some(owner.instruction.clone());
18209        owner.release_operator("fixture-owner", None);
18210        queue.put(&mut owner).unwrap();
18211        let approval = owner.resumption.clone().unwrap();
18212        runner.state.resource_block = None;
18213        runner.state.save().unwrap();
18214        runner.state = RunState::load(&runner.state.id).unwrap();
18215        advance_base_fixture(&runner).await;
18216        runner.sync_to_base().await.unwrap();
18217        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
18218        assert_eq!(runner.state.base_episode_used(), 1);
18219        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
18220        assert!(
18221            runner.state.base_sync_recovery.episodes[0]
18222                .boundary
18223                .as_ref()
18224                .unwrap()
18225                .consumed
18226        );
18227        assert!(
18228            !runner
18229                .state
18230                .renew_base_episode(&task, &approval, &head, "base")
18231        );
18232        for _ in 0..3 {
18233            owner.release_operator("fixture-owner", None);
18234            queue.put(&mut owner).unwrap();
18235            runner.state = RunState::load(&runner.state.id).unwrap();
18236            runner.state.begin_pass();
18237            runner.sync_to_base().await.unwrap();
18238            assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
18239            assert_eq!(runner.state.base_episode_used(), 1);
18240        }
18241        runner.state.resource_block = Some(crate::run::ResourceBlock {
18242            node: "gate".into(),
18243            kind: "disk pressure".into(),
18244            detail: "free space required".into(),
18245            at: Timestamp::now(),
18246            cause: crate::run::ResourceBlockCause::Other,
18247        });
18248        runner.state.end_pass_parked(ParkCause::Interrupt {
18249            reason: "disk pressure".into(),
18250        });
18251        runner.state.save().unwrap();
18252        owner.release_operator("fixture-owner-after-disk", None);
18253        queue.put(&mut owner).unwrap();
18254        runner.state.resource_block = None;
18255        advance_base_fixture(&runner).await;
18256        runner.sync_to_base().await.unwrap();
18257        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 3);
18258        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 3);
18259        assert_eq!(runner.state.base_episode_used(), 1);
18260        assert_eq!(runner.state.base_sync_recovery.renewals.len(), 2);
18261    }
18262
18263    #[cfg(unix)]
18264    #[tokio::test]
18265    async fn base_recovery_continuous_advancement_stops_at_four() {
18266        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
18267        fresh_base_interval_fixture(&mut runner);
18268        for spent in 1..=BASE_SYNC_ROUNDS {
18269            runner.sync_to_base().await.unwrap();
18270            assert!(!runner.state.base_sync_blocked());
18271            assert_eq!(runner.state.base_episode_used(), spent);
18272            advance_base_fixture(&runner).await;
18273        }
18274        runner.sync_to_base().await.unwrap();
18275        assert_eq!(
18276            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
18277            crate::base_sync_recovery::StopKind::Exhausted
18278        );
18279        let stop = runner.state.base_sync_recovery.stop.as_ref().unwrap();
18280        assert!(stop.unverified_sync);
18281        let action = runner.state.base_sync_next_action();
18282        assert!(action.contains("never reached its gate"));
18283        assert!(action.contains("4/4 in episode 0, 4 lifetime"));
18284        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18285        runner.state = RunState::load(&runner.state.id).unwrap();
18286        runner.sync_to_base().await.unwrap();
18287        assert_eq!(runner.state.base_episode_used(), 4);
18288        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 1);
18289    }
18290
18291    #[cfg(unix)]
18292    #[tokio::test]
18293    async fn base_recovery_stop_diagnostic_requires_synced_head_without_current_gate() {
18294        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
18295        runner.state.ensure_base_episode();
18296        // Verification progress alone is not evidence of a successful sync.
18297        runner.state.record_base_progress(&head);
18298        runner.state.base_sync_recovery.stop = None;
18299        runner.state.record_base_sync_stop(&head);
18300        assert!(
18301            !runner
18302                .state
18303                .base_sync_recovery
18304                .stop
18305                .as_ref()
18306                .unwrap()
18307                .unverified_sync
18308        );
18309
18310        runner.state.finish_base_operation(Some(&head));
18311        // A gate for another head cannot verify this synchronization.
18312        runner.state.gate_ran = true;
18313        runner.state.gate_head = Some("older-head".into());
18314        runner.state.base_sync_recovery.stop = None;
18315        runner.state.record_base_sync_stop(&head);
18316        runner.state.save().unwrap();
18317        runner.state = RunState::load(&runner.state.id).unwrap();
18318        assert!(
18319            runner
18320                .state
18321                .base_sync_recovery
18322                .stop
18323                .as_ref()
18324                .unwrap()
18325                .unverified_sync
18326        );
18327
18328        runner.state.gate_head = Some(head.clone());
18329        runner.state.base_sync_recovery.stop = None;
18330        runner.state.record_base_sync_stop(&head);
18331        assert!(
18332            !runner
18333                .state
18334                .base_sync_recovery
18335                .stop
18336                .as_ref()
18337                .unwrap()
18338                .unverified_sync
18339        );
18340        assert!(
18341            !runner
18342                .state
18343                .base_sync_next_action()
18344                .contains("never reached its gate")
18345        );
18346
18347        // Historical records cannot establish the missing synchronization evidence.
18348        let mut legacy = serde_json::to_value(&runner.state).unwrap();
18349        legacy["base_sync_recovery"]["stop"]
18350            .as_object_mut()
18351            .unwrap()
18352            .remove("unverified_sync");
18353        legacy["base_sync_recovery"]["episodes"][0]
18354            .as_object_mut()
18355            .unwrap()
18356            .remove("last_sync_head");
18357        runner.state = serde_json::from_value(legacy).unwrap();
18358        assert!(
18359            !runner
18360                .state
18361                .base_sync_recovery
18362                .stop
18363                .as_ref()
18364                .unwrap()
18365                .unverified_sync
18366        );
18367        assert!(
18368            runner.state.base_sync_recovery.episodes[0]
18369                .last_sync_head
18370                .is_none()
18371        );
18372    }
18373
18374    #[cfg(unix)]
18375    #[tokio::test]
18376    async fn base_recovery_next_action_reports_new_episode_and_pending_approval() {
18377        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18378        runner.state.authorize_base_sync(&task).unwrap();
18379        assert!(
18380            runner
18381                .state
18382                .base_sync_next_action()
18383                .contains("Approval recorded")
18384        );
18385        assert!(
18386            runner
18387                .state
18388                .base_sync_next_action()
18389                .contains("4/4 in episode 0, 4 lifetime")
18390        );
18391        assert!(runner.state.consume_base_recovery(&head));
18392        assert!(
18393            runner
18394                .state
18395                .base_sync_next_action()
18396                .contains("0/4 in episode 1, 4 lifetime")
18397        );
18398    }
18399
18400    #[cfg(unix)]
18401    #[tokio::test]
18402    async fn base_recovery_changed_head_invalidates_without_spending() {
18403        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
18404        runner.state.authorize_base_sync(&task).unwrap();
18405        git::git(
18406            &runner.state.repo,
18407            &["commit", "--allow-empty", "-m", "external head change"],
18408        )
18409        .await
18410        .unwrap();
18411        runner.sync_to_base().await.unwrap();
18412        let a = runner
18413            .state
18414            .base_sync_recovery
18415            .authorizations
18416            .last()
18417            .unwrap();
18418        assert!(a.consumed);
18419        assert!(a.invalidated.as_deref().unwrap().contains("HEAD changed"));
18420        runner.state = RunState::load(&runner.state.id).unwrap();
18421        assert!(
18422            runner
18423                .state
18424                .base_sync_next_action()
18425                .contains("Approval invalidated")
18426        );
18427        assert!(!runner.state.base_recovery_pending());
18428        assert!(runner.state.base_sync_blocked());
18429        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18430    }
18431
18432    #[cfg(unix)]
18433    #[tokio::test]
18434    async fn base_recovery_stale_fetched_base_invalidates_approval() {
18435        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18436        runner.state.driver_exited = true;
18437        runner.state.save().unwrap();
18438        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
18439            .await
18440            .unwrap();
18441        runner.state = RunState::load(&runner.state.id).unwrap();
18442        advance_base_fixture(&runner).await;
18443        runner.sync_to_base().await.unwrap();
18444        let a = runner
18445            .state
18446            .base_sync_recovery
18447            .authorizations
18448            .last()
18449            .unwrap();
18450        assert!(
18451            a.consumed
18452                && a.invalidated
18453                    .as_deref()
18454                    .unwrap()
18455                    .contains("fetched base changed")
18456        );
18457        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18458        assert_eq!(
18459            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18460            head
18461        );
18462        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
18463            .await
18464            .unwrap();
18465        runner.state = RunState::load(&runner.state.id).unwrap();
18466        runner.sync_to_base().await.unwrap();
18467        assert!(!runner.state.base_sync_blocked());
18468        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18469    }
18470
18471    #[cfg(unix)]
18472    #[tokio::test]
18473    async fn base_recovery_crash_after_git_finishes_reserved_operation_once() {
18474        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18475        runner.state.authorize_base_sync(&task).unwrap();
18476        assert!(runner.state.consume_base_recovery(&head));
18477        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18478        runner.state.reserve_base_operation(&head, &tip);
18479        runner.state.save().unwrap();
18480        let scratch = runner.state.dir().join("base-sync");
18481        assert_eq!(
18482            crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
18483                .await
18484                .unwrap(),
18485            crate::rebase::Rebased::Applied
18486        );
18487        runner.state = RunState::load(&runner.state.id).unwrap();
18488        runner.sync_to_base().await.unwrap();
18489        assert!(
18490            runner
18491                .state
18492                .base_sync_recovery
18493                .operations
18494                .last()
18495                .unwrap()
18496                .finished
18497        );
18498        assert_eq!(runner.state.base_episode_used(), 1);
18499        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18500        assert!(!runner.state.base_sync_blocked());
18501    }
18502
18503    #[cfg(unix)]
18504    #[tokio::test]
18505    async fn base_recovery_crash_preserves_untracked_files() {
18506        for ignored in [false, true] {
18507            let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18508            runner.state.authorize_base_sync(&task).unwrap();
18509            assert!(runner.state.consume_base_recovery(&head));
18510            let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18511            runner.state.reserve_base_operation(&head, &tip);
18512            runner.state.save().unwrap();
18513            let scratch = runner.state.dir().join("base-sync");
18514            assert_eq!(
18515                crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
18516                    .await
18517                    .unwrap(),
18518                crate::rebase::Rebased::Applied
18519            );
18520            let repo = &runner.state.repo;
18521            let result = git::rev_parse(repo, "HEAD").await.unwrap();
18522            assert_ne!(result, head);
18523            if ignored {
18524                let exclude = git::git(repo, &["rev-parse", "--git-path", "info/exclude"])
18525                    .await
18526                    .unwrap();
18527                std::fs::write(repo.join(exclude), "local-notes\n").unwrap();
18528            }
18529            std::fs::write(repo.join("local-notes"), "retained work\n").unwrap();
18530            assert!(
18531                git::git_raw(repo, &["diff", "--quiet", &head])
18532                    .await
18533                    .unwrap()
18534                    .ok()
18535            );
18536            // Resume after the branch moved, before its checkout was reset.
18537            runner.state = RunState::load(&runner.state.id).unwrap();
18538            runner.sync_to_base().await.unwrap();
18539            assert!(runner.state.base_sync_blocked());
18540            assert!(!runner.state.base_sync_recovery.operations[0].finished);
18541            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18542            assert_eq!(
18543                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18544                result
18545            );
18546            assert_eq!(
18547                std::fs::read_to_string(runner.state.repo.join("local-notes")).unwrap(),
18548                "retained work\n"
18549            );
18550            assert!(
18551                git::git_raw(&runner.state.repo, &["diff", "--quiet", &head])
18552                    .await
18553                    .unwrap()
18554                    .ok()
18555            );
18556        }
18557    }
18558
18559    #[cfg(unix)]
18560    #[tokio::test]
18561    async fn base_recovery_crash_does_not_adopt_foreign_commits() {
18562        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18563        runner.state.authorize_base_sync(&task).unwrap();
18564        assert!(runner.state.consume_base_recovery(&head));
18565        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18566        runner.state.reserve_base_operation(&head, &tip);
18567        runner.state.save().unwrap();
18568        let scratch = runner.state.dir().join("base-sync");
18569        crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
18570            .await
18571            .unwrap();
18572        git::sync_to_head(&runner.state.repo).await.unwrap();
18573        std::fs::write(runner.state.repo.join("foreign"), "foreign work").unwrap();
18574        git::git(&runner.state.repo, &["add", "foreign"])
18575            .await
18576            .unwrap();
18577        git::git(&runner.state.repo, &["commit", "-m", "foreign work"])
18578            .await
18579            .unwrap();
18580        let foreign_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
18581        runner.state = RunState::load(&runner.state.id).unwrap();
18582        runner.sync_to_base().await.unwrap();
18583        assert!(runner.state.base_sync_blocked());
18584        assert!(
18585            !runner
18586                .state
18587                .base_sync_recovery
18588                .operations
18589                .last()
18590                .unwrap()
18591                .finished
18592        );
18593        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18594        assert_eq!(
18595            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18596            foreign_head
18597        );
18598    }
18599
18600    #[cfg(unix)]
18601    async fn paused_base_conflict_fixture() -> (tempfile::TempDir, Runner, String, String, PathBuf)
18602    {
18603        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
18604        fresh_base_interval_fixture(&mut runner);
18605        let repo = &runner.state.repo;
18606        git::git(repo, &["checkout", "main"]).await.unwrap();
18607        std::fs::write(repo.join("retained"), "upstream change\n").unwrap();
18608        git::git(repo, &["add", "retained"]).await.unwrap();
18609        git::git(repo, &["commit", "-m", "upstream retained change"])
18610            .await
18611            .unwrap();
18612        git::git(repo, &["push", "origin", "main"]).await.unwrap();
18613        let tip = git::rev_parse(repo, "HEAD").await.unwrap();
18614        git::git(repo, &["checkout", "fix/retained"]).await.unwrap();
18615        let scratch = runner.state.dir().join("base-sync");
18616        assert!(matches!(
18617            git::rebase_start(repo, &scratch, "fix/retained", &tip)
18618                .await
18619                .unwrap(),
18620            git::RebaseStart::Conflicted(_)
18621        ));
18622        runner.state.rebase_fixes.push(crate::run::RebaseFixRecord {
18623            agent: "fixture".into(),
18624            paths: vec!["retained".into()],
18625            from: Some(head.clone()),
18626            stop: Some(git::rev_parse(&scratch, "REBASE_HEAD").await.unwrap()),
18627            index_outside: None,
18628            finished: false,
18629            error: None,
18630            launcher: None,
18631            infra: None,
18632            outage: None,
18633        });
18634        (tmp, runner, head, tip, scratch)
18635    }
18636
18637    #[cfg(unix)]
18638    #[tokio::test]
18639    async fn base_recovery_imports_legacy_rebase_before_following_new_main() {
18640        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
18641        // A resource stop from before reservations existed, with resolved
18642        // contents left for the launcher's ordinary staging continuation.
18643        std::fs::write(
18644            scratch.join("retained"),
18645            "upstream and retained resolution\n",
18646        )
18647        .unwrap();
18648        runner.state.resource_block = Some(crate::run::ResourceBlock {
18649            node: "rebase".into(),
18650            kind: "repository coordination".into(),
18651            detail: "busy".into(),
18652            at: Timestamp::now(),
18653            cause: crate::run::ResourceBlockCause::Other,
18654        });
18655        runner.state.save().unwrap();
18656        // Advance the remote without moving either checkout participating
18657        // in the standing rebase.
18658        let newer = git::git(
18659            &runner.state.repo,
18660            &[
18661                "commit-tree",
18662                "main^{tree}",
18663                "-p",
18664                "main",
18665                "-m",
18666                "base advanced during wait",
18667            ],
18668        )
18669        .await
18670        .unwrap();
18671        git::git(
18672            &runner.state.repo,
18673            &[
18674                "push",
18675                "origin",
18676                &format!("{}:refs/heads/main", newer.trim()),
18677            ],
18678        )
18679        .await
18680        .unwrap();
18681        runner.state = RunState::load(&runner.state.id).unwrap();
18682        runner.state.resource_block = None;
18683        runner.sync_to_base().await.unwrap();
18684        assert!(!runner.state.base_sync_blocked());
18685        let op = &runner.state.base_sync_recovery.operations[0];
18686        assert_eq!(op.head, head);
18687        assert_eq!(op.tip, tip);
18688        assert!(op.finished);
18689        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18690        assert_eq!(runner.state.rebase_fixes.len(), 1);
18691        let latest = git::rev_parse(&runner.state.repo, "origin/main")
18692            .await
18693            .unwrap();
18694        assert_ne!(latest, tip);
18695        runner.state = RunState::load(&runner.state.id).unwrap();
18696        runner.sync_to_base().await.unwrap();
18697        assert!(!runner.state.base_sync_blocked());
18698        assert_eq!(runner.state.base_sync_recovery.operations.len(), 2);
18699        assert_eq!(runner.state.base_sync_recovery.operations[1].tip, latest);
18700        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
18701    }
18702
18703    #[cfg(unix)]
18704    #[tokio::test]
18705    async fn base_recovery_resumes_exact_validated_conflict_result_after_crash() {
18706        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
18707        runner.state.reserve_base_operation(&head, &tip);
18708        runner.state.save().unwrap();
18709        std::fs::write(
18710            scratch.join("retained"),
18711            "upstream and retained resolution\n",
18712        )
18713        .unwrap();
18714        git::git(&scratch, &["add", "retained"]).await.unwrap();
18715        git::git(
18716            &scratch,
18717            &["-c", "core.editor=true", "rebase", "--continue"],
18718        )
18719        .await
18720        .unwrap();
18721        let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
18722        assert!(
18723            !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
18724                .await
18725                .unwrap()
18726                .is_empty()
18727        );
18728        assert_eq!(
18729            crate::rebase::finish(
18730                &mut runner.state,
18731                &scratch,
18732                "fix/retained",
18733                &head,
18734                &tip,
18735                &["retained".into()],
18736                ""
18737            )
18738            .await
18739            .unwrap(),
18740            crate::rebase::Rebased::Applied
18741        );
18742        assert!(!scratch.exists());
18743        // Simulate losing the caller before finish_base_operation/save.
18744        runner.state = RunState::load(&runner.state.id).unwrap();
18745        let op = &runner.state.base_sync_recovery.operations[0];
18746        assert!(!op.finished);
18747        assert_eq!(op.validated_head.as_deref(), Some(result.as_str()));
18748        runner.sync_to_base().await.unwrap();
18749        assert!(!runner.state.base_sync_blocked());
18750        assert!(runner.state.base_sync_recovery.operations[0].finished);
18751        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18752        assert_eq!(runner.state.rebase_fixes.len(), 1);
18753        let winner = runner.state.winner().unwrap().clone();
18754        let wait = runner.repository_wait();
18755        assert!(
18756            verify_current_head(&mut runner.state, &winner, &wait)
18757                .await
18758                .unwrap()
18759        );
18760        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
18761    }
18762
18763    #[cfg(unix)]
18764    #[tokio::test]
18765    async fn base_recovery_revalidates_completed_scratch_before_validation_save() {
18766        for damage in [None, Some("record"), Some("foreign"), Some("dirty")] {
18767            let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
18768            runner.state.reserve_base_operation(&head, &tip);
18769            runner.state.save().unwrap();
18770            std::fs::write(
18771                scratch.join("retained"),
18772                "upstream and retained resolution\n",
18773            )
18774            .unwrap();
18775            git::git(&scratch, &["add", "retained"]).await.unwrap();
18776            git::git(
18777                &scratch,
18778                &["-c", "core.editor=true", "rebase", "--continue"],
18779            )
18780            .await
18781            .unwrap();
18782            let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
18783            assert!(!git::rebase_in_progress(&scratch).await);
18784            assert!(
18785                !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
18786                    .await
18787                    .unwrap()
18788                    .is_empty()
18789            );
18790            match damage {
18791                Some("record") => {
18792                    let path =
18793                        git::git(&scratch, &["rev-parse", "--git-path", "magi-rebase-heads"])
18794                            .await
18795                            .unwrap();
18796                    std::fs::write(scratch.join(path), "").unwrap();
18797                }
18798                Some("foreign") => {
18799                    std::fs::write(scratch.join("foreign"), "foreign work").unwrap();
18800                    git::git(&scratch, &["add", "foreign"]).await.unwrap();
18801                    git::git(&scratch, &["commit", "-m", "foreign work"])
18802                        .await
18803                        .unwrap();
18804                }
18805                Some("dirty") => {
18806                    std::fs::write(scratch.join("retained"), "uncommitted work").unwrap();
18807                }
18808                _ => {}
18809            }
18810            let retained_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
18811            // Crash immediately after Git continuation, before finish runs.
18812            runner.state = RunState::load(&runner.state.id).unwrap();
18813            assert!(
18814                runner.state.base_sync_recovery.operations[0]
18815                    .validated_head
18816                    .is_none()
18817            );
18818            runner.sync_to_base().await.unwrap();
18819            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18820            assert_eq!(runner.state.base_episode_used(), 1);
18821            assert_eq!(runner.state.rebase_fixes.len(), 1);
18822            assert_eq!(
18823                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18824                retained_head
18825            );
18826            if damage.is_some() {
18827                assert!(runner.state.base_sync_blocked());
18828                assert!(scratch.exists());
18829                assert!(!runner.state.base_sync_recovery.operations[0].finished);
18830                assert!(
18831                    runner.state.base_sync_recovery.operations[0]
18832                        .validated_head
18833                        .is_none()
18834                );
18835            } else {
18836                assert!(!runner.state.base_sync_blocked());
18837                assert!(!scratch.exists());
18838                assert!(runner.state.base_sync_recovery.operations[0].finished);
18839                assert_eq!(
18840                    runner.state.base_sync_recovery.operations[0]
18841                        .validated_head
18842                        .as_deref(),
18843                    Some(result.as_str())
18844                );
18845                let winner = runner.state.winner().unwrap().clone();
18846                let wait = runner.repository_wait();
18847                assert!(
18848                    verify_current_head(&mut runner.state, &winner, &wait)
18849                        .await
18850                        .unwrap()
18851                );
18852                assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
18853                runner.state = RunState::load(&runner.state.id).unwrap();
18854                runner.sync_to_base().await.unwrap();
18855                assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18856            }
18857        }
18858    }
18859
18860    #[cfg(unix)]
18861    async fn resumed_gate_fixture() -> (tempfile::TempDir, Runner, String) {
18862        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
18863        // This is an ordinary gate stop, not an authorized base-budget recovery.
18864        runner.state.prep_complete = Some(true);
18865        runner.state.base_sync = None;
18866        runner.state.base_sync_recovery = Default::default();
18867        runner.state.config.graph.gate_fix_rounds = 1;
18868        let mut review = review_round(true, 0, 1, 1, false, true);
18869        review.head = head.clone();
18870        review.verified_head = Some(head.clone());
18871        runner.state.reviews = vec![review];
18872        runner.state.gate = vec![CommandOutcome {
18873            command: "old gate".into(),
18874            code: Some(1),
18875            output_tail: "old failure".into(),
18876            duration_ms: 0,
18877            resource_blocked: false,
18878        }];
18879        runner.state.gate_head = Some(head.clone());
18880        runner.state.gate_ran = true;
18881        runner.state.gate_fixes = vec![crate::run::GateFixRecord {
18882            agent: "fixture".into(),
18883            failed: runner.state.gate.clone(),
18884            notes: "spent".into(),
18885            committed: false,
18886            error: None,
18887        }];
18888        runner.state.land_approval = Some(crate::run::LandApproval {
18889            question: "old approval".into(),
18890            head: head.clone(),
18891        });
18892        runner.state.status = RunStatus::Blocked;
18893        (tmp, runner, head)
18894    }
18895
18896    #[cfg(unix)]
18897    #[tokio::test]
18898    async fn resumed_gate_rebase_verifies_new_head_without_refilling_repairs() {
18899        for (e2e_ok, gate_ok) in [(true, true), (true, false), (false, true)] {
18900            let (tmp, mut runner, old) = resumed_gate_fixture().await;
18901            let phases = tmp.path().join("phases");
18902            runner.state.config.verify.e2e = vec![format!(
18903                "echo e2e >> '{}'; {}",
18904                phases.display(),
18905                if e2e_ok {
18906                    "true"
18907                } else {
18908                    "echo new-e2e-failure; false"
18909                }
18910            )];
18911            runner.state.config.verify.gate = vec![format!(
18912                "echo gate >> '{}'; {}",
18913                phases.display(),
18914                if gate_ok {
18915                    "true"
18916                } else {
18917                    "echo new-gate-failure; false"
18918                }
18919            )];
18920            runner.state.save().unwrap();
18921            runner.state = RunState::load(&runner.state.id).unwrap();
18922            runner.sync_to_base().await.unwrap();
18923            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
18924            assert_ne!(head, old);
18925            // Reentry after Git updated but before verification was invalidated.
18926            runner.state = RunState::load(&runner.state.id).unwrap();
18927            runner.execute_graph().await.unwrap();
18928            assert_eq!(runner.state.gate_fixes.len(), 1);
18929            assert_eq!(runner.state.reviews.len(), 1);
18930            assert_eq!(runner.state.reviews[0].head, old);
18931            assert_eq!(runner.state.land_approval.as_ref().unwrap().head, old);
18932            assert_eq!(runner.state.verification_history.len(), 1);
18933            let history = &runner.state.verification_history[0];
18934            assert_eq!(history.gate_head.as_deref(), Some(old.as_str()));
18935            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
18936            assert!(history.archived_at.is_some());
18937            assert_eq!(history.fixes_spent, Some(1));
18938            assert_eq!(history.gate[0].output_tail, "old failure");
18939            let archive_events: Vec<_> = runner
18940                .state
18941                .events
18942                .iter()
18943                .filter(|e| e.node == "gate" && e.message.starts_with("archived gate on "))
18944                .collect();
18945            assert_eq!(archive_events.len(), 1);
18946            assert!(archive_events[0].message.contains(&short(&old)));
18947            assert!(archive_events[0].message.contains(&short(&head)));
18948            assert!(
18949                archive_events[0]
18950                    .message
18951                    .contains("1 gate-fix round(s) already spent stay spent")
18952            );
18953            assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, head);
18954            assert_eq!(runner.state.head_e2e.as_ref().unwrap().passed, e2e_ok);
18955            if e2e_ok {
18956                assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
18957                assert_eq!(runner.state.gate_allows_progress(), gate_ok);
18958            } else {
18959                assert!(!runner.state.gate_ran);
18960            }
18961            assert_eq!(
18962                runner.state.status,
18963                if e2e_ok && gate_ok {
18964                    RunStatus::Ready
18965                } else {
18966                    RunStatus::Blocked
18967                }
18968            );
18969            if !e2e_ok || !gate_ok {
18970                let cause = runner.state.verification_blocking_cause().unwrap();
18971                assert!(cause.contains(&head));
18972                assert!(cause.contains(if e2e_ok { "gate failed" } else { "e2e failed" }));
18973                // A later successful progress event must not become the cause.
18974                runner.state.event("land", "rebased successfully");
18975                let notice = crate::notices::run_ended(&runner.state).unwrap();
18976                assert!(!format!("{notice:?}").contains("rebased successfully"));
18977                assert!(runner.state.merge.is_none());
18978            }
18979            let before = std::fs::read_to_string(&phases).unwrap();
18980            runner.state.save().unwrap();
18981            runner.state = RunState::load(&runner.state.id).unwrap();
18982            runner.review_loop().await.unwrap();
18983            runner.gate().await.unwrap();
18984            assert_eq!(std::fs::read_to_string(&phases).unwrap(), before);
18985            assert_eq!(runner.state.verification_history.len(), 1);
18986            let history = &runner.state.verification_history[0];
18987            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
18988            assert!(history.archived_at.is_some());
18989            assert_eq!(history.fixes_spent, Some(1));
18990        }
18991    }
18992
18993    #[cfg(unix)]
18994    #[tokio::test]
18995    async fn resumed_gate_unchanged_head_keeps_failure_and_unknown_head_rechecks() {
18996        let (tmp, mut runner, head) = resumed_gate_fixture().await;
18997        let marker = tmp.path().join("gate-ran");
18998        runner.state.config.verify.gate = vec![format!("touch '{}'", marker.display())];
18999        runner.review_loop().await.unwrap();
19000        runner.gate().await.unwrap();
19001        assert_eq!(runner.state.status, RunStatus::Blocked);
19002        assert!(!marker.exists());
19003        assert!(runner.state.verification_history.is_empty());
19004        runner.state.gate_head = None;
19005        runner.gate().await.unwrap();
19006        assert!(marker.exists());
19007        assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
19008        assert_eq!(runner.state.verification_history.len(), 1);
19009        assert_eq!(runner.state.gate_fixes.len(), 1);
19010    }
19011
19012    #[cfg(unix)]
19013    #[tokio::test]
19014    async fn resumed_gate_pending_e2e_retries_without_spending_or_landing() {
19015        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
19016        runner.sync_to_base().await.unwrap();
19017        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19018        runner.state.reconcile_verification_head(&head);
19019        // Both crash-before-command and resource wait are unresolved evidence.
19020        for outcomes in [
19021            Vec::new(),
19022            vec![CommandOutcome {
19023                command: "true".into(),
19024                code: None,
19025                output_tail: "cache unavailable".into(),
19026                duration_ms: 0,
19027                resource_blocked: true,
19028            }],
19029        ] {
19030            runner.state.head_e2e = Some(crate::run::GateRepairE2e {
19031                head: head.clone(),
19032                passed: false,
19033                outcomes,
19034            });
19035            runner.state.gate_ran = false;
19036            runner.state.gate.clear();
19037            runner.state.save().unwrap();
19038            runner.state = RunState::load(&runner.state.id).unwrap();
19039            runner.merge().await.unwrap();
19040            assert!(runner.state.merge.is_none());
19041            runner.review_loop().await.unwrap();
19042            runner.gate().await.unwrap();
19043            assert!(runner.state.head_e2e.as_ref().unwrap().passed);
19044            assert!(runner.state.gate_allows_progress());
19045            assert_eq!(runner.state.gate_fixes.len(), 1);
19046            assert!(runner.state.merge.is_none());
19047        }
19048        // Moving the winner after a successful gate cannot publish an unchecked SHA.
19049        git::git(
19050            &runner.state.repo,
19051            &["commit", "--allow-empty", "-m", "external update"],
19052        )
19053        .await
19054        .unwrap();
19055        runner.merge().await.unwrap();
19056        assert!(runner.state.merge.is_none());
19057        assert_eq!(runner.state.status, RunStatus::Blocked);
19058    }
19059
19060    #[cfg(unix)]
19061    #[tokio::test]
19062    async fn resumed_gate_resource_waits_preserve_budget_and_retry_on_reentry() {
19063        for waiting_on_gate in [false, true] {
19064            let (tmp, mut runner, _old) = resumed_gate_fixture().await;
19065            runner.sync_to_base().await.unwrap();
19066            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19067            runner.state.reconcile_verification_head(&head);
19068            if waiting_on_gate {
19069                runner.state.head_e2e = Some(crate::run::GateRepairE2e {
19070                    head: head.clone(),
19071                    passed: true,
19072                    outcomes: Vec::new(),
19073                });
19074            }
19075            let cache = tmp.path().join("cache");
19076            runner.state.config.verify.e2e =
19077                vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
19078            runner.state.config.verify.gate = vec!["true".into()];
19079            runner.state.config.graph.timeout_resource_wait = 1;
19080            let owner =
19081                crate::cache::Owner::here("other", "e2e", "e2e", &runner.state.repo, "other-head");
19082            let guard =
19083                match crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap() {
19084                    crate::cache::AcquireOutcome::Acquired(g) => g,
19085                    crate::cache::AcquireOutcome::Busy(b) => panic!("unexpected busy cache: {b:?}"),
19086                };
19087            runner.review_loop().await.unwrap();
19088            runner.gate().await.unwrap();
19089            assert!(!runner.state.gate_ran);
19090            assert_eq!(runner.state.gate_fixes.len(), 1);
19091            assert!(runner.state.resource_block.is_some());
19092            runner.merge().await.unwrap();
19093            assert!(runner.state.merge.is_none());
19094            drop(guard);
19095            runner.state = RunState::load(&runner.state.id).unwrap();
19096            // The driver clears the previous pass's resource stop on resume.
19097            runner.state.resource_block = None;
19098            runner.review_loop().await.unwrap();
19099            runner.gate().await.unwrap();
19100            assert!(runner.state.gate_allows_progress());
19101            assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
19102            assert_eq!(runner.state.gate_fixes.len(), 1);
19103        }
19104    }
19105
19106    #[cfg(unix)]
19107    #[tokio::test]
19108    async fn resumed_gate_pre_gate_head_change_and_review_holds() {
19109        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
19110        runner.sync_to_base().await.unwrap();
19111        let before = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19112        runner.state.config.verify.pre_gate = vec!["echo mechanical > mechanical".into()];
19113        // Verification passes before pre_gate and fails on the mechanically changed head.
19114        runner.state.config.verify.e2e = vec!["test ! -f mechanical".into()];
19115        runner.review_loop().await.unwrap();
19116        runner.gate().await.unwrap();
19117        let after = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19118        assert_ne!(before, after);
19119        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, after);
19120        assert!(!runner.state.head_e2e.as_ref().unwrap().passed);
19121        assert!(!runner.state.gate_allows_progress());
19122        runner.merge().await.unwrap();
19123        assert!(runner.state.merge.is_none());
19124        assert!(
19125            runner
19126                .state
19127                .verification_history
19128                .iter()
19129                .any(|h| h.e2e.as_ref().is_some_and(|e| e.head == before && e.passed))
19130        );
19131
19132        // An incomplete review is still an independent hold on a changed head.
19133        runner.state.reviews[0].clean = false;
19134        runner.state.reviews[0].answered = 0;
19135        runner.state.config.verify.e2e = vec!["true".into()];
19136        runner.review_loop().await.unwrap();
19137        runner.gate().await.unwrap();
19138        runner.merge().await.unwrap();
19139        assert_eq!(runner.state.status, RunStatus::Blocked);
19140        assert!(runner.state.merge.is_none());
19141        assert!(
19142            runner
19143                .state
19144                .verification_blocking_cause()
19145                .unwrap()
19146                .contains("review blocked")
19147        );
19148    }
19149
19150    #[cfg(unix)]
19151    #[tokio::test]
19152    async fn resumed_gate_cannot_certify_a_head_changed_by_its_command() {
19153        let (_tmp, mut runner, old) = resumed_gate_fixture().await;
19154        runner.state.gate_head = None;
19155        runner.state.config.verify.gate =
19156            vec!["git -c commit.gpgsign=false commit --allow-empty -m 'gate changed head'".into()];
19157        runner.review_loop().await.unwrap();
19158        runner.gate().await.unwrap();
19159        assert_ne!(
19160            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19161            old
19162        );
19163        assert_eq!(runner.state.gate_head.as_deref(), Some(old.as_str()));
19164        assert!(!runner.state.gate_allows_progress());
19165        assert_eq!(runner.state.status, RunStatus::Blocked);
19166        runner.merge().await.unwrap();
19167        assert!(runner.state.merge.is_none());
19168    }
19169
19170    #[cfg(unix)]
19171    #[tokio::test]
19172    async fn base_recovery_success_requires_new_review_e2e_and_gate() {
19173        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19174        let mut old_review = review_round(true, 0, 1, 1, false, true);
19175        old_review.head = head.clone();
19176        old_review.verified_head = Some(head.clone());
19177        runner.state.reviews = vec![old_review];
19178        runner.state.gate = vec![CommandOutcome {
19179            command: "old gate".into(),
19180            code: None,
19181            output_tail: "timed out after 2400s".into(),
19182            duration_ms: 2_400_000,
19183            resource_blocked: false,
19184        }];
19185        runner.state.gate_ran = true;
19186        runner.state.gate_head = Some(head.clone());
19187        runner.state.land_approval = Some(crate::run::LandApproval {
19188            question: "old-head-approval".into(),
19189            head: head.clone(),
19190        });
19191        runner.state.authorize_base_sync(&task).unwrap();
19192        runner.sync_to_base().await.unwrap();
19193        assert!(!runner.state.base_sync_blocked());
19194        let fresh = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19195        assert_ne!(head, fresh);
19196        assert_eq!(runner.state.reviews.len(), 1);
19197        assert!(!runner.state.gate_ran);
19198        let saved = &runner.state.base_sync_recovery.authorizations[0];
19199        assert_eq!(saved.reviews[0].head, head);
19200        assert_eq!(saved.gate_head.as_deref(), Some(head.as_str()));
19201        assert!(saved.gate_ran);
19202        assert!(!saved.gate[0].ok());
19203        runner.review_loop().await.unwrap();
19204        runner.gate().await.unwrap();
19205        assert_eq!(runner.state.reviews[0].head, head);
19206        assert_eq!(
19207            runner.state.reviews[0].verified_head.as_deref(),
19208            Some(head.as_str())
19209        );
19210        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, fresh);
19211        assert!(runner.state.head_e2e.as_ref().unwrap().passed);
19212        assert_eq!(runner.state.gate_head.as_deref(), Some(fresh.as_str()));
19213        assert!(runner.state.gate_ran);
19214        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
19215        assert_eq!(runner.state.land_approval.as_ref().unwrap().head, head);
19216        assert_ne!(runner.state.land_approval.as_ref().unwrap().head, fresh);
19217        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19218        assert_eq!(
19219            std::fs::read_to_string(runner.state.repo.join("retained")).unwrap(),
19220            "retained change"
19221        );
19222    }
19223
19224    #[cfg(unix)]
19225    #[tokio::test]
19226    async fn base_recovery_moving_base_uses_bounded_authorized_interval() {
19227        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
19228        let queue = crate::queue::Queue::open();
19229        let mut owner = queue.get(&task).unwrap();
19230        owner.release_operator("test-resume", None);
19231        queue.put(&mut owner).unwrap();
19232        let generation = owner.resumption.as_ref().unwrap().generation;
19233        runner.state.task_instruction = Some(owner.instruction.clone());
19234        runner.state.driver_exited = true;
19235        runner.state.save().unwrap();
19236        let home = crate::run::home();
19237        let _claim = queue.claim(&task).unwrap();
19238        owner.resumption.as_mut().unwrap().at =
19239            runner.state.base_sync_recovery.stop.as_ref().unwrap().at;
19240        queue.put(&mut owner).unwrap();
19241        assert!(
19242            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19243                .await
19244                .is_err(),
19245            "an approval from before the stop grants nothing"
19246        );
19247        owner.resumption.as_mut().unwrap().at = Timestamp::now();
19248        queue.put(&mut owner).unwrap();
19249        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19250            .await
19251            .unwrap();
19252        assert!(
19253            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19254                .await
19255                .is_err()
19256        );
19257        runner.state = RunState::load(&runner.state.id).unwrap();
19258        assert_eq!(
19259            runner.state.base_sync_recovery.authorizations[0].generation,
19260            Some(generation)
19261        );
19262        runner.sync_to_base().await.unwrap();
19263        let repo = runner.state.repo.clone();
19264        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
19265        git::git(&repo, &["checkout", "main"]).await.unwrap();
19266        std::fs::write(repo.join("base-change"), "base moved again").unwrap();
19267        git::git(&repo, &["add", "."]).await.unwrap();
19268        git::git(&repo, &["commit", "-m", "move base again"])
19269            .await
19270            .unwrap();
19271        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
19272        git::git(&repo, &["checkout", "fix/retained"])
19273            .await
19274            .unwrap();
19275        runner.sync_to_base().await.unwrap();
19276        assert!(!runner.state.base_sync_blocked());
19277        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
19278        assert_eq!(runner.state.base_episode_used(), 2);
19279        let fresh = git::rev_parse(&repo, "HEAD").await.unwrap();
19280        assert_ne!(fresh, head);
19281        assert!(!runner.state.base_recovery_pending());
19282        // Even replaying the generation with a later timestamp grants nothing.
19283        owner.resumption.as_mut().unwrap().at = Timestamp::now();
19284        queue.put(&mut owner).unwrap();
19285        assert!(
19286            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19287                .await
19288                .is_err()
19289        );
19290        runner.state = RunState::load(&runner.state.id).unwrap();
19291        runner.sync_to_base().await.unwrap();
19292        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
19293        assert_eq!(runner.state.base_sync_recovery.authorizations.len(), 1);
19294        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), fresh);
19295    }
19296
19297    #[cfg(unix)]
19298    #[tokio::test]
19299    async fn base_recovery_tally_skips_deliberation_and_voting_without_a_sync_stop() {
19300        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
19301        runner.state.base_sync = None;
19302        runner.state.status = RunStatus::Blocked;
19303        let mut second = runner.state.candidates[0].clone();
19304        second.label = 'B';
19305        runner.state.candidates.push(second);
19306        assert!(runner.state.votes.is_empty());
19307        assert!(runner.state.deliberation.is_empty());
19308        runner.deliberate().await.unwrap();
19309        runner.vote().await.unwrap();
19310        assert_eq!(runner.state.status, RunStatus::Blocked);
19311        assert!(runner.state.votes.is_empty());
19312        assert!(runner.state.deliberation.is_empty());
19313    }
19314
19315    /// A minimal, git-free `Runner` at a given status — `settle_questions`
19316    /// reads nothing else off it.
19317    fn runner_at(status: RunStatus) -> Runner {
19318        let mut state = RunState::new(
19319            PathBuf::from("/nonexistent/repo"),
19320            "main".to_owned(),
19321            "deadbeef".to_owned(),
19322            "task".to_owned(),
19323            Config::default(),
19324        );
19325        // These fixtures test execution flow, independent of host disk capacity.
19326        state.config.disk.min_free_bytes = 0;
19327        // These fixtures share one home and save concurrently. Short clock
19328        // IDs can collide, making an ownership test read another test's run.
19329        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
19330        state.id = format!(
19331            "20000101-000000-{:04x}",
19332            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
19333        );
19334        state.status = status;
19335        Runner {
19336            state,
19337            roles: ResolvedRoles {
19338                implementers: Vec::new(),
19339                judges: Vec::new(),
19340                reviewers: Vec::new(),
19341                fixer: None,
19342                conductor: conductor(),
19343                implementer_roster: Vec::new(),
19344                judge_roster: Vec::new(),
19345                reviewer_roster: Vec::new(),
19346            },
19347            sem: Arc::new(Semaphore::new(1)),
19348            pause: Pause::new(),
19349            interrupt: Pause::new(),
19350        }
19351    }
19352
19353    #[tokio::test]
19354    async fn source_eviction_resume_restores_before_graph_shortcuts_and_setup() {
19355        crate::run::pin_test_home();
19356        let temp = tempfile::tempdir().unwrap();
19357        let root = temp.path().canonicalize().unwrap();
19358        let repo = root.join("repo");
19359        std::fs::create_dir(&repo).unwrap();
19360        init_repo(&repo);
19361        git::git(&repo, &["config", "core.autocrlf", "false"])
19362            .await
19363            .unwrap();
19364        let mut runner = runner_at(RunStatus::Blocked);
19365        runner.state.repo = repo.clone();
19366        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
19367        runner.state.config.agents = vec![conductor()];
19368        runner.state.config.graph.selected_implementer = Some("conductor".into());
19369        runner.state.config.graph.worktree_root = Some(root.join("worktrees"));
19370        let (shell, command, setup_output) = if cfg!(windows) {
19371            (
19372                vec!["cmd".into(), "/C".into()],
19373                "echo ready>seat-ready",
19374                "ready\r\n",
19375            )
19376        } else {
19377            (
19378                vec!["sh".into(), "-c".into()],
19379                "printf ready > seat-ready",
19380                "ready",
19381            )
19382        };
19383        runner.state.config.verify.shell = Some(shell);
19384        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
19385            run: Some(command.into()),
19386            ..Default::default()
19387        }];
19388        runner.state.save().unwrap();
19389        let path = runner.state.worktree_root().join("judge-1");
19390        git::worktree_add_detached(&repo, &path, &runner.state.base_commit)
19391            .await
19392            .unwrap();
19393        std::fs::write(path.join("checkpoint"), "unrelated seat").unwrap();
19394        git::git(&path, &["add", "."]).await.unwrap();
19395        let tree = git::git(&path, &["write-tree"]).await.unwrap();
19396        let head = git::git(&path, &["commit-tree", &tree, "-m", "seat checkpoint"])
19397            .await
19398            .unwrap();
19399        git::git(&path, &["checkout", "--detach", &head])
19400            .await
19401            .unwrap();
19402        let evidence = crate::fold_evidence::snapshot(
19403            &runner.state,
19404            &crate::run::home().canonicalize().unwrap(),
19405            &head,
19406            64 * 1024 * 1024,
19407        )
19408        .await
19409        .unwrap();
19410        let mut contents = BTreeMap::new();
19411        contents.insert(
19412            repo.join("logs/HEAD"),
19413            format!("{head} {head} fixture\n").into_bytes(),
19414        );
19415        let record = serde_json::json!({
19416            "version":1, "run":runner.state.id, "source":path, "head":head,
19417            "evidence":evidence, "admin":{}, "admin_contents":contents,
19418            "history":{head.clone():evidence}, "phase":"evicted"
19419        });
19420        std::fs::write(
19421            runner.state.dir().join("artifacts/eviction-judge-1.json"),
19422            serde_json::to_vec(&record).unwrap(),
19423        )
19424        .unwrap();
19425        assert!(git::worktree_remove_clean(&repo, &path).await.unwrap());
19426        git::git(&repo, &["reflog", "expire", "--expire=now", "--all"])
19427            .await
19428            .unwrap();
19429        git::git(&repo, &["gc", "--prune=now"]).await.unwrap();
19430        assert!(
19431            !git::git_raw(&repo, &["cat-file", "-e", &head])
19432                .await
19433                .unwrap()
19434                .ok()
19435        );
19436        let mut resumed = Runner::resume(&runner.state.id).unwrap();
19437        let error = resumed.execute().await.unwrap_err();
19438        assert!(
19439            error
19440                .to_string()
19441                .contains("selected implementation is held"),
19442            "{error:#}"
19443        );
19444        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
19445        assert_eq!(
19446            std::fs::read_to_string(path.join("seat-ready")).unwrap(),
19447            setup_output
19448        );
19449        assert_eq!(
19450            std::fs::read_to_string(path.join("checkpoint")).unwrap(),
19451            "unrelated seat"
19452        );
19453        let error = resumed.execute().await.unwrap_err();
19454        assert!(
19455            error
19456                .to_string()
19457                .contains("selected implementation is held"),
19458            "{error:#}"
19459        );
19460        std::fs::write(path.join("checkpoint"), "next recorded review").unwrap();
19461        git::git(&path, &["add", "."]).await.unwrap();
19462        let next_tree = git::git(&path, &["write-tree"]).await.unwrap();
19463        let next = git::git(
19464            &path,
19465            &[
19466                "commit-tree",
19467                &next_tree,
19468                "-p",
19469                &head,
19470                "-m",
19471                "next review checkpoint",
19472            ],
19473        )
19474        .await
19475        .unwrap();
19476        git::git(&path, &["checkout", "--detach", &next])
19477            .await
19478            .unwrap();
19479        resumed.state.reviews.push(
19480            serde_json::from_value(serde_json::json!({
19481                "round":1, "head":next, "reviews":[]
19482            }))
19483            .unwrap(),
19484        );
19485        resumed.state.save().unwrap();
19486        let error = resumed.execute().await.unwrap_err();
19487        assert!(
19488            error
19489                .to_string()
19490                .contains("selected implementation is held"),
19491            "{error:#}"
19492        );
19493        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), next);
19494    }
19495
19496    #[tokio::test]
19497    async fn driver_claim_waits_for_maintenance_before_starting_a_pass() {
19498        crate::run::pin_test_home();
19499        let mut runner = runner_at(RunStatus::Gating);
19500        runner.state.save().unwrap();
19501        let id = runner.state.id.clone();
19502        let passes = runner.state.passes.len();
19503        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
19504        let mut claiming = Box::pin(runner.claim_driver(None));
19505        std::future::poll_fn(|cx| {
19506            assert!(std::future::Future::poll(claiming.as_mut(), cx).is_pending());
19507            std::task::Poll::Ready(())
19508        })
19509        .await;
19510        assert_eq!(RunState::load(&id).unwrap().passes.len(), passes);
19511        drop(owner);
19512        let execution = tokio::time::timeout(Duration::from_secs(2), claiming)
19513            .await
19514            .unwrap()
19515            .unwrap();
19516        assert_eq!(execution.runner.state.passes.len(), passes + 1);
19517        assert!(execution.runner.state.resource_block.is_none());
19518        assert_eq!(
19519            execution.runner.state.liveness(false),
19520            crate::run::Liveness::Live
19521        );
19522        drop(execution);
19523        assert!(RunState::load(&id).unwrap().driver_exited);
19524    }
19525
19526    #[tokio::test]
19527    async fn a_failed_driver_lease_record_releases_the_claim_and_retained_state() {
19528        crate::run::pin_test_home();
19529        let mut runner = runner_at(RunStatus::Gating);
19530        runner.state.save().unwrap();
19531        // run.json can commit, but the subsequent lease metadata write fails.
19532        // Cleanup must run after releasing the short ownership lock.
19533        std::fs::create_dir(runner.state.dir().join("driver.json.tmp")).unwrap();
19534        assert!(runner.claim_driver(None).await.is_err());
19535        assert!(runner.state.driver_exited);
19536        assert_eq!(runner.state.driver_pid, None);
19537        let disk = RunState::load(&runner.state.id).unwrap();
19538        assert!(disk.driver_exited);
19539        assert_eq!(disk.driver_pid, None);
19540        assert_eq!(disk.status, RunStatus::Gating);
19541    }
19542
19543    #[tokio::test]
19544    async fn an_early_graph_error_releases_its_driver() {
19545        crate::run::pin_test_home();
19546        let mut runner = runner_at(RunStatus::Blocked);
19547        runner.state.config.graph.selected_implementer = Some("selected".into());
19548        runner.state.save().unwrap();
19549        assert!(runner.execute().await.is_err());
19550        let disk = RunState::load(&runner.state.id).unwrap();
19551        assert!(disk.driver_exited);
19552        assert_eq!(disk.driver_pid, None);
19553        assert_eq!(disk.status, RunStatus::Blocked);
19554    }
19555
19556    fn merge_repair_request(phase: crate::run::MergeRepairPhase) -> crate::run::MergeRepair {
19557        crate::run::MergeRepair {
19558            question: "repair-question".into(),
19559            head: "old-head".into(),
19560            pr: "https://github.com/o/r/pull/42".into(),
19561            reviews: vec![review_round(false, 1, 1, 1, false, true)],
19562            gate: vec![outcome(Some(0), false)],
19563            gate_head: Some("old-head".into()),
19564            gate_fixes: Vec::new(),
19565            pre_gate: Vec::new(),
19566            phase,
19567            failure: None,
19568        }
19569    }
19570
19571    #[tokio::test]
19572    async fn merge_repair_claim_refuses_concurrent_and_obsolete_drivers() {
19573        crate::run::pin_test_home();
19574        let mut runner = runner_at(RunStatus::Landing);
19575        runner.state.merge_repairs.push(merge_repair_request(
19576            crate::run::MergeRepairPhase::Requested,
19577        ));
19578        runner.state.save().unwrap();
19579        let claim = FixClaim::acquire(&runner.state.dir()).unwrap();
19580        assert!(
19581            runner
19582                .execute()
19583                .await
19584                .unwrap_err()
19585                .to_string()
19586                .contains("already running")
19587        );
19588        assert_eq!(
19589            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
19590            crate::run::MergeRepairPhase::Requested
19591        );
19592        drop(claim);
19593        let mut disk = runner.state.clone();
19594        disk.merge_repairs[0].phase = crate::run::MergeRepairPhase::Complete;
19595        disk.save().unwrap();
19596        assert!(
19597            runner
19598                .execute()
19599                .await
19600                .unwrap_err()
19601                .to_string()
19602                .contains("decision changed")
19603        );
19604        assert_eq!(
19605            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
19606            crate::run::MergeRepairPhase::Complete
19607        );
19608    }
19609
19610    #[test]
19611    fn merge_repair_starts_a_real_new_budget_and_preserves_old_evidence() {
19612        crate::run::pin_test_home();
19613        let mut runner = runner_at(RunStatus::Landing);
19614        let request = merge_repair_request(crate::run::MergeRepairPhase::Fixing);
19615        runner.state.reviews = request.reviews.clone();
19616        runner.state.gate = request.gate.clone();
19617        runner.state.gate_ran = true;
19618        runner.state.land_approval = Some(crate::run::LandApproval {
19619            question: "old".into(),
19620            head: "old-head".into(),
19621        });
19622        runner.state.merge_repairs.push(request);
19623        runner.begin_merge_repair_review(0).unwrap();
19624        assert_eq!(review_conclusion(&runner.state.reviews, 2), None);
19625        assert!(!runner.state.gate_status().ok());
19626        assert!(runner.state.land_approval.is_none());
19627        let disk = RunState::load(&runner.state.id).unwrap();
19628        assert_eq!(disk.merge_repairs[0].reviews[0].blocking, 1);
19629        assert!(disk.merge_repairs[0].gate[0].ok());
19630        assert_eq!(
19631            disk.merge_repairs[0].phase,
19632            crate::run::MergeRepairPhase::Reviewing
19633        );
19634        assert_eq!(disk.merge_repairs[0].pr, "https://github.com/o/r/pull/42");
19635        assert!(disk.reviews.is_empty());
19636    }
19637
19638    #[tokio::test]
19639    async fn merge_repair_interrupted_fixer_and_exhausted_generation_hold_without_repeating_work() {
19640        crate::run::pin_test_home();
19641        for phase in [
19642            crate::run::MergeRepairPhase::Fixing,
19643            crate::run::MergeRepairPhase::Requested,
19644        ] {
19645            let mut runner = runner_at(RunStatus::Landing);
19646            runner.state.config.graph.land_rounds = 0;
19647            runner.state.merge_repairs.push(merge_repair_request(phase));
19648            runner.state.save().unwrap();
19649            assert!(!runner.repair_merge_review().await.unwrap());
19650            assert_eq!(runner.state.status, RunStatus::Blocked);
19651            assert_eq!(
19652                runner.state.merge_repairs[0].phase,
19653                crate::run::MergeRepairPhase::Failed
19654            );
19655            let reason = runner.state.merge_repairs[0].failure.as_ref().unwrap();
19656            assert!(
19657                reason.contains(if phase == crate::run::MergeRepairPhase::Fixing {
19658                    "interrupted"
19659                } else {
19660                    "budget exhausted"
19661                })
19662            );
19663            assert!(runner.state.merge.is_none());
19664        }
19665    }
19666
19667    /// `park_here` folding in the reason `Pause::park_because` recorded -
19668    /// this is what lets an operator reading a run's events tell an
19669    /// interrupt-driven park from an ordinary shutdown park.
19670    #[test]
19671    fn park_here_folds_the_interrupt_reason_into_the_park_event() {
19672        crate::run::pin_test_home();
19673        let mut runner = runner_at(RunStatus::Implementing);
19674        let interrupt = Pause::new();
19675        runner.watch_interrupt(interrupt.clone());
19676
19677        interrupt.park_because("task a1b2 asked to run first");
19678
19679        assert!(runner.park_here().expect("park_here"));
19680        assert!(runner.state.parked);
19681        let last = runner.state.events.last().expect("a park event");
19682        assert_eq!(last.node, "park");
19683        assert!(
19684            last.message.contains("task a1b2 asked to run first"),
19685            "expected the interrupt reason in {:?}",
19686            last.message
19687        );
19688    }
19689
19690    /// The cause is stored on the pass when it parks, and the first cause a
19691    /// shared pause was given is the one that stays.
19692    #[test]
19693    fn park_here_records_the_structured_cause_and_the_first_one_wins() {
19694        crate::run::pin_test_home();
19695        let mut runner = runner_at(RunStatus::Implementing);
19696        runner.state.begin_pass();
19697        let shutdown = Pause::new();
19698        runner.on_pause(shutdown.clone());
19699        let upgrade = ParkCause::Upgrade {
19700            from: "0.121.0".to_owned(),
19701            to: Some("0.121.1".to_owned()),
19702        };
19703        shutdown.park_for(upgrade.clone());
19704        shutdown.park_for(ParkCause::Operator);
19705
19706        assert!(runner.park_here().expect("park_here"));
19707        assert_eq!(
19708            runner.state.passes[0].end,
19709            Some(crate::run::PassEnd::Parked { cause: upgrade })
19710        );
19711        let last = runner.state.events.last().expect("a park event");
19712        assert!(last.message.contains("0.121.0"), "{}", last.message);
19713    }
19714
19715    #[tokio::test]
19716    async fn driver_admission_accepts_a_freshly_minted_record_under_its_lease() {
19717        crate::run::pin_test_home();
19718        let mut runner = runner_at(RunStatus::Reviewing);
19719        runner.state.save().unwrap();
19720        let mut execution = runner.claim_driver(None).await.expect("first execution");
19721        assert_eq!(execution.runner.state.passes.len(), 1);
19722        execution
19723            .driver
19724            .finish(&mut execution.runner.state)
19725            .await
19726            .unwrap();
19727    }
19728
19729    #[tokio::test]
19730    async fn driver_admission_resumes_a_record_saved_before_its_first_claim() {
19731        crate::run::pin_test_home();
19732        let mut runner = runner_at(RunStatus::Reviewing);
19733        runner.state.config.agents = vec![conductor()];
19734        runner.state.config.graph.timeout_resource_wait = 0;
19735        runner.state.save().unwrap();
19736        let id = runner.state.id.clone();
19737        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
19738        assert!(runner.claim_driver(None).await.is_err());
19739        drop(owner);
19740        drop(runner);
19741        let mut resumed = Runner::resume(&id).unwrap();
19742        assert_eq!(resumed.state.driver_claimed, Some(false));
19743        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Dead);
19744        assert_eq!(resumed.state.liveness(true), crate::run::Liveness::Live);
19745        let mut execution = resumed
19746            .claim_driver(None)
19747            .await
19748            .expect("retry initial claim after reload");
19749        assert_eq!(execution.runner.state.driver_claimed, Some(true));
19750        assert_eq!(execution.runner.state.passes.len(), 1);
19751        execution
19752            .driver
19753            .finish(&mut execution.runner.state)
19754            .await
19755            .unwrap();
19756    }
19757
19758    #[tokio::test]
19759    async fn driver_admission_preclaim_marker_does_not_bypass_an_execution_lease() {
19760        crate::run::pin_test_home();
19761        let mut runner = runner_at(RunStatus::Reviewing);
19762        runner.state.config.agents = vec![conductor()];
19763        runner.state.save().unwrap();
19764        let id = runner.state.id.clone();
19765        let lease = crate::driver::maintenance(&crate::run::home(), &id).unwrap();
19766        let mut resumed = Runner::resume(&id).unwrap();
19767        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Live);
19768        assert!(resumed.claim_driver(None).await.is_err());
19769        assert!(RunState::load(&id).unwrap().passes.is_empty());
19770        drop(lease);
19771        let mut execution = resumed.claim_driver(None).await.unwrap();
19772        execution
19773            .driver
19774            .finish(&mut execution.runner.state)
19775            .await
19776            .unwrap();
19777    }
19778
19779    #[tokio::test]
19780    async fn driver_admission_accepts_legacy_unknown_process_with_a_proven_free_pass_lease() {
19781        crate::run::pin_test_home();
19782        let mut runner = runner_at(RunStatus::Reviewing);
19783        let state = &mut runner.state;
19784        state.config.agents = vec![conductor()];
19785        state.driver_claimed = None;
19786        state.driver_pid = Some(std::process::id());
19787        state.driver_started_at = None;
19788        state.begin_pass();
19789        state.save().unwrap();
19790        let lease = crate::driver::maintenance(&crate::run::home(), &state.id).unwrap();
19791        std::fs::write(
19792            state.dir().join("driver.json"),
19793            serde_json::to_vec(&serde_json::json!({
19794                "pid": state.driver_pid, "started_at": null,
19795                "pass": state.passes[0].started_at, "pass_index": state.passes[0].index,
19796            }))
19797            .unwrap(),
19798        )
19799        .unwrap();
19800        assert_eq!(state.liveness(false), crate::run::Liveness::Live);
19801        drop(lease);
19802        assert_eq!(state.liveness(false), crate::run::Liveness::Dead);
19803        let mut resumed = Runner::resume(&state.id).unwrap();
19804        assert!(!resumed.state.driver_exited);
19805        let mut execution = resumed
19806            .claim_driver(None)
19807            .await
19808            .expect("lease proves previous execution ended");
19809        assert_eq!(execution.runner.state.passes.len(), 2);
19810        execution
19811            .driver
19812            .finish(&mut execution.runner.state)
19813            .await
19814            .unwrap();
19815    }
19816
19817    #[tokio::test]
19818    async fn driver_admission_admits_a_legacy_record_without_a_claim_marker() {
19819        crate::run::pin_test_home();
19820        let mut runner = runner_at(RunStatus::Reviewing);
19821        let mut json = serde_json::to_value(&runner.state).unwrap();
19822        json.as_object_mut().unwrap().remove("driver_claimed");
19823        runner.state = serde_json::from_value(json).unwrap();
19824        assert_eq!(runner.state.driver_claimed, None);
19825        runner.state.save().unwrap();
19826        let mut execution = runner
19827            .claim_driver(None)
19828            .await
19829            .expect("the execution lease, not a missing marker, excludes a second driver");
19830        assert_eq!(execution.runner.state.passes.len(), 1);
19831        execution
19832            .driver
19833            .finish(&mut execution.runner.state)
19834            .await
19835            .unwrap();
19836    }
19837
19838    #[tokio::test]
19839    async fn driver_admission_refuses_a_proven_live_driver() {
19840        crate::run::pin_test_home();
19841        let mut runner = runner_at(RunStatus::Reviewing);
19842        let pid = std::process::id();
19843        runner.state.driver_pid = Some(pid);
19844        runner.state.driver_started_at = crate::proc::process_started_at(pid);
19845        assert!(runner.state.driver_started_at.is_some());
19846        runner.state.save().unwrap();
19847        let error = runner
19848            .claim_driver(None)
19849            .await
19850            .err()
19851            .expect("a live driver must refuse");
19852        assert!(error.to_string().contains("live driver"), "{error:#}");
19853        let saved = RunState::load(&runner.state.id).unwrap();
19854        assert_eq!(saved.driver_pid, Some(pid));
19855        assert_eq!(saved.status, RunStatus::Reviewing);
19856        assert!(saved.passes.is_empty());
19857    }
19858
19859    #[test]
19860    fn parking_resource_halt_persists_the_pass_once() {
19861        crate::run::pin_test_home();
19862        let mut runner = runner_at(RunStatus::Reviewing);
19863        runner.state.begin_pass();
19864        runner.state.resource_block = Some(crate::run::ResourceBlock {
19865            node: "fix".into(),
19866            kind: "shared build cache".into(),
19867            detail: "cancelled".into(),
19868            at: Timestamp::now(),
19869            cause: crate::run::ResourceBlockCause::Cancelled { park: None },
19870        });
19871        let cause = ParkCause::Upgrade {
19872            from: "old".into(),
19873            to: Some("new".into()),
19874        };
19875        runner.pause.park_for(cause.clone());
19876        // Both direct fixer exits and graph resource boundaries must complete
19877        // parking, rather than returning a stale Reviewing record.
19878        runner.stop_for_resource().unwrap();
19879        assert!(runner.resource_halt().unwrap());
19880        assert!(runner.park_here().unwrap());
19881        let saved = RunState::load(&runner.state.id).unwrap();
19882        assert!(saved.parked);
19883        assert_eq!(saved.status, RunStatus::Reviewing);
19884        assert!(saved.passes[0].ended_at.is_some());
19885        assert_eq!(
19886            saved.passes[0].end,
19887            Some(crate::run::PassEnd::Parked {
19888                cause: cause.clone()
19889            })
19890        );
19891        assert_eq!(
19892            saved.resource_block.unwrap().cause,
19893            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
19894        );
19895        assert_eq!(
19896            saved
19897                .events
19898                .iter()
19899                .filter(|event| event.node == "park")
19900                .count(),
19901            1
19902        );
19903    }
19904
19905    /// `watch_interrupt` and `on_pause` are genuinely independent: an ordinary
19906    /// shutdown `Pause` (what `Stop::park` hands every run, shared and never
19907    /// cleared) must not make a *different* run - one only watching its own,
19908    /// unshared interrupt `Pause` - see itself as parked. If a future change
19909    /// ever collapsed these back into one handle, the interrupt scheduler
19910    /// would park every run for the rest of the daemon's life, not just the
19911    /// one it meant to interrupt.
19912    #[test]
19913    fn the_stop_level_pause_and_a_runs_interrupt_pause_do_not_leak_into_each_other() {
19914        crate::run::pin_test_home();
19915        let mut runner = runner_at(RunStatus::Implementing);
19916        let shutdown = Pause::new();
19917        runner.on_pause(shutdown.clone());
19918        let interrupt = Pause::new();
19919        runner.watch_interrupt(interrupt.clone());
19920
19921        // Nobody has asked for anything yet.
19922        assert!(!runner.park_here().expect("park_here"));
19923        assert!(!runner.state.parked);
19924
19925        // Only the interrupt handle fires; the shutdown handle stays clear.
19926        interrupt.park_because("test");
19927        assert!(!shutdown.parked());
19928        assert!(runner.park_here().expect("park_here"));
19929    }
19930
19931    /// The property every prior attempt at this feature failed to pin down:
19932    /// asking a run to park while one of its nodes has a real, in-flight
19933    /// async operation running (an agent call, in production) must not cut
19934    /// that operation short. `park_here` is only ever consulted *between*
19935    /// `execute`'s node calls - see its own doc - so nothing inside a node
19936    /// can observe a park request until the node itself returns. This proves
19937    /// that structurally, with real `tokio` concurrency and a channel
19938    /// handshake (never a sleep, which would only prove "usually", not
19939    /// "cannot"): the "node" below reports that it has genuinely started,
19940    /// and only then is the park requested; the node still has to be told to
19941    /// finish before `park_here` is ever called, exactly mirroring every
19942    /// `self.some_node().await; if self.park_here()? { return Ok(()); }` pair
19943    /// in `execute`.
19944    #[tokio::test]
19945    async fn a_park_request_made_mid_node_only_takes_effect_at_the_next_boundary() {
19946        crate::run::pin_test_home();
19947        let mut runner = runner_at(RunStatus::Implementing);
19948        let interrupt = Pause::new();
19949        runner.watch_interrupt(interrupt.clone());
19950
19951        let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>();
19952        let (finish_tx, finish_rx) = tokio::sync::oneshot::channel::<()>();
19953
19954        // Stands in for one node's in-flight agent call: it proves it has
19955        // genuinely started, then blocks - exactly as a spawned CLI process
19956        // does - until told to finish.
19957        let node = async move {
19958            started_tx.send(()).expect("send started");
19959            finish_rx.await.expect("recv finish");
19960            "node finished"
19961        };
19962
19963        let interrupter = async move {
19964            started_rx.await.expect("recv started");
19965            // The call is now genuinely in flight. Ask it to park.
19966            interrupt.park_because("higher-priority task waiting");
19967            // Nothing the node does can observe this yet - there is no
19968            // check inside it, by construction - so let the executor run
19969            // anything pending and then let the node finish on its own.
19970            tokio::task::yield_now().await;
19971            finish_tx.send(()).expect("send finish");
19972        };
19973
19974        let (node_result, ()) = tokio::join!(node, interrupter);
19975        assert_eq!(
19976            node_result, "node finished",
19977            "the in-flight call ran to completion"
19978        );
19979
19980        // Only now, at the boundary the real `execute` would check right
19981        // after this node, does the park take effect.
19982        assert!(runner.park_here().expect("park_here"));
19983        assert!(runner.state.parked);
19984    }
19985
19986    /// A run parked mid-competition carries every field it had accumulated
19987    /// through the exact same disk round-trip an ordinary resume uses -
19988    /// `RunState::save`/`RunState::load`, which is all `Runner::resume` is.
19989    /// Nothing about parking for an interrupt is a special case of that path;
19990    /// this is what proves it rather than assuming it.
19991    #[test]
19992    fn a_run_parked_for_an_interrupt_resumes_with_nothing_lost() {
19993        crate::run::pin_test_home();
19994        let mut runner = runner_at(RunStatus::Judging);
19995        // `Runner::resume` re-resolves roles from the saved config, which
19996        // refuses an empty roster - give it the same minimal one `conductor`
19997        // itself uses.
19998        runner.state.config.agents = vec![conductor()];
19999        runner.state.candidates = vec![Candidate {
20000            index: 0,
20001            label: 'A',
20002            agent: "alpha".to_owned(),
20003            branch: "magi/x/A".to_owned(),
20004            worktree: PathBuf::from("/nonexistent/worktree"),
20005            summary: "did the thing".to_owned(),
20006            stat: "1 file changed".to_owned(),
20007            files: 1,
20008            commits: 1,
20009            empty: false,
20010            failed: None,
20011            verified_noop: None,
20012            duration_ms: 1234,
20013            folded: false,
20014        }];
20015        let run_id = runner.state.id.clone();
20016
20017        let interrupt = Pause::new();
20018        runner.watch_interrupt(interrupt.clone());
20019        interrupt.park_because("task c3d4 asked to run first");
20020        assert!(runner.park_here().expect("park_here"));
20021
20022        let resumed = Runner::resume(&run_id).expect("resume");
20023        assert_eq!(resumed.state.candidates.len(), 1);
20024        assert_eq!(resumed.state.candidates[0].summary, "did the thing");
20025        assert_eq!(resumed.state.candidates[0].branch, "magi/x/A");
20026        assert_eq!(resumed.state.status, runner.state.status);
20027        assert!(
20028            resumed.state.parked,
20029            "still parked until `execute` actually walks the graph again"
20030        );
20031        assert!(resumed.state.events.iter().any(|e| e.node == "park"));
20032    }
20033
20034    /// A fresh open question on `run`, stored and handed back for assertions.
20035    fn ask_open_question(store: &ask::Questions, run: &str) -> ask::Question {
20036        let mut q = ask::Question::new(
20037            run.to_owned(),
20038            "implement".to_owned(),
20039            "impl-A".to_owned(),
20040            "Which storage backend should the cache use?".to_owned(),
20041            String::new(),
20042            vec!["SQLite".to_owned(), "Redis".to_owned()],
20043        );
20044        store.put(&mut q).unwrap();
20045        q
20046    }
20047
20048    #[test]
20049    fn a_failed_runs_open_question_is_abandoned() {
20050        ask_test_home();
20051        let store = ask::Questions::open();
20052        let mut runner = runner_at(RunStatus::Failed);
20053        let run = runner.state.id.clone();
20054        let q = ask_open_question(&store, &run);
20055
20056        runner.settle_questions();
20057
20058        let back = store.get(&q.id).unwrap();
20059        assert!(
20060            !back.status.open(),
20061            "the seat that asked died with the run; nobody is left to read an answer"
20062        );
20063        assert!(
20064            back.detail.contains(&run) && back.detail.contains("failed"),
20065            "the reason names what the run became, not just that it is gone: {}",
20066            back.detail
20067        );
20068    }
20069
20070    #[test]
20071    fn a_merged_runs_open_question_is_abandoned_too() {
20072        ask_test_home();
20073        let store = ask::Questions::open();
20074        // A run that finishes cleanly still leaves nobody to read an answer -
20075        // this is not only a failure-path cleanup.
20076        for status in [RunStatus::Merged, RunStatus::Ready] {
20077            let mut runner = runner_at(status);
20078            let run = runner.state.id.clone();
20079            let q = ask_open_question(&store, &run);
20080
20081            runner.settle_questions();
20082
20083            let back = store.get(&q.id).unwrap();
20084            assert!(
20085                !back.status.open(),
20086                "{status:?} run's question must not outlive the run"
20087            );
20088        }
20089    }
20090
20091    #[test]
20092    fn a_still_resumable_runs_open_question_is_left_alone() {
20093        ask_test_home();
20094        let store = ask::Questions::open();
20095        // `Blocked` and `Stalled` can still be resumed — the candidates, the
20096        // review round and the seat sessions are all still on disk — so a
20097        // question asked mid-round may yet get a real answer from a real
20098        // resume. Sweeping it here would be exactly the failure mode this
20099        // whole feature exists to avoid on the other side.
20100        for status in [RunStatus::Blocked, RunStatus::Stalled] {
20101            let mut runner = runner_at(status);
20102            let run = runner.state.id.clone();
20103            let q = ask_open_question(&store, &run);
20104
20105            runner.settle_questions();
20106
20107            let back = store.get(&q.id).unwrap();
20108            assert!(
20109                back.status.open(),
20110                "{status:?} is still alive; the question must still be waiting"
20111            );
20112        }
20113    }
20114
20115    #[test]
20116    fn settle_questions_never_touches_an_already_answered_question() {
20117        ask_test_home();
20118        let store = ask::Questions::open();
20119        let mut runner = runner_at(RunStatus::Failed);
20120        let run = runner.state.id.clone();
20121        let mut q = ask_open_question(&store, &run);
20122        q.answer(crate::ask::Answer::Choice("SQLite".to_owned()))
20123            .unwrap();
20124        store.put(&mut q).unwrap();
20125
20126        // Called twice, the way a crash-recovered daemon reclaim and the
20127        // graph's own cleanup both can for the same run — `abandon_for_run`
20128        // only ever touches what is still open, so this must be inert both
20129        // times, not merely the second.
20130        runner.settle_questions();
20131        runner.settle_questions();
20132
20133        let back = store.get(&q.id).unwrap();
20134        assert_eq!(
20135            back.status,
20136            ask::QuestionStatus::Answered,
20137            "a real answer is a decision on record, never overwritten by a sweep"
20138        );
20139    }
20140
20141    #[tokio::test]
20142    async fn fold_reclaims_only_proven_idle_isolated_outputs() {
20143        let tmp = tempfile::tempdir().unwrap();
20144        let home = tmp.path().join("home");
20145        let repo = tmp.path().join("repo");
20146        std::fs::create_dir(&home).unwrap();
20147        std::fs::create_dir(&repo).unwrap();
20148        init_repo(&repo);
20149
20150        let mut config = Config::default();
20151        config.graph.worktree_root = Some(tmp.path().join("wt"));
20152        config.verify.build_cache = crate::config::BuildCache::Isolated;
20153        let mut state = RunState::new(
20154            repo.clone(),
20155            "main".into(),
20156            "base".into(),
20157            "fold fixture".into(),
20158            config,
20159        );
20160        let root = state.worktree_root();
20161        let mut outputs = Vec::new();
20162        for name in ["idle", "busy"] {
20163            let checkout = root.join(name);
20164            git::worktree_add_detached(&repo, &checkout, "main")
20165                .await
20166                .unwrap();
20167            let target = crate::build_target::resolve(&home, &checkout).unwrap();
20168            let output = target.join("generated");
20169            std::fs::write(&output, name).unwrap();
20170            outputs.push((target, output));
20171        }
20172        let unknown = crate::build_target::root(&home)
20173            .join("00000000-0000-0000-0000-000000000000")
20174            .join("target");
20175        std::fs::create_dir_all(&unknown).unwrap();
20176        let unowned = unknown.join("generated");
20177        std::fs::write(&unowned, "keep").unwrap();
20178        let owner = crate::cache::Owner::here("fixture", "build", "busy", &root.join("busy"), "");
20179        let crate::cache::AcquireOutcome::Acquired(_lease) =
20180            crate::cache::try_acquire(&home, &outputs[1].0, &owner).unwrap()
20181        else {
20182            panic!("fixture target must be free");
20183        };
20184
20185        fold_run(&mut state, true, &home).await.unwrap();
20186        assert!(!root.exists());
20187        assert!(!outputs[0].1.exists());
20188        assert!(outputs[1].1.is_file());
20189        assert!(unowned.is_file());
20190    }
20191
20192    /// `fold_run(&mut state, drop_winner = false)` is exactly the call
20193    /// `clean::fold_due` makes for a `Ready`/`Failed` run - one that finished
20194    /// without merging, whose winner is still the operator's answer to read.
20195    /// Nothing previously called `fold_run` itself with a real `tally`, so
20196    /// this is the first test to pin down the one distinction the whole
20197    /// automatic-fold feature depends on: the winner's worktree and branch
20198    /// must survive, everything else sharing the run's worktree bay - a
20199    /// loser, standing in for a judge/review worktree too, since `fold_run`'s
20200    /// second sweep treats every non-winner directory under the bay alike -
20201    /// must not.
20202    #[tokio::test]
20203    async fn fold_run_keeps_only_the_winner_when_the_winner_is_not_dropped() {
20204        crate::run::pin_test_home();
20205        let tmp = tempfile::tempdir().expect("tempdir");
20206        let repo = tmp.path().join("repo");
20207        std::fs::create_dir_all(&repo).unwrap();
20208        init_repo(&repo);
20209
20210        let mut config = Config::default();
20211        config.graph.worktree_root = Some(tmp.path().join("wt"));
20212
20213        let mut state = RunState::new(
20214            repo.clone(),
20215            "main".to_owned(),
20216            "deadbeef".to_owned(),
20217            "task".to_owned(),
20218            config,
20219        );
20220        let root = state.worktree_root();
20221        let wt_a = root.join("cand-A");
20222        let wt_b = root.join("cand-B");
20223        git::worktree_add_branch(&repo, &wt_a, "magi/x/A", "main")
20224            .await
20225            .expect("worktree A");
20226        git::worktree_add_branch(&repo, &wt_b, "magi/x/B", "main")
20227            .await
20228            .expect("worktree B");
20229
20230        state.candidates = vec![
20231            Candidate {
20232                index: 0,
20233                label: 'A',
20234                agent: "alpha".to_owned(),
20235                branch: "magi/x/A".to_owned(),
20236                worktree: wt_a.clone(),
20237                summary: String::new(),
20238                stat: String::new(),
20239                files: 0,
20240                commits: 0,
20241                empty: false,
20242                failed: None,
20243                verified_noop: None,
20244                duration_ms: 0,
20245                folded: false,
20246            },
20247            Candidate {
20248                index: 1,
20249                label: 'B',
20250                agent: "beta".to_owned(),
20251                branch: "magi/x/B".to_owned(),
20252                worktree: wt_b.clone(),
20253                summary: String::new(),
20254                stat: String::new(),
20255                files: 0,
20256                commits: 0,
20257                empty: false,
20258                failed: None,
20259                verified_noop: None,
20260                duration_ms: 0,
20261                folded: false,
20262            },
20263        ];
20264        state.tally = Some(Tally {
20265            first_choice: BTreeMap::from([('A', 1)]),
20266            borda: BTreeMap::new(),
20267            winner: 'A',
20268            rankings: 1,
20269            unanimous_initial: true,
20270            deliberated: false,
20271            changed_votes: 0,
20272            unanimous_final: true,
20273            tie_break: None,
20274            judges: 1,
20275            present: 1,
20276            quorum: 1,
20277            met_quorum: true,
20278            uncontested: None,
20279        });
20280        state.status = RunStatus::Ready;
20281
20282        fold_run(&mut state, false, &crate::run::home())
20283            .await
20284            .expect("fold_run");
20285
20286        assert!(wt_a.exists(), "the unmerged winner's worktree survives");
20287        assert!(
20288            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
20289            "the unmerged winner's branch survives"
20290        );
20291        assert!(
20292            !state.candidates[0].folded,
20293            "the winner is not marked folded"
20294        );
20295
20296        assert!(!wt_b.exists(), "the loser's worktree is removed");
20297        assert!(
20298            !git::branch_exists(&repo, "magi/x/B").await.unwrap(),
20299            "the loser's branch is removed"
20300        );
20301        assert!(state.candidates[1].folded, "the loser is marked folded");
20302    }
20303
20304    #[tokio::test]
20305    #[cfg(unix)]
20306    async fn fold_run_waits_for_shared_lock_before_removing_worktrees_branches_or_config() {
20307        use std::os::fd::AsRawFd as _;
20308        use std::time::Duration;
20309
20310        let tmp = tempfile::tempdir().unwrap();
20311        let repo = tmp.path().join("repo");
20312        std::fs::create_dir_all(&repo).unwrap();
20313        init_repo(&repo);
20314        let common = repo.join(".git");
20315        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
20316        let home = tmp.path().join("home");
20317        let mut config = Config::default();
20318        config.coordination = crate::config::test_coordination();
20319        config.graph.worktree_root = Some(tmp.path().join("wt"));
20320        config.graph.timeout_resource_wait = 1;
20321        let mut state = RunState::new(
20322            repo.clone(),
20323            "main".into(),
20324            "deadbeef".into(),
20325            "task".into(),
20326            config,
20327        );
20328        let root = state.worktree_root();
20329        let candidate = root.join("cand-A");
20330        let reviewer = root.join("review-1");
20331        let branch = state.branch_for('A');
20332        git::worktree_add_branch(&repo, &candidate, &branch, "main")
20333            .await
20334            .unwrap();
20335        git::worktree_add_detached(&repo, &reviewer, "main")
20336            .await
20337            .unwrap();
20338        git::acquire_worktree_config(&repo).await.unwrap();
20339        state.enabled_worktree_config = true;
20340        state.status = RunStatus::Ready;
20341        state.candidates.push(Candidate {
20342            index: 0,
20343            label: 'A',
20344            agent: "implement".into(),
20345            branch: branch.clone(),
20346            worktree: candidate.clone(),
20347            summary: String::new(),
20348            stat: String::new(),
20349            files: 0,
20350            commits: 0,
20351            empty: false,
20352            failed: None,
20353            verified_noop: None,
20354            duration_ms: 0,
20355            folded: false,
20356        });
20357        state.save_under(&home).unwrap();
20358        let config_before = std::fs::read(common.join("config")).unwrap();
20359        let worktrees_before = git::git(&repo, &["worktree", "list", "--porcelain"])
20360            .await
20361            .unwrap();
20362        // A separate OS handle bypasses the launcher's local gate, exactly as
20363        // an external updater does, and must still prevent all folding work.
20364        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
20365        assert_eq!(
20366            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
20367            0
20368        );
20369        let mut fold = Box::pin(fold_run(&mut state, true, &home));
20370        assert!(
20371            tokio::time::timeout(Duration::from_millis(200), &mut fold)
20372                .await
20373                .is_err()
20374        );
20375        assert!(candidate.exists());
20376        assert!(reviewer.exists());
20377        assert!(git::branch_exists(&repo, &branch).await.unwrap());
20378        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
20379        assert_eq!(
20380            git::git(&repo, &["worktree", "list", "--porcelain"])
20381                .await
20382                .unwrap(),
20383            worktrees_before
20384        );
20385        let error = tokio::time::timeout(Duration::from_secs(3), &mut fold)
20386            .await
20387            .unwrap()
20388            .unwrap_err();
20389        assert!(error.is::<crate::repo_lock::ResourceBlocked>());
20390        drop(fold);
20391        assert!(candidate.exists() && reviewer.exists());
20392        assert!(!state.candidates[0].folded && state.enabled_worktree_config);
20393        assert_eq!(
20394            state.resource_block.as_ref().unwrap().kind,
20395            "repository coordination"
20396        );
20397        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
20398        drop(external);
20399        let mut fold = Box::pin(fold_run(&mut state, true, &home));
20400        let removed = tokio::time::timeout(Duration::from_secs(10), &mut fold)
20401            .await
20402            .unwrap()
20403            .unwrap();
20404        drop(fold);
20405        assert!(removed.contains(&branch));
20406        assert!(!root.exists());
20407        assert!(!git::branch_exists(&repo, &branch).await.unwrap());
20408        assert!(state.candidates[0].folded);
20409        assert!(!state.enabled_worktree_config);
20410        assert_ne!(std::fs::read(common.join("config")).unwrap(), config_before);
20411        let enabled = git::git_raw(
20412            &repo,
20413            &["config", "--local", "--get", "extensions.worktreeConfig"],
20414        )
20415        .await
20416        .unwrap();
20417        assert!(!enabled.ok(), "the last config reference was released");
20418    }
20419
20420    /// A branch handed to a later run is that run's (and its pull request's):
20421    /// folding the run that released it must not delete it.
20422    #[tokio::test]
20423    async fn fold_run_keeps_a_branch_that_was_handed_to_a_later_run() {
20424        let tmp = tempfile::tempdir().expect("tempdir");
20425        let repo = tmp.path().join("repo");
20426        std::fs::create_dir_all(&repo).unwrap();
20427        init_repo(&repo);
20428        let home = tmp.path().join("home");
20429
20430        let mut config = Config::default();
20431        config.graph.worktree_root = Some(tmp.path().join("wt"));
20432        let mut state = RunState::new(
20433            repo.clone(),
20434            "main".to_owned(),
20435            "deadbeef".to_owned(),
20436            "task".to_owned(),
20437            config,
20438        );
20439        // The worktree is already gone (released); the branch survives.
20440        git::git(&repo, &["branch", "magi/x/A", "main"])
20441            .await
20442            .expect("branch");
20443        state.candidates = vec![Candidate {
20444            index: 0,
20445            label: 'A',
20446            agent: "alpha".to_owned(),
20447            branch: "magi/x/A".to_owned(),
20448            worktree: state.worktree_root().join("cand-A"),
20449            summary: String::new(),
20450            stat: String::new(),
20451            files: 0,
20452            commits: 0,
20453            empty: false,
20454            failed: None,
20455            verified_noop: None,
20456            duration_ms: 0,
20457            folded: true,
20458        }];
20459        state.released_to = Some("20260901-000000-new1".to_owned());
20460        state.released_branches = vec!["magi/x/A".to_owned()];
20461
20462        fold_run(&mut state, true, &home).await.expect("fold_run");
20463        state.status = RunStatus::Merged;
20464        state.base_commit = git::rev_parse(&repo, "main").await.unwrap();
20465        state.merge = Some(crate::run::MergeOutcome {
20466            mode: MergeMode::Pr,
20467            ok: true,
20468            detail: "confirmed merged".into(),
20469            empty: false,
20470        });
20471        fold_run(&mut state, true, &home)
20472            .await
20473            .expect("merged fold");
20474
20475        assert!(
20476            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
20477            "the handed-over branch survives a fold"
20478        );
20479    }
20480
20481    /// A winner with nothing ahead of the base is caught before `gh` is ever
20482    /// asked for a pull request, and the message carries what the task's
20483    /// references resolved to.
20484    #[tokio::test]
20485    async fn an_empty_winner_is_detected_before_a_pull_request_is_attempted() {
20486        let tmp = tempfile::tempdir().expect("tempdir");
20487        let repo = tmp.path().join("repo");
20488        std::fs::create_dir_all(&repo).unwrap();
20489        init_repo(&repo);
20490        let run = |args: &[&str]| {
20491            let out = std::process::Command::new("git")
20492                .quiet()
20493                .args(args)
20494                .current_dir(&repo)
20495                .output()
20496                .expect("spawn git");
20497            assert!(out.status.success(), "git {args:?}");
20498        };
20499        run(&["branch", "magi/x/A"]);
20500        run(&["checkout", "-q", "-b", "magi/x/B"]);
20501        std::fs::write(repo.join("f.txt"), "x\n").unwrap();
20502        run(&["add", "-A"]);
20503        run(&["commit", "-q", "-m", "work"]);
20504        run(&["checkout", "-q", "main"]);
20505
20506        // A pull request is compared against the remote's base, so the
20507        // fixture needs one. Before it exists nothing can be read, and the
20508        // answer must be "not empty".
20509        let probe = RunState::new(
20510            repo.clone(),
20511            "main".to_owned(),
20512            "deadbeef".to_owned(),
20513            "task".to_owned(),
20514            Config::default(),
20515        );
20516        assert!(!merge_is_empty(&repo, &probe, "magi/x/A", MergeMode::Pr).await);
20517        let bare = tmp.path().join("origin.git");
20518        let out = std::process::Command::new("git")
20519            .quiet()
20520            .args(["init", "-q", "--bare"])
20521            .arg(&bare)
20522            .output()
20523            .expect("spawn git");
20524        assert!(out.status.success(), "git init --bare");
20525        run(&["remote", "add", "origin", bare.to_str().unwrap()]);
20526        run(&["push", "-q", "origin", "main"]);
20527
20528        let mut state = RunState::new(
20529            repo.clone(),
20530            "main".to_owned(),
20531            "deadbeef".to_owned(),
20532            "task".to_owned(),
20533            Config::default(),
20534        );
20535        state.seeds = vec![refs::Seed {
20536            token: "magi/27b2/A".to_owned(),
20537            kind: refs::SeedKind::Unresolved,
20538            sha: String::new(),
20539            branch: true,
20540            detail: "no branch or commit named magi/27b2/A".to_owned(),
20541        }];
20542
20543        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Pr).await);
20544        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Local).await);
20545        assert!(!merge_is_empty(&repo, &state, "magi/x/B", MergeMode::Pr).await);
20546        let detail = empty_candidate_detail(&state, "main");
20547        assert!(detail.starts_with("empty candidate"), "{detail}");
20548        assert!(!detail.contains("magi/27b2/A"), "{detail}");
20549        assert!(detail.contains("--start-from"), "{detail}");
20550    }
20551
20552    /// `status == Ready` used to be read as "this is the harmless
20553    /// `MergeMode::None` no-op path, nothing to guard" (graph.rs, prior to
20554    /// this test). But `land` sets the very same status when a `MergeMode::Pr`
20555    /// run's PR was closed without merging — and reentering `merge` with
20556    /// `mode` still `Pr` does not know the difference, so it pushed and
20557    /// opened a second pull request. `mode == Local` reproduces the same
20558    /// blind spot without a network call: reentry must not attempt another
20559    /// git merge once this node has already recorded an outcome.
20560    #[tokio::test]
20561    async fn merge_does_not_reattempt_once_a_run_has_concluded() {
20562        let tmp = tempfile::tempdir().expect("tempdir");
20563        let repo = tmp.path().join("repo");
20564        std::fs::create_dir_all(&repo).unwrap();
20565        init_repo(&repo);
20566
20567        let mut config = Config::default();
20568        config.merge.mode = MergeMode::Local;
20569
20570        let mut state = RunState::new(
20571            repo.clone(),
20572            "main".to_owned(),
20573            "deadbeef".to_owned(),
20574            "task".to_owned(),
20575            config,
20576        );
20577        state.candidates = vec![Candidate {
20578            index: 0,
20579            label: 'A',
20580            agent: "alpha".to_owned(),
20581            branch: "does-not-exist".to_owned(),
20582            worktree: repo.clone(),
20583            summary: String::new(),
20584            stat: String::new(),
20585            files: 0,
20586            commits: 0,
20587            empty: false,
20588            failed: None,
20589            verified_noop: None,
20590            duration_ms: 0,
20591            folded: false,
20592        }];
20593        state.tally = Some(Tally {
20594            first_choice: BTreeMap::from([('A', 1)]),
20595            borda: BTreeMap::new(),
20596            winner: 'A',
20597            rankings: 1,
20598            unanimous_initial: true,
20599            deliberated: false,
20600            changed_votes: 0,
20601            unanimous_final: true,
20602            tie_break: None,
20603            judges: 0,
20604            present: 0,
20605            quorum: 0,
20606            met_quorum: true,
20607            uncontested: Some("only candidate A produced a change".to_owned()),
20608        });
20609        state.reviews = vec![ReviewRound {
20610            round: 1,
20611            head: "deadbeef".to_owned(),
20612            verified_head: None,
20613            verified_at: None,
20614            reviews: Vec::new(),
20615            e2e: Vec::new(),
20616            fix: None,
20617            blocking: 0,
20618            answered: 0,
20619            expected: 0,
20620            clean: true,
20621            verify_retried: false,
20622            e2e_deferred: false,
20623            e2e_defer_reason: None,
20624            progressed: false,
20625            vote_split: false,
20626            reconsideration: Vec::new(),
20627            verdict: None,
20628        }];
20629        state.gate = vec![CommandOutcome {
20630            command: "test".to_owned(),
20631            code: Some(0),
20632            output_tail: String::new(),
20633            duration_ms: 0,
20634            resource_blocked: false,
20635        }];
20636        state.gate_ran = true;
20637        // Reached its conclusion already — e.g. `land` closing the PR without
20638        // merging it, which (like the honest `MergeMode::None` path) leaves
20639        // `status` at `Ready`. The recorded outcome is what actually marks
20640        // this node done.
20641        state.status = RunStatus::Ready;
20642        state.merge = Some(MergeOutcome {
20643            mode: MergeMode::Local,
20644            ok: false,
20645            detail: "already concluded".to_owned(),
20646            empty: false,
20647        });
20648
20649        let mut runner = Runner {
20650            state,
20651            roles: ResolvedRoles {
20652                implementers: Vec::new(),
20653                judges: Vec::new(),
20654                reviewers: Vec::new(),
20655                fixer: None,
20656                conductor: conductor(),
20657                implementer_roster: Vec::new(),
20658                judge_roster: Vec::new(),
20659                reviewer_roster: Vec::new(),
20660            },
20661            sem: Arc::new(Semaphore::new(1)),
20662            pause: Pause::new(),
20663            interrupt: Pause::new(),
20664        };
20665
20666        runner.merge().await.expect("merge");
20667
20668        assert_eq!(
20669            runner.state.status,
20670            RunStatus::Ready,
20671            "a concluded run's status must not change on reentry"
20672        );
20673        assert_eq!(
20674            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
20675            Some("already concluded"),
20676            "merge must not run again once the node already recorded an outcome"
20677        );
20678    }
20679
20680    /// `gate` leaves `state.gate_ran` false both before it has ever run and
20681    /// when its last attempt was resource-blocked (the shared build cache
20682    /// could not be acquired or confirmed fresh in time - see
20683    /// `CommandOutcome::resource_blocked`'s own doc). Trusting the empty
20684    /// `Vec` this also leaves behind used to read as "nothing failed" and let
20685    /// a run merge a tree the gate never actually checked - exactly the case
20686    /// a contended cache produces on every retry until it clears. `merge`
20687    /// must refuse until `gate` has actually recorded an attempt.
20688    #[tokio::test]
20689    async fn merge_refuses_a_gate_that_has_not_actually_run() {
20690        let tmp = tempfile::tempdir().expect("tempdir");
20691        let repo = tmp.path().join("repo");
20692        std::fs::create_dir_all(&repo).unwrap();
20693        init_repo(&repo);
20694
20695        let mut config = Config::default();
20696        config.merge.mode = MergeMode::Local;
20697
20698        let mut state = RunState::new(
20699            repo.clone(),
20700            "main".to_owned(),
20701            "deadbeef".to_owned(),
20702            "task".to_owned(),
20703            config,
20704        );
20705        state.candidates = vec![Candidate {
20706            index: 0,
20707            label: 'A',
20708            agent: "alpha".to_owned(),
20709            branch: "does-not-exist".to_owned(),
20710            worktree: repo.clone(),
20711            summary: String::new(),
20712            stat: String::new(),
20713            files: 0,
20714            commits: 0,
20715            empty: false,
20716            failed: None,
20717            verified_noop: None,
20718            duration_ms: 0,
20719            folded: false,
20720        }];
20721        state.tally = Some(Tally {
20722            first_choice: BTreeMap::from([('A', 1)]),
20723            borda: BTreeMap::new(),
20724            winner: 'A',
20725            rankings: 1,
20726            unanimous_initial: true,
20727            deliberated: false,
20728            changed_votes: 0,
20729            unanimous_final: true,
20730            tie_break: None,
20731            judges: 0,
20732            present: 0,
20733            quorum: 0,
20734            met_quorum: true,
20735            uncontested: Some("only candidate A produced a change".to_owned()),
20736        });
20737        state.reviews = vec![ReviewRound {
20738            round: 1,
20739            head: "deadbeef".to_owned(),
20740            verified_head: None,
20741            verified_at: None,
20742            reviews: Vec::new(),
20743            e2e: Vec::new(),
20744            fix: None,
20745            blocking: 0,
20746            answered: 0,
20747            expected: 0,
20748            clean: true,
20749            verify_retried: false,
20750            e2e_deferred: false,
20751            e2e_defer_reason: None,
20752            progressed: false,
20753            vote_split: false,
20754            reconsideration: Vec::new(),
20755            verdict: None,
20756        }];
20757        // The point: `gate` has not recorded anything yet.
20758        state.gate = Vec::new();
20759        state.gate_ran = false;
20760        state.status = RunStatus::Gating;
20761
20762        let mut runner = Runner {
20763            state,
20764            roles: ResolvedRoles {
20765                implementers: Vec::new(),
20766                judges: Vec::new(),
20767                reviewers: Vec::new(),
20768                fixer: None,
20769                conductor: conductor(),
20770                implementer_roster: Vec::new(),
20771                judge_roster: Vec::new(),
20772                reviewer_roster: Vec::new(),
20773            },
20774            sem: Arc::new(Semaphore::new(1)),
20775            pause: Pause::new(),
20776            interrupt: Pause::new(),
20777        };
20778
20779        runner.merge().await.expect("merge");
20780
20781        assert!(
20782            runner.state.merge.is_none(),
20783            "an empty gate must never be read as a passing one: {:?}",
20784            runner.state.merge
20785        );
20786    }
20787
20788    /// The `shoka` repro this schema bump exists for: `verify.gate` has no
20789    /// commands configured and `merge.mode` is `none` (a review-only run).
20790    /// `gate` must still record a real attempt — zero commands, vacuously
20791    /// passed — rather than leaving `state.gate` empty in a way `merge`
20792    /// cannot tell apart from "never ran"; otherwise the run reaches
20793    /// `Gating` and can never leave it. See `RunState::gate_ran`'s own doc.
20794    #[tokio::test]
20795    async fn gate_and_merge_reach_ready_when_no_gate_commands_are_configured() {
20796        let tmp = tempfile::tempdir().expect("tempdir");
20797        let repo = tmp.path().join("repo");
20798        std::fs::create_dir_all(&repo).unwrap();
20799        init_repo(&repo);
20800
20801        // Default config: `verify.gate` empty, `merge.mode` is `none`.
20802        let config = Config::default();
20803
20804        let mut state = RunState::new(
20805            repo.clone(),
20806            "main".to_owned(),
20807            "deadbeef".to_owned(),
20808            "task".to_owned(),
20809            config,
20810        );
20811        state.candidates = vec![Candidate {
20812            index: 0,
20813            label: 'A',
20814            agent: "alpha".to_owned(),
20815            branch: "does-not-exist".to_owned(),
20816            worktree: repo.clone(),
20817            summary: String::new(),
20818            stat: String::new(),
20819            files: 0,
20820            commits: 0,
20821            empty: false,
20822            failed: None,
20823            verified_noop: None,
20824            duration_ms: 0,
20825            folded: false,
20826        }];
20827        state.tally = Some(Tally {
20828            first_choice: BTreeMap::from([('A', 1)]),
20829            borda: BTreeMap::new(),
20830            winner: 'A',
20831            rankings: 1,
20832            unanimous_initial: true,
20833            deliberated: false,
20834            changed_votes: 0,
20835            unanimous_final: true,
20836            tie_break: None,
20837            judges: 0,
20838            present: 0,
20839            quorum: 0,
20840            met_quorum: true,
20841            uncontested: Some("only candidate A produced a change".to_owned()),
20842        });
20843        state.reviews = vec![ReviewRound {
20844            round: 1,
20845            head: "deadbeef".to_owned(),
20846            verified_head: None,
20847            verified_at: None,
20848            reviews: Vec::new(),
20849            e2e: Vec::new(),
20850            fix: None,
20851            blocking: 0,
20852            answered: 0,
20853            expected: 0,
20854            clean: true,
20855            verify_retried: false,
20856            e2e_deferred: false,
20857            e2e_defer_reason: None,
20858            progressed: false,
20859            vote_split: false,
20860            reconsideration: Vec::new(),
20861            verdict: None,
20862        }];
20863
20864        let mut runner = Runner {
20865            state,
20866            roles: ResolvedRoles {
20867                implementers: Vec::new(),
20868                judges: Vec::new(),
20869                reviewers: Vec::new(),
20870                fixer: None,
20871                conductor: conductor(),
20872                implementer_roster: Vec::new(),
20873                judge_roster: Vec::new(),
20874                reviewer_roster: Vec::new(),
20875            },
20876            sem: Arc::new(Semaphore::new(1)),
20877            pause: Pause::new(),
20878            interrupt: Pause::new(),
20879        };
20880
20881        runner.gate().await.expect("gate");
20882        assert!(
20883            runner.state.gate_ran,
20884            "zero configured commands is still a real attempt, not an unrun gate"
20885        );
20886        assert!(runner.state.gate.is_empty());
20887        assert_eq!(runner.state.gate_status(), GateStatus::NotConfigured);
20888        assert_ne!(
20889            runner.state.status,
20890            RunStatus::Blocked,
20891            "a gate with nothing to check must not read as failed"
20892        );
20893
20894        runner.merge().await.expect("merge");
20895        assert_eq!(
20896            runner.state.status,
20897            RunStatus::Ready,
20898            "a clean review-only run with no gate commands must reach Ready, not stay stuck in Gating"
20899        );
20900    }
20901
20902    /// `Config::cache_dir` is derived from `verify.e2e` as well as
20903    /// `verify.gate` (so the e2e leg and the final gate never build against
20904    /// different directories). With zero `verify.gate` commands but a
20905    /// `CARGO_TARGET_DIR`-using `verify.e2e`, `gate` used to still queue for
20906    /// that lease before discovering it had nothing to run - so a repo with
20907    /// no gate commands could come back `resource_blocked` (and therefore
20908    /// still `gate_ran == false`) on nothing but an unrelated run holding the
20909    /// cache, exactly the contention this run's own zero commands could
20910    /// never have touched. `gate` must recognise there is nothing to check
20911    /// before it ever asks for the lease.
20912    #[tokio::test]
20913    async fn gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run() {
20914        crate::run::pin_test_home();
20915        let home = crate::run::home();
20916
20917        let tmp = tempfile::tempdir().expect("tempdir");
20918        let repo = tmp.path().join("repo");
20919        std::fs::create_dir_all(&repo).unwrap();
20920        init_repo(&repo);
20921        // Unique to this test, so holding its lease cannot collide with
20922        // another test sharing the same process-wide `home`.
20923        let cache_dir = tmp.path().join("target");
20924
20925        let mut config = Config::default();
20926        config.verify.e2e = vec![format!("CARGO_TARGET_DIR='{}' true", cache_dir.display())];
20927        // `verify.gate` stays empty (the default). Any accidental cache
20928        // acquisition must report contention immediately, regardless of how
20929        // long unrelated Git subprocesses take under parallel test load.
20930        config.graph.timeout_verify = Some(2);
20931        config.graph.timeout_resource_wait = 0;
20932
20933        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
20934        let _held = match crate::cache::try_acquire(&home, &cache_dir, &other)
20935            .expect("no io error acquiring directly")
20936        {
20937            crate::cache::AcquireOutcome::Acquired(g) => g,
20938            crate::cache::AcquireOutcome::Busy(b) => {
20939                panic!("expected the direct acquire to win the lease first: {b:?}")
20940            }
20941        };
20942
20943        let mut state = RunState::new(
20944            repo.clone(),
20945            "main".to_owned(),
20946            "deadbeef".to_owned(),
20947            "task".to_owned(),
20948            config,
20949        );
20950        state.candidates = vec![Candidate {
20951            index: 0,
20952            label: 'A',
20953            agent: "alpha".to_owned(),
20954            branch: "does-not-exist".to_owned(),
20955            worktree: repo.clone(),
20956            summary: String::new(),
20957            stat: String::new(),
20958            files: 0,
20959            commits: 0,
20960            empty: false,
20961            failed: None,
20962            verified_noop: None,
20963            duration_ms: 0,
20964            folded: false,
20965        }];
20966        state.tally = Some(Tally {
20967            first_choice: BTreeMap::from([('A', 1)]),
20968            borda: BTreeMap::new(),
20969            winner: 'A',
20970            rankings: 1,
20971            unanimous_initial: true,
20972            deliberated: false,
20973            changed_votes: 0,
20974            unanimous_final: true,
20975            tie_break: None,
20976            judges: 0,
20977            present: 0,
20978            quorum: 0,
20979            met_quorum: true,
20980            uncontested: Some("only candidate A produced a change".to_owned()),
20981        });
20982        state.reviews = vec![ReviewRound {
20983            round: 1,
20984            head: "deadbeef".to_owned(),
20985            verified_head: None,
20986            verified_at: None,
20987            reviews: Vec::new(),
20988            e2e: Vec::new(),
20989            fix: None,
20990            blocking: 0,
20991            answered: 0,
20992            expected: 0,
20993            clean: true,
20994            verify_retried: false,
20995            e2e_deferred: false,
20996            e2e_defer_reason: None,
20997            progressed: false,
20998            vote_split: false,
20999            reconsideration: Vec::new(),
21000            verdict: None,
21001        }];
21002
21003        state.reviews[0].verified_head = Some(git::rev_parse(&repo, "HEAD").await.unwrap());
21004        state.reviews[0].e2e = vec![CommandOutcome {
21005            command: state.config.verify.e2e[0].clone(),
21006            code: Some(0),
21007            output_tail: String::new(),
21008            duration_ms: 0,
21009            resource_blocked: false,
21010        }];
21011        let mut runner = Runner {
21012            state,
21013            roles: ResolvedRoles {
21014                implementers: Vec::new(),
21015                judges: Vec::new(),
21016                reviewers: Vec::new(),
21017                fixer: None,
21018                conductor: conductor(),
21019                implementer_roster: Vec::new(),
21020                judge_roster: Vec::new(),
21021                reviewer_roster: Vec::new(),
21022            },
21023            sem: Arc::new(Semaphore::new(1)),
21024            pause: Pause::new(),
21025            interrupt: Pause::new(),
21026        };
21027
21028        runner.gate().await.expect("gate");
21029        assert!(runner.state.resource_block.is_none());
21030        assert!(
21031            !runner
21032                .state
21033                .events
21034                .iter()
21035                .any(|event| { event.message.contains("waiting for the shared build cache") }),
21036            "a gate with nothing to run must never request the held cache lease"
21037        );
21038        assert!(
21039            runner.state.gate_ran,
21040            "zero commands is still a real, immediate attempt"
21041        );
21042        assert!(runner.state.gate.is_empty());
21043        assert_ne!(
21044            runner.state.status,
21045            RunStatus::Blocked,
21046            "must not read as resource-blocked on a lease it never asked for"
21047        );
21048    }
21049
21050    /// A separate process carries a live worker's environment throughout all
21051    /// verification entry points; the parallel harness never changes its env.
21052    #[cfg(unix)]
21053    #[tokio::test]
21054    async fn verification_is_standalone_inside_a_live_worker() {
21055        const CHILD: &str = "MAGI_VERIFY_WORKER_TEST";
21056        if std::env::var_os(CHILD).is_none() {
21057            let home = tempfile::tempdir().unwrap();
21058            let generation = crate::worker::pin_current(home.path()).unwrap();
21059            let output = std::process::Command::new(std::env::current_exe().unwrap())
21060                .args([
21061                    "--exact",
21062                    "graph::tests::verification_is_standalone_inside_a_live_worker",
21063                    "--nocapture",
21064                ])
21065                .env(CHILD, "1")
21066                .env("MAGI_HOME", home.path())
21067                .env("MAGI_WORKER_HOME", home.path())
21068                .env("MAGI_WORKER_ID", "abcdef")
21069                .env("MAGI_WORKER_GENERATION", &generation.id)
21070                .env("MAGI_WORKER_EXE", &generation.executable)
21071                .env("MAGI_RUN", "verification-parent")
21072                .env("MAGI_NODE", "gate")
21073                .env("MAGI_SEAT", "worker-fixture")
21074                .env("MAGI_PROCESS_OWNER", "fixture-owner")
21075                .env("MAGI_NO_AUTOUPDATE", "0")
21076                .env("VERIFY_EXPECT_PATH", std::env::var_os("PATH").unwrap())
21077                .env("VERIFY_AUTH_TOKEN", "fixture-auth")
21078                .env(
21079                    "VERIFY_EXPECT_TOOLCHAIN",
21080                    std::env::var_os("RUSTUP_TOOLCHAIN").unwrap_or_default(),
21081                )
21082                .env(
21083                    "VERIFY_EXPECT_CACHE",
21084                    std::env::var_os("CARGO_TARGET_DIR").unwrap_or_default(),
21085                )
21086                .output()
21087                .unwrap();
21088            assert!(
21089                output.status.success()
21090                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
21091                "{}\n{}",
21092                String::from_utf8_lossy(&output.stdout),
21093                String::from_utf8_lossy(&output.stderr)
21094            );
21095            return;
21096        }
21097        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
21098        let home = crate::run::home();
21099        let directory = home.join("workers/jobs/abcdef");
21100        std::fs::create_dir_all(&directory).unwrap();
21101        let job = crate::worker::Job {
21102            id: "abcdef".into(),
21103            sequence: 1,
21104            kind: "task".into(),
21105            key: "task:verification".into(),
21106            payload: serde_json::json!({}),
21107            generation: std::env::var("MAGI_WORKER_GENERATION").unwrap(),
21108            version: Some(env!("CARGO_PKG_VERSION").into()),
21109            status: crate::worker::Status::Running,
21110            result: None,
21111            pid: Some(std::process::id()),
21112            created_at: 0,
21113            finished_at: None,
21114        };
21115        std::fs::write(
21116            directory.join("job.json"),
21117            serde_json::to_vec(&job).unwrap(),
21118        )
21119        .unwrap();
21120        let _lease = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
21121        let assert_worker = || {
21122            assert_eq!(
21123                crate::worker::current_job(&home).unwrap().unwrap().id,
21124                job.id
21125            );
21126            assert_eq!(crate::worker::active(&home).unwrap().len(), 1);
21127            assert_eq!(
21128                crate::worker::helper_executable(&home).unwrap(),
21129                PathBuf::from(std::env::var_os("MAGI_WORKER_EXE").unwrap())
21130            );
21131            assert!(
21132                crate::updater::Checker::new(&crate::config::Update {
21133                    mode: crate::config::UpdateMode::Notify,
21134                    interval: None,
21135                    auto_restart: false,
21136                })
21137                .is_none(),
21138                "the driver remains pinned, even while tests are standalone"
21139            );
21140        };
21141        assert_worker();
21142        let repo = home.join("repo");
21143        std::fs::create_dir_all(&repo).unwrap();
21144        init_repo(&repo);
21145        // Keep storage, seat/control context, containment and tool lookup.
21146        // No inherited values (or credentials) are printed on success.
21147        let probe = r#"test -z "${MAGI_WORKER_ID+x}" &&
21148            test -z "${MAGI_WORKER_GENERATION+x}" &&
21149            test -z "${MAGI_WORKER_HOME+x}" &&
21150            test -z "${MAGI_WORKER_EXE+x}" &&
21151            test "$MAGI_HOME/repo" -ef . &&
21152            test "$MAGI_RUN" = verification-parent &&
21153            test "$MAGI_NODE" = gate &&
21154            test "$MAGI_SEAT" = worker-fixture &&
21155            test -n "$MAGI_PROCESS_OWNER" &&
21156            test "$PATH" = "$VERIFY_EXPECT_PATH" &&
21157            test "$VERIFY_AUTH_TOKEN" = fixture-auth &&
21158            test "$RUSTUP_TOOLCHAIN" = "$VERIFY_EXPECT_TOOLCHAIN" &&
21159            test "$CARGO_TARGET_DIR" = "$VERIFY_EXPECT_CACHE""#;
21160        // Negative control: an ordinary child inherits the contamination.
21161        assert!(
21162            !std::process::Command::new("sh")
21163                .args(["-c", probe])
21164                .current_dir(&repo)
21165                .status()
21166                .unwrap()
21167                .success()
21168        );
21169        let unrelated_home = tempfile::tempdir().unwrap();
21170        assert!(
21171            crate::worker::current_job(unrelated_home.path()).is_err(),
21172            "an inherited worker id cannot be resolved in a unit fixture's home"
21173        );
21174        let mut runner = runner_at(RunStatus::Gating);
21175        runner.state.repo = repo.clone();
21176        runner.state.config.disk.min_free_bytes = 0;
21177        runner.state.config.coordination = crate::config::test_coordination();
21178        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
21179        runner.state.config.verify.e2e = vec![format!("{probe} && printf 'e2e\\n' >> phases")];
21180        runner.state.config.verify.pre_gate = vec![format!("{probe} && printf 'pre\\n' >> phases")];
21181        runner.state.config.verify.gate = vec![format!("{probe} && printf 'gate\\n' >> phases")];
21182        let winner = Candidate {
21183            index: 0,
21184            label: 'A',
21185            agent: "fixture".into(),
21186            branch: "main".into(),
21187            worktree: repo.clone(),
21188            summary: String::new(),
21189            stat: String::new(),
21190            files: 0,
21191            commits: 0,
21192            empty: false,
21193            failed: None,
21194            verified_noop: None,
21195            duration_ms: 0,
21196            folded: false,
21197        };
21198        let (e2e, retried, pids) = run_e2e_with_retry(
21199            &mut runner.state,
21200            &["sh".into(), "-c".into()],
21201            &[format!("{probe} && printf initial")],
21202            &repo,
21203            Duration::from_secs(10),
21204            "initial",
21205            None,
21206        )
21207        .await;
21208        assert!(!retried && pids.is_empty());
21209        assert_eq!(e2e[0].code, Some(0), "{e2e:?}");
21210        assert_eq!(e2e[0].output_tail, "initial");
21211        let gate = runner.run_gate(&winner).await.unwrap();
21212        assert!(gate.iter().all(CommandOutcome::ok), "{gate:?}");
21213        // An interrupted repair must recheck e2e from saved state. Landing
21214        // reuses that state and must run both pre-gate and gate again.
21215        runner.state.gate_repair_e2e = Some(crate::run::GateRepairE2e {
21216            head: git::rev_parse(&repo, "HEAD").await.unwrap(),
21217            passed: false,
21218            outcomes: Vec::new(),
21219        });
21220        runner.state.save().unwrap();
21221        let mut resumed = RunState::load(&runner.state.id).unwrap();
21222        let wait = crate::repo_lock::WaitPolicy::default();
21223        assert!(matches!(
21224            check_gate_repair_e2e(&mut resumed, &winner, &wait)
21225                .await
21226                .unwrap(),
21227            GateFix::Retry
21228        ));
21229        let saved = RunState::load(&resumed.id).unwrap();
21230        let repair = saved.gate_repair_e2e.unwrap();
21231        assert!(repair.passed);
21232        assert_eq!(repair.outcomes.len(), 1);
21233        assert!(repair.outcomes[0].ok());
21234        let landing = run_landing_gate(&mut resumed, &winner, &wait)
21235            .await
21236            .unwrap();
21237        assert_eq!(landing.len(), 1);
21238        assert!(landing[0].ok(), "{landing:?}");
21239        assert_eq!(
21240            std::fs::read_to_string(repo.join("phases")).unwrap(),
21241            "pre\ngate\ne2e\npre\ngate\n"
21242        );
21243        assert_worker();
21244    }
21245
21246    #[cfg(unix)]
21247    #[tokio::test]
21248    async fn verification_keeps_the_panic_and_the_full_output() {
21249        crate::run::pin_test_home();
21250        let tmp = tempfile::tempdir().unwrap();
21251        let mut config = Config::default();
21252        config.disk.min_free_bytes = 0;
21253        let mut state = RunState::new(
21254            tmp.path().to_owned(),
21255            "main".into(),
21256            "base".into(),
21257            "verification evidence".into(),
21258            config,
21259        );
21260        let script = "echo \"thread 'x' panicked at t.rs:1:1:\"; echo 'boom assertion'; \
21261                      i=0; while [ $i -lt 20000 ]; do echo \"  $i: 0xabc - <a::b>\"; \
21262                      echo '             at /x/y.rs:1:1'; i=$((i+1)); done; exit 101";
21263        let mut names = Vec::new();
21264        for _ in 0..2 {
21265            let (outcomes, _) = run_commands(
21266                &mut state,
21267                "gate",
21268                "gate",
21269                0,
21270                &["sh".into(), "-c".into()],
21271                &[script.into()],
21272                tmp.path(),
21273                Duration::from_secs(60),
21274            )
21275            .await;
21276            let tail = &outcomes[0].output_tail;
21277            assert!(tail.contains("panicked at t.rs:1:1"), "{tail}");
21278            assert!(tail.contains("boom assertion"));
21279            assert!(tail.len() <= crate::run::VERIFY_SUMMARY + 100);
21280            let line = tail.lines().next().unwrap();
21281            names.push(line.to_owned());
21282        }
21283        assert_ne!(names[0], names[1], "the second run must not overwrite");
21284        let full = crate::run::read_artifact(&state, "gate-1.out").unwrap();
21285        assert!(full.len() > 500_000 && full.contains("boom assertion"));
21286        assert!(crate::run::read_artifact(&state, "gate-2.out").is_some());
21287
21288        // Storage failures are evidence too; preserve the command's verdict.
21289        std::fs::remove_dir_all(state.dir().join("artifacts")).unwrap();
21290        std::fs::write(state.dir().join("artifacts"), "blocked").unwrap();
21291        let (outcomes, _) = run_commands(
21292            &mut state,
21293            "gate",
21294            "gate",
21295            0,
21296            &["sh".into(), "-c".into()],
21297            &["echo failure-output; exit 7".into()],
21298            tmp.path(),
21299            Duration::from_secs(10),
21300        )
21301        .await;
21302        assert_eq!(outcomes[0].code, Some(7));
21303        assert!(state.events.iter().any(|e| {
21304            e.node == "gate" && e.message.contains("could not save the full gate output:")
21305        }));
21306    }
21307
21308    #[cfg(unix)]
21309    #[tokio::test]
21310    async fn verification_commands_distinguish_timeouts_signals_and_exit_codes() {
21311        crate::run::pin_test_home();
21312        let tmp = tempfile::tempdir().unwrap();
21313        let mut config = Config::default();
21314        config.disk.min_free_bytes = 0;
21315        let mut state = RunState::new(
21316            tmp.path().to_owned(),
21317            "main".into(),
21318            "base".into(),
21319            "verification evidence".into(),
21320            config,
21321        );
21322        let (outcomes, pids) = run_commands(
21323            &mut state,
21324            "gate",
21325            "gate",
21326            1,
21327            &["sh".into(), "-c".into()],
21328            &[
21329                "printf before-timeout; exec sleep 30".into(),
21330                "kill -TERM $$".into(),
21331                "exit 7".into(),
21332                "printf success".into(),
21333            ],
21334            tmp.path(),
21335            Duration::from_secs(1),
21336        )
21337        .await;
21338        wait_for_timed_out_children_to_die(&pids).await;
21339        assert_eq!(
21340            pids.len(),
21341            1,
21342            "unleased timeout retains its death-check PID"
21343        );
21344        assert_eq!(outcomes.len(), 4);
21345        assert_eq!(outcomes[0].code, None);
21346        assert!(outcomes[0].output_tail.contains("before-timeout"));
21347        assert!(outcomes[0].output_tail.contains("timed out after 1s"));
21348        assert_eq!(outcomes[1].code, None);
21349        assert!(outcomes[1].output_tail.contains("command terminated:"));
21350        assert!(!outcomes[1].output_tail.contains("timed out"));
21351        assert_eq!(outcomes[2].code, Some(7));
21352        assert!(!outcomes[2].output_tail.contains("timed out"));
21353        assert_eq!(outcomes[3].code, Some(0));
21354        assert_eq!(outcomes[3].output_tail, "success");
21355        assert!(outcomes.iter().all(|outcome| !outcome.resource_blocked));
21356    }
21357
21358    /// The addendum's second gap: a `verify.gate` command running for real
21359    /// wall-clock time had nothing at all to show for it in `active` before
21360    /// `run_commands` learned to record it — a run could sit in `Gating` for
21361    /// minutes with `magi show` and `GET /api/runs/{id}` both silent about
21362    /// what was actually happening. Proven with a genuinely still-running
21363    /// command, not just a before/after check on the final state: a poller
21364    /// task reads the same `run.json` `gate()` is writing, the same way the
21365    /// phone or `magi show` would, while the shell command is still blocked
21366    /// on its own release marker.
21367    #[tokio::test]
21368    async fn gate_records_a_running_task_entry_while_its_command_is_still_in_flight() {
21369        crate::run::pin_test_home();
21370
21371        let tmp = tempfile::tempdir().expect("tempdir");
21372        let repo = tmp.path().join("repo");
21373        std::fs::create_dir_all(&repo).unwrap();
21374        init_repo(&repo);
21375
21376        let mut config = Config::default();
21377        config.disk.min_free_bytes = 0;
21378        config.verify.gate = vec![
21379            "printf started > started.marker; i=0; while [ ! -f release.marker ] && \
21380             [ \"$i\" -lt 100 ]; do i=$((i+1)); sleep 0.05; done; test -f release.marker"
21381                .to_owned(),
21382        ];
21383
21384        let mut state = RunState::new(
21385            repo.clone(),
21386            "main".to_owned(),
21387            "deadbeef".to_owned(),
21388            "task".to_owned(),
21389            config,
21390        );
21391        let run_id = state.id.clone();
21392        state.candidates = vec![Candidate {
21393            index: 0,
21394            label: 'A',
21395            agent: "alpha".to_owned(),
21396            branch: "does-not-exist".to_owned(),
21397            worktree: repo.clone(),
21398            summary: String::new(),
21399            stat: String::new(),
21400            files: 0,
21401            commits: 0,
21402            empty: false,
21403            failed: None,
21404            verified_noop: None,
21405            duration_ms: 0,
21406            folded: false,
21407        }];
21408        state.tally = Some(Tally {
21409            first_choice: BTreeMap::from([('A', 1)]),
21410            borda: BTreeMap::new(),
21411            winner: 'A',
21412            rankings: 1,
21413            unanimous_initial: true,
21414            deliberated: false,
21415            changed_votes: 0,
21416            unanimous_final: true,
21417            tie_break: None,
21418            judges: 0,
21419            present: 0,
21420            quorum: 0,
21421            met_quorum: true,
21422            uncontested: Some("only candidate A produced a change".to_owned()),
21423        });
21424        state.reviews = vec![ReviewRound {
21425            round: 1,
21426            head: "deadbeef".to_owned(),
21427            verified_head: None,
21428            verified_at: None,
21429            reviews: Vec::new(),
21430            e2e: Vec::new(),
21431            fix: None,
21432            blocking: 0,
21433            answered: 0,
21434            expected: 0,
21435            clean: true,
21436            verify_retried: false,
21437            e2e_deferred: false,
21438            e2e_defer_reason: None,
21439            progressed: false,
21440            vote_split: false,
21441            reconsideration: Vec::new(),
21442            verdict: None,
21443        }];
21444
21445        let mut runner = Runner {
21446            state,
21447            roles: ResolvedRoles {
21448                implementers: Vec::new(),
21449                judges: Vec::new(),
21450                reviewers: Vec::new(),
21451                fixer: None,
21452                conductor: conductor(),
21453                implementer_roster: Vec::new(),
21454                judge_roster: Vec::new(),
21455                reviewer_roster: Vec::new(),
21456            },
21457            sem: Arc::new(Semaphore::new(1)),
21458            pause: Pause::new(),
21459            interrupt: Pause::new(),
21460        };
21461
21462        let started_marker = repo.join("started.marker");
21463        let release_marker = repo.join("release.marker");
21464        let observe = async {
21465            loop {
21466                if started_marker.exists()
21467                    && let Ok(s) = crate::run::RunState::load(&run_id)
21468                    && let Some(a) = s.active.get("gate")
21469                {
21470                    std::fs::write(&release_marker, b"go").expect("release marker");
21471                    break a.clone();
21472                }
21473                tokio::time::sleep(Duration::from_millis(50)).await;
21474            }
21475        };
21476        let captured = {
21477            let gate = runner.gate();
21478            tokio::pin!(gate);
21479            let captured = tokio::select! {
21480                observed = observe => observed,
21481                result = &mut gate => panic!(
21482                    "gate exited before its in-flight entry was observed: {result:?}"
21483                ),
21484            };
21485            gate.await.expect("gate");
21486            captured
21487        };
21488
21489        assert_eq!(captured.task.as_deref(), Some("gate"));
21490        assert_eq!(captured.node, "gate");
21491        assert_eq!(captured.index, Some(1));
21492        assert_eq!(captured.total, Some(1));
21493        assert!(
21494            captured
21495                .command
21496                .as_deref()
21497                .is_some_and(|c| c.contains("started.marker")),
21498            "{captured:?}"
21499        );
21500
21501        assert!(
21502            runner.state.active.is_empty(),
21503            "the entry must be cleared once the command actually finished: {:?}",
21504            runner.state.active
21505        );
21506        assert!(runner.state.gate_ran);
21507        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
21508    }
21509
21510    /// The hand-off over a blocking finding a reviewer rejected on leaves a
21511    /// record for `land`; one with only a Minor, or no reject, leaves none.
21512    #[tokio::test]
21513    async fn stop_reviewing_records_a_contested_hand_off_only_for_major_plus_reject() {
21514        use crate::verdict::{Finding, ReviewVote, Severity};
21515        crate::run::pin_test_home();
21516        let tmp = tempfile::tempdir().expect("tempdir");
21517        let repo = tmp.path().join("repo");
21518        std::fs::create_dir_all(&repo).unwrap();
21519        init_repo(&repo);
21520
21521        for (severity, vote, expect) in [
21522            (Severity::Major, ReviewVote::Reject, true),
21523            (Severity::Minor, ReviewVote::Reject, false),
21524            (Severity::Major, ReviewVote::Approve, false),
21525        ] {
21526            let mut round = review_round(false, 1, 1, 1, false, true);
21527            round.reviews = vec![ReviewRecord {
21528                reviewer: 1,
21529                agent: "alpha".to_owned(),
21530                summary: String::new(),
21531                findings: vec![Finding {
21532                    id: "R1-1-1".to_owned(),
21533                    severity,
21534                    file: None,
21535                    line: None,
21536                    title: "t".to_owned(),
21537                    detail: String::new(),
21538                }],
21539                vote: Some(vote),
21540                failed: None,
21541                duration_ms: 0,
21542                attempts: 0,
21543            }];
21544            let mut state = RunState::new(
21545                repo.clone(),
21546                "main".to_owned(),
21547                "deadbeef".to_owned(),
21548                "task".to_owned(),
21549                Config::default(),
21550            );
21551            state.reviews = vec![round];
21552            let mut runner = Runner {
21553                state,
21554                roles: ResolvedRoles {
21555                    implementers: Vec::new(),
21556                    judges: Vec::new(),
21557                    reviewers: Vec::new(),
21558                    fixer: None,
21559                    conductor: conductor(),
21560                    implementer_roster: Vec::new(),
21561                    judge_roster: Vec::new(),
21562                    reviewer_roster: Vec::new(),
21563                },
21564                sem: Arc::new(Semaphore::new(1)),
21565                pause: Pause::new(),
21566                interrupt: Pause::new(),
21567            };
21568            let shell = runner.state.config.shell();
21569            runner
21570                .stop_reviewing("round budget spent", &shell, &repo)
21571                .await
21572                .expect("stop_reviewing");
21573            assert_eq!(runner.state.status, RunStatus::Gating);
21574            assert_eq!(
21575                runner.state.contested_handoff.is_some(),
21576                expect,
21577                "{severity:?} + {vote:?}"
21578            );
21579        }
21580    }
21581
21582    /// The shape the incident this whole fix responds to actually had: the
21583    /// round budget spent, the last round's own e2e blocked on the shared
21584    /// build cache (held here by a live pid — this test process — exactly
21585    /// `cache`'s own unit tests' pattern for "another owner, still alive"
21586    /// without forking a process). `stop_reviewing` must retry it — not
21587    /// silently leave the round looking untouched (the catch-up-only half of
21588    /// the bug), and not read the contention as a red `e2e` and block the
21589    /// run on it (the other half). Called directly, the same way
21590    /// `gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run`
21591    /// above exercises `gate`, so this never needs a real cargo build to
21592    /// reach: the lease is never released, so `with_cache_lease` never gets
21593    /// past acquiring it into anything that would need a real workspace.
21594    #[tokio::test]
21595    async fn stop_reviewing_retries_a_resource_blocked_e2e_instead_of_reading_it_as_red() {
21596        crate::run::pin_test_home();
21597        let home = crate::run::home();
21598
21599        let tmp = tempfile::tempdir().expect("tempdir");
21600        let repo = tmp.path().join("repo");
21601        std::fs::create_dir_all(&repo).unwrap();
21602        init_repo(&repo);
21603        let head = crate::git::rev_parse(&repo, "HEAD")
21604            .await
21605            .expect("rev-parse");
21606        // Unique to this test, so holding its lease cannot collide with
21607        // another test sharing the same process-wide `home`.
21608        let cache_dir = tmp.path().join("target");
21609
21610        let mut config = Config::default();
21611        config.verify.e2e = vec![format!(
21612            "CARGO_TARGET_DIR='{}' test -f README.md",
21613            cache_dir.display()
21614        )];
21615        config.graph.review_rounds = 1;
21616        // Bounded so a regression that does start waiting fails the test in
21617        // seconds, not hangs it.
21618        config.graph.timeout_verify = Some(2);
21619        config.graph.timeout_resource_wait = 2;
21620
21621        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
21622        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
21623            .expect("no io error acquiring directly")
21624        {
21625            crate::cache::AcquireOutcome::Acquired(g) => g,
21626            crate::cache::AcquireOutcome::Busy(b) => {
21627                panic!("expected the direct acquire to win the lease first: {b:?}")
21628            }
21629        };
21630
21631        let mut state = RunState::new(
21632            repo.clone(),
21633            "main".to_owned(),
21634            head.clone(),
21635            "task".to_owned(),
21636            config,
21637        );
21638        state.candidates = vec![Candidate {
21639            index: 0,
21640            label: 'A',
21641            agent: "alpha".to_owned(),
21642            branch: "does-not-exist".to_owned(),
21643            worktree: repo.clone(),
21644            summary: String::new(),
21645            stat: String::new(),
21646            files: 0,
21647            commits: 0,
21648            empty: false,
21649            failed: None,
21650            verified_noop: None,
21651            duration_ms: 0,
21652            folded: false,
21653        }];
21654        state.tally = Some(Tally {
21655            first_choice: BTreeMap::from([('A', 1)]),
21656            borda: BTreeMap::new(),
21657            winner: 'A',
21658            rankings: 1,
21659            unanimous_initial: true,
21660            deliberated: false,
21661            changed_votes: 0,
21662            unanimous_final: true,
21663            tie_break: None,
21664            judges: 0,
21665            present: 0,
21666            quorum: 0,
21667            met_quorum: true,
21668            uncontested: Some("only candidate A produced a change".to_owned()),
21669        });
21670        // The round budget's last round, deferred: `needs_catchup_run`'s
21671        // other trigger. `stop_reviewing`'s retry machinery must treat this
21672        // exactly like a resource-blocked attempt once it actually runs.
21673        state.reviews = vec![ReviewRound {
21674            round: 1,
21675            head: head.clone(),
21676            verified_head: None,
21677            verified_at: None,
21678            reviews: Vec::new(),
21679            e2e: Vec::new(),
21680            fix: None,
21681            blocking: 1,
21682            answered: 1,
21683            expected: 1,
21684            clean: false,
21685            verify_retried: false,
21686            e2e_deferred: true,
21687            e2e_defer_reason: Some("1 blocking finding(s) already required a fix".to_owned()),
21688            progressed: false,
21689            vote_split: false,
21690            reconsideration: Vec::new(),
21691            verdict: None,
21692        }];
21693
21694        let mut runner = Runner {
21695            state,
21696            roles: ResolvedRoles {
21697                implementers: Vec::new(),
21698                judges: Vec::new(),
21699                reviewers: Vec::new(),
21700                fixer: None,
21701                conductor: conductor(),
21702                implementer_roster: Vec::new(),
21703                judge_roster: Vec::new(),
21704                reviewer_roster: Vec::new(),
21705            },
21706            sem: Arc::new(Semaphore::new(1)),
21707            pause: Pause::new(),
21708            interrupt: Pause::new(),
21709        };
21710
21711        let shell = runner.state.config.shell();
21712        runner
21713            .stop_reviewing("round budget spent", &shell, &repo)
21714            .await
21715            .expect("stop_reviewing");
21716
21717        let last = runner.state.reviews.last().expect("round record");
21718        assert_eq!(
21719            last.e2e_status(),
21720            E2eStatus::ResourceBlocked,
21721            "the shared cache is still held; the attempt must read as blocked, not deferred or \
21722             failed: {last:?}"
21723        );
21724        assert_eq!(
21725            last.verified_head.as_deref(),
21726            Some(head.as_str()),
21727            "which commit this attempt targeted is known even though nothing finished checking \
21728             it"
21729        );
21730        let first_attempt_at = last
21731            .verified_at
21732            .expect("when this attempt ran is known too");
21733        assert_ne!(
21734            runner.state.status,
21735            RunStatus::Blocked,
21736            "contention is evidence about the machine, not the patch — it must not settle the \
21737             run as blocked: {:?}",
21738            runner.state.status
21739        );
21740        assert!(
21741            !runner
21742                .state
21743                .events
21744                .iter()
21745                .any(|e| e.node == "review" && e.message.contains("e2e failed")),
21746            "a resource-blocked attempt must never be logged as a failed e2e: {:?}",
21747            runner.state.events
21748        );
21749
21750        // The cache is still held: a later reentry must retry the same
21751        // round's verification again — not leave it looking exactly as
21752        // untouched as the first blocked attempt, which is indistinguishable
21753        // from never having tried again at all.
21754        runner
21755            .stop_reviewing("round budget spent", &shell, &repo)
21756            .await
21757            .expect("stop_reviewing retry");
21758        assert_eq!(
21759            runner.state.reviews.len(),
21760            1,
21761            "no new round was started: {:?}",
21762            runner.state.reviews
21763        );
21764        let last = runner.state.reviews.last().expect("round record");
21765        assert_eq!(last.e2e_status(), E2eStatus::ResourceBlocked, "{last:?}");
21766        assert!(
21767            last.verified_at.expect("still known") > first_attempt_at,
21768            "a second reentry must be a fresh attempt, not a stale copy of the first"
21769        );
21770        assert_ne!(runner.state.status, RunStatus::Blocked);
21771
21772        held.release();
21773    }
21774
21775    #[cfg(unix)]
21776    #[tokio::test]
21777    async fn catchup_compile_failure_after_clean_base_sync_uses_remaining_review_rounds() {
21778        ask_test_home();
21779        for (max_rounds, reentry) in [(2, false), (2, true), (1, false)] {
21780            let tmp = tempfile::tempdir().unwrap();
21781            let repo = tmp.path().join("repo");
21782            std::fs::create_dir(&repo).unwrap();
21783            init_repo(&repo);
21784            let run_git = |args: &[&str]| {
21785                let out = std::process::Command::new("git")
21786                    .args(args)
21787                    .current_dir(&repo)
21788                    .output()
21789                    .unwrap();
21790                assert!(
21791                    out.status.success(),
21792                    "{args:?}: {}",
21793                    String::from_utf8_lossy(&out.stderr)
21794                );
21795            };
21796            let origin = tmp.path().join("origin.git");
21797            run_git(&["init", "--bare", origin.to_str().unwrap()]);
21798            run_git(&["remote", "add", "origin", origin.to_str().unwrap()]);
21799            std::fs::write(repo.join("spec.rs"), "struct AgentSpec {}\n").unwrap();
21800            run_git(&["add", "spec.rs"]);
21801            run_git(&["commit", "-m", "initial spec"]);
21802            run_git(&["push", "origin", "main"]);
21803            let base = git::rev_parse(&repo, "HEAD").await.unwrap();
21804            run_git(&["checkout", "-b", "fix/review"]);
21805            std::fs::write(
21806                repo.join("check.rs"),
21807                "include!(\"spec.rs\"); fn main() { let _ = AgentSpec {}; }\n",
21808            )
21809            .unwrap();
21810            run_git(&["add", "check.rs"]);
21811            run_git(&["commit", "-m", "use spec"]);
21812            let reviewed = git::rev_parse(&repo, "HEAD").await.unwrap();
21813            run_git(&["checkout", "main"]);
21814            std::fs::write(
21815                repo.join("spec.rs"),
21816                "struct AgentSpec { max_turn_secs: u64 }\n",
21817            )
21818            .unwrap();
21819            run_git(&["add", "spec.rs"]);
21820            run_git(&["commit", "-m", "extend spec"]);
21821            run_git(&["push", "origin", "main"]);
21822            run_git(&["checkout", "fix/review"]);
21823
21824            let mut runner = runner_at(RunStatus::Reviewing);
21825            runner.state.repo = repo.clone();
21826            runner.state.base_commit = base;
21827            runner.state.pr_head = Some("fix/review".into());
21828            runner.state.config.graph.review_rounds = max_rounds;
21829            runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
21830            runner.state.config.graph.sessions = false;
21831            runner.state.config.disk.min_free_bytes = 0;
21832            runner.state.config.verify.e2e =
21833                vec!["rustc --emit=metadata -o ../check.rmeta check.rs || { echo 'error: could not compile fixture' >&2; exit 101; }".into()];
21834            runner.state.candidates = vec![Candidate {
21835                index: 0,
21836                label: 'A',
21837                agent: "fixture".into(),
21838                branch: "fix/review".into(),
21839                worktree: repo.clone(),
21840                summary: String::new(),
21841                stat: String::new(),
21842                files: 1,
21843                commits: 1,
21844                empty: false,
21845                failed: None,
21846                verified_noop: None,
21847                duration_ms: 0,
21848                folded: false,
21849            }];
21850            runner.state.tally = Some(Tally {
21851                first_choice: BTreeMap::new(),
21852                borda: BTreeMap::new(),
21853                winner: 'A',
21854                rankings: 0,
21855                unanimous_initial: true,
21856                deliberated: false,
21857                changed_votes: 0,
21858                unanimous_final: true,
21859                tie_break: None,
21860                judges: 0,
21861                present: 0,
21862                quorum: 0,
21863                met_quorum: true,
21864                uncontested: Some("review-only".into()),
21865            });
21866            let mut last = review_round(false, 0, 1, 1, false, false);
21867            last.head = reviewed.clone();
21868            last.e2e_deferred = true;
21869            last.e2e[0].resource_blocked = true;
21870            last.e2e[0].output_tail = "waiting for the shared build cache".into();
21871            if max_rounds == 1 {
21872                last.e2e.clear();
21873            }
21874            runner.state.reviews = vec![last];
21875            let calls = tmp.path().join("fix-calls");
21876            let mut fixer = spec("repair");
21877            fixer
21878                .env
21879                .insert("FIX_CALLS".into(), calls.display().to_string());
21880            fixer.command = vec!["sh".into(), "-c".into(), r#"
21881                echo fix >> "$FIX_CALLS"
21882                grep -q E0063 "$MAGI_PROMPT_FILE" || exit 1
21883                grep -q max_turn_secs "$MAGI_PROMPT_FILE" || exit 1
21884                printf 'include!("spec.rs"); fn main() { let _ = AgentSpec { max_turn_secs: 0 }; }\n' > check.rs
21885                printf '{"addressed":[],"rejected":[],"notes":"initialize the new field"}\n'
21886            "#.into()];
21887            let mut reviewer = spec("reviewer");
21888            reviewer.command = vec![
21889                "sh".into(),
21890                "-c".into(),
21891                "printf '%s\\n' '{\"summary\":\"clean\",\"vote\":\"approve\",\"findings\":[]}'"
21892                    .into(),
21893            ];
21894            runner.roles.fixer = Some(vec![fixer]);
21895            runner.roles.reviewers = vec![reviewer];
21896
21897            runner.sync_to_base().await.unwrap();
21898            let rebased = git::rev_parse(&repo, "HEAD").await.unwrap();
21899            assert_ne!(rebased, reviewed);
21900            assert!(runner.state.base_sync.as_ref().unwrap().conflict.is_none());
21901            if reentry {
21902                // Simulate a crash after catch-up evidence was saved but before
21903                // dispatching the fixer. No dedicated pending-repair field exists.
21904                let shell = runner.state.config.shell();
21905                runner
21906                    .stop_unresolved_review("deferred verification", &shell, &repo)
21907                    .await
21908                    .unwrap();
21909                assert!(runner.catchup_repairable());
21910                assert!(!calls.exists());
21911                runner.state = RunState::load(&runner.state.id).unwrap();
21912                assert!(runner.catchup_repairable());
21913            }
21914            runner.review_loop().await.unwrap();
21915            let first = &runner.state.reviews[0];
21916            assert_eq!(first.head, reviewed);
21917            assert_eq!(first.verified_head.as_deref(), Some(rebased.as_str()));
21918            assert!(
21919                first.verify_retried,
21920                "a reproduced build failure gets exactly one retry: {:?}",
21921                first.e2e
21922            );
21923            assert!(first.e2e[0].output_tail.contains("E0063"));
21924            assert!(!runner.catchup_repairable());
21925            if max_rounds == 2 {
21926                assert_eq!(
21927                    runner.state.status,
21928                    RunStatus::Gating,
21929                    "{}",
21930                    crate::report::run(&runner.state)
21931                );
21932                assert_eq!(runner.state.reviews.len(), 2);
21933                assert!(first.fix.as_ref().unwrap().committed);
21934                assert!(runner.state.reviews[1].clean);
21935                assert_eq!(
21936                    runner
21937                        .state
21938                        .reviews
21939                        .iter()
21940                        .filter(|r| r.fix.is_some())
21941                        .count(),
21942                    1
21943                );
21944                assert_eq!(std::fs::read_to_string(&calls).unwrap().lines().count(), 1);
21945                assert_eq!(runner.state.reviews[1].e2e_status(), E2eStatus::Passed);
21946            } else {
21947                assert_eq!(runner.state.status, RunStatus::Blocked);
21948                assert!(first.fix.is_none());
21949                assert!(!calls.exists());
21950                let recovery = crate::recovery::assess(
21951                    "prior",
21952                    Some(&runner.state),
21953                    &runner.landing_base(),
21954                    crate::recovery::Relation::Diverged,
21955                );
21956                assert_eq!(recovery.mode, crate::recovery::Mode::FullReview);
21957                let reasons = recovery.reasons.join("\n");
21958                assert!(
21959                    reasons.contains(&reviewed) && reasons.contains(&rebased),
21960                    "{reasons}"
21961                );
21962                assert!(
21963                    reasons.contains("base sync to")
21964                        && reasons.contains("additional review is required"),
21965                    "{reasons}"
21966                );
21967            }
21968        }
21969    }
21970
21971    /// A resumed run — a fresh `Runner`, `self.state.reviews` already
21972    /// holding the round `stop_reviewing` left `ResourceBlocked` from a
21973    /// prior process — must not sit at `Reviewing` forever: `review_loop`'s
21974    /// own top-of-function fast path (`review_conclusion`) correctly reads
21975    /// this shape as `None` rather than guessing `Blocked`, and the loop's
21976    /// own `for` range is empty once the round budget is spent, so
21977    /// `review_loop` must retry the check itself rather than silently doing
21978    /// nothing. Reaches the exact same retry `stop_reviewing_retries_a_*`
21979    /// above exercises directly, but through `review_loop`'s own entry point
21980    /// this time, proving the wiring between the two rather than just the
21981    /// retry logic in isolation.
21982    #[tokio::test]
21983    async fn a_resumed_review_loop_retries_a_last_round_left_resource_blocked() {
21984        crate::run::pin_test_home();
21985        let home = crate::run::home();
21986
21987        let tmp = tempfile::tempdir().expect("tempdir");
21988        let repo = tmp.path().join("repo");
21989        std::fs::create_dir_all(&repo).unwrap();
21990        init_repo(&repo);
21991        let head = crate::git::rev_parse(&repo, "HEAD")
21992            .await
21993            .expect("rev-parse");
21994        let cache_dir = tmp.path().join("target");
21995
21996        let mut config = Config::default();
21997        config.verify.e2e = vec![format!(
21998            "CARGO_TARGET_DIR='{}' test -f README.md",
21999            cache_dir.display()
22000        )];
22001        config.graph.review_rounds = 1;
22002        config.graph.timeout_verify = Some(2);
22003        config.graph.timeout_resource_wait = 2;
22004
22005        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
22006        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
22007            .expect("no io error acquiring directly")
22008        {
22009            crate::cache::AcquireOutcome::Acquired(g) => g,
22010            crate::cache::AcquireOutcome::Busy(b) => {
22011                panic!("expected the direct acquire to win the lease first: {b:?}")
22012            }
22013        };
22014
22015        let mut state = RunState::new(
22016            repo.clone(),
22017            "main".to_owned(),
22018            head.clone(),
22019            "task".to_owned(),
22020            config,
22021        );
22022        state.candidates = vec![Candidate {
22023            index: 0,
22024            label: 'A',
22025            agent: "alpha".to_owned(),
22026            branch: "does-not-exist".to_owned(),
22027            worktree: repo.clone(),
22028            summary: String::new(),
22029            stat: String::new(),
22030            files: 0,
22031            commits: 0,
22032            empty: false,
22033            failed: None,
22034            verified_noop: None,
22035            duration_ms: 0,
22036            folded: false,
22037        }];
22038        state.tally = Some(Tally {
22039            first_choice: BTreeMap::from([('A', 1)]),
22040            borda: BTreeMap::new(),
22041            winner: 'A',
22042            rankings: 1,
22043            unanimous_initial: true,
22044            deliberated: false,
22045            changed_votes: 0,
22046            unanimous_final: true,
22047            tie_break: None,
22048            judges: 0,
22049            present: 0,
22050            quorum: 0,
22051            met_quorum: true,
22052            uncontested: Some("only candidate A produced a change".to_owned()),
22053        });
22054        // The exact shape a prior process's `stop_reviewing` would have left
22055        // on disk: the round budget's last round, a real attempt already
22056        // made and already resource-blocked.
22057        state.reviews = vec![ReviewRound {
22058            round: 1,
22059            head: head.clone(),
22060            verified_head: Some(head.clone()),
22061            verified_at: Some(jiff::Timestamp::now()),
22062            reviews: Vec::new(),
22063            e2e: vec![CommandOutcome {
22064                command: format!(
22065                    "CARGO_TARGET_DIR='{}' test -f README.md",
22066                    cache_dir.display()
22067                ),
22068                code: None,
22069                output_tail: "waiting for the shared build cache".to_owned(),
22070                duration_ms: 0,
22071                resource_blocked: true,
22072            }],
22073            fix: None,
22074            blocking: 1,
22075            answered: 1,
22076            expected: 1,
22077            clean: false,
22078            verify_retried: false,
22079            e2e_deferred: false,
22080            e2e_defer_reason: None,
22081            progressed: false,
22082            vote_split: false,
22083            reconsideration: Vec::new(),
22084            verdict: None,
22085        }];
22086
22087        let first_attempt_at = state.reviews[0].verified_at.expect("set above");
22088        let mut runner = Runner {
22089            state,
22090            roles: ResolvedRoles {
22091                implementers: Vec::new(),
22092                judges: Vec::new(),
22093                reviewers: Vec::new(),
22094                fixer: None,
22095                conductor: conductor(),
22096                implementer_roster: Vec::new(),
22097                judge_roster: Vec::new(),
22098                reviewer_roster: Vec::new(),
22099            },
22100            sem: Arc::new(Semaphore::new(1)),
22101            pause: Pause::new(),
22102            interrupt: Pause::new(),
22103        };
22104
22105        // The lease is still held throughout, so this reentry's own retry is
22106        // also contended — proving `review_loop` actually tried again (not
22107        // that it happened to succeed) is what the timestamp comparison
22108        // below is for.
22109        runner.review_loop().await.expect("review_loop");
22110
22111        assert_eq!(
22112            runner.state.reviews.len(),
22113            1,
22114            "no new round was started on top of the unresolved one: {:?}",
22115            runner.state.reviews
22116        );
22117        let last = &runner.state.reviews[0];
22118        assert_eq!(
22119            last.e2e_status(),
22120            E2eStatus::ResourceBlocked,
22121            "still contended: {last:?}"
22122        );
22123        assert!(
22124            last.verified_at.expect("still known") > first_attempt_at,
22125            "review_loop must have actually retried the check, not left it exactly as found"
22126        );
22127        assert_ne!(
22128            runner.state.status,
22129            RunStatus::Blocked,
22130            "a resumed run must not read leftover contention as a verdict on the patch: {:?}",
22131            runner.state.status
22132        );
22133
22134        held.release();
22135    }
22136
22137    #[tokio::test]
22138    async fn stopped_landing_resumes_from_structured_pr_even_with_legacy_gating_status() {
22139        crate::run::pin_test_home();
22140        for status in [RunStatus::Blocked, RunStatus::Gating] {
22141            let mut runner = runner_at(status);
22142            runner.state.config.graph.land = true;
22143            runner.state.gate_ran = true;
22144            runner.state.merge = Some(MergeOutcome {
22145                mode: MergeMode::Pr,
22146                ok: false,
22147                detail: "the fixer produced no commit".into(),
22148                empty: false,
22149            });
22150            let url = "https://example.invalid/o/r/pull/1";
22151            runner.state.pr = Some(crate::run::PrRecord {
22152                url: url.into(),
22153                number: 1,
22154                state: "open".into(),
22155                checks: "red".into(),
22156                round: 1,
22157                rounds: 1,
22158                red_at_merge: Vec::new(),
22159            });
22160            runner.state.save().unwrap();
22161            // The nonexistent repository makes observation fail before a forge
22162            // command can run. We still must reach land, rather than silently
22163            // return from the graph with its old gate and merge records.
22164            runner.execute_graph().await.unwrap();
22165            assert_eq!(runner.state.status, RunStatus::Blocked);
22166            assert!(runner.state.land_sync_pending);
22167            assert!(runner.state.events.iter().any(|event|
22168                event.node == "land" && event.message == format!("watching {url}")));
22169            assert_eq!(
22170                runner.state.merge.as_ref().unwrap().detail,
22171                "the fixer produced no commit"
22172            );
22173        }
22174    }
22175
22176    #[tokio::test]
22177    async fn a_run_resumed_mid_landing_reenters_land_instead_of_opening_a_second_pull_request() {
22178        crate::run::pin_test_home();
22179        let tmp = tempfile::tempdir().expect("tempdir");
22180        let repo = tmp.path().join("repo");
22181        std::fs::create_dir_all(&repo).unwrap();
22182        init_repo(&repo);
22183
22184        let mut config = Config::default();
22185        config.merge.mode = MergeMode::Pr;
22186        config.graph.land = true;
22187        config.graph.land_approval = false;
22188
22189        let mut state = RunState::new(
22190            repo.clone(),
22191            "main".to_owned(),
22192            "deadbeef".to_owned(),
22193            "task".to_owned(),
22194            config,
22195        );
22196        state.candidates = vec![Candidate {
22197            index: 0,
22198            label: 'A',
22199            agent: "alpha".to_owned(),
22200            branch: "does-not-exist".to_owned(),
22201            worktree: repo.clone(),
22202            summary: String::new(),
22203            stat: String::new(),
22204            files: 0,
22205            commits: 0,
22206            empty: false,
22207            failed: None,
22208            verified_noop: None,
22209            duration_ms: 0,
22210            folded: false,
22211        }];
22212        state.tally = Some(Tally {
22213            first_choice: BTreeMap::from([('A', 1)]),
22214            borda: BTreeMap::new(),
22215            winner: 'A',
22216            rankings: 1,
22217            unanimous_initial: true,
22218            deliberated: false,
22219            changed_votes: 0,
22220            unanimous_final: true,
22221            tie_break: None,
22222            judges: 0,
22223            present: 0,
22224            quorum: 0,
22225            met_quorum: true,
22226            uncontested: Some("only candidate A produced a change".to_owned()),
22227        });
22228        state.reviews = vec![ReviewRound {
22229            round: 1,
22230            head: "deadbeef".to_owned(),
22231            verified_head: None,
22232            verified_at: None,
22233            reviews: Vec::new(),
22234            e2e: Vec::new(),
22235            fix: None,
22236            blocking: 0,
22237            answered: 0,
22238            expected: 0,
22239            clean: true,
22240            verify_retried: false,
22241            e2e_deferred: false,
22242            e2e_defer_reason: None,
22243            progressed: false,
22244            vote_split: false,
22245            reconsideration: Vec::new(),
22246            verdict: None,
22247        }];
22248        state.gate = vec![CommandOutcome {
22249            command: "test".to_owned(),
22250            code: Some(0),
22251            output_tail: String::new(),
22252            duration_ms: 0,
22253            resource_blocked: false,
22254        }];
22255        state.gate_ran = true;
22256        // A first pass through `merge` already pushed and opened this pull
22257        // request; `status` is `Landing` because a previous call into `land`
22258        // parked or was interrupted before it reached a terminal outcome.
22259        state.status = RunStatus::Landing;
22260        state.merge = Some(MergeOutcome {
22261            mode: MergeMode::Pr,
22262            ok: true,
22263            detail: "https://example.invalid/x/y/pull/1".to_owned(),
22264            empty: false,
22265        });
22266
22267        // The Landing-resume shortcut calls `run_land` directly rather than
22268        // through `merge`, which is exactly the call site that used to skip
22269        // `settle_questions` - see the fixture below.
22270        ask_test_home();
22271        // A real resume loads a persisted run; driver ownership is checked
22272        // against that record before the Landing shortcut is entered.
22273        state.save().expect("save landing run");
22274        let store = ask::Questions::open();
22275        let q = ask_open_question(&store, &state.id);
22276
22277        let mut runner = Runner {
22278            state,
22279            roles: ResolvedRoles {
22280                implementers: Vec::new(),
22281                judges: Vec::new(),
22282                reviewers: Vec::new(),
22283                fixer: None,
22284                conductor: conductor(),
22285                implementer_roster: Vec::new(),
22286                judge_roster: Vec::new(),
22287                reviewer_roster: Vec::new(),
22288            },
22289            sem: Arc::new(Semaphore::new(1)),
22290            pause: Pause::new(),
22291            interrupt: Pause::new(),
22292        };
22293
22294        // `execute`, not `merge` directly: the Landing-resume shortcut lives
22295        // at the top of `execute`, not inside `merge` (see `execute`'s doc)
22296        // exactly because `review_loop` would otherwise clobber the marker
22297        // first.
22298        runner.execute().await.expect("execute");
22299
22300        assert_eq!(
22301            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
22302            Some("https://example.invalid/x/y/pull/1"),
22303            "reentry must not push again or open a second pull request over the \
22304             one `land` is already watching"
22305        );
22306        assert_ne!(
22307            runner.state.status,
22308            RunStatus::Landing,
22309            "land could not actually reach the fake pull request, so it must \
22310             have given up rather than left the run silently parked forever"
22311        );
22312        // `land` could not reach the fake pull request, so it gave up into
22313        // `Blocked` - still resumable, so the question must not have been
22314        // swept just because this branch now also calls `settle_questions`.
22315        assert_eq!(runner.state.status, RunStatus::Blocked);
22316        assert!(
22317            store.get(&q.id).unwrap().status.open(),
22318            "Blocked is still alive; settle_questions must have been a no-op here"
22319        );
22320    }
22321
22322    fn state_with_round(round: ReviewRound) -> RunState {
22323        let mut s = RunState::new(
22324            PathBuf::from("/repo"),
22325            "main".to_owned(),
22326            "abc1234".to_owned(),
22327            "add retries".to_owned(),
22328            Config::default(),
22329        );
22330        s.reviews = vec![round];
22331        s
22332    }
22333
22334    fn finding(id: &str, severity: Severity, title: &str) -> crate::verdict::Finding {
22335        crate::verdict::Finding {
22336            id: id.to_owned(),
22337            severity,
22338            file: None,
22339            line: None,
22340            title: title.to_owned(),
22341            detail: String::new(),
22342        }
22343    }
22344
22345    #[test]
22346    fn pr_body_names_open_findings_and_declined_ones() {
22347        let round = ReviewRound {
22348            round: 2,
22349            head: "deadbee".to_owned(),
22350            verified_head: None,
22351            verified_at: None,
22352            reviews: vec![ReviewRecord {
22353                attempts: 0,
22354                reviewer: 1,
22355                agent: "alpha".to_owned(),
22356                summary: String::new(),
22357                findings: vec![finding("R2-1-1", Severity::Minor, "unused import")],
22358                vote: None,
22359                failed: None,
22360                duration_ms: 0,
22361            }],
22362            e2e: vec![CommandOutcome {
22363                command: "cargo test".to_owned(),
22364                code: Some(0),
22365                output_tail: String::new(),
22366                duration_ms: 0,
22367                resource_blocked: false,
22368            }],
22369            verify_retried: false,
22370            e2e_deferred: false,
22371            e2e_defer_reason: None,
22372            fix: Some(FixRecord {
22373                agent: "alpha".to_owned(),
22374                addressed: Vec::new(),
22375                rejected: vec![crate::verdict::Rejection {
22376                    id: "R1-1-1".to_owned(),
22377                    why: "not reachable from any caller".to_owned(),
22378                }],
22379                notes: String::new(),
22380                committed: true,
22381                failed: None,
22382                duration_ms: 0,
22383                continuation: None,
22384            }),
22385            blocking: 0,
22386            answered: 1,
22387            expected: 1,
22388            clean: false,
22389            progressed: true,
22390            vote_split: false,
22391            reconsideration: Vec::new(),
22392            verdict: None,
22393        };
22394        let state = state_with_round(round);
22395        let body = pr_message(&state, 'A').body;
22396
22397        assert!(body.contains("add retries"), "the task must still be there");
22398        assert!(body.contains("R2-1-1"), "{body}");
22399        assert!(!body.contains("unused import"), "{body}");
22400        assert!(body.contains("R1-1-1"), "the declined finding: {body}");
22401        assert!(
22402            !body.contains("not reachable from any caller"),
22403            "the reason it was declined: {body}"
22404        );
22405    }
22406
22407    #[test]
22408    fn pr_body_says_nothing_extra_when_the_round_was_clean() {
22409        let round = ReviewRound {
22410            round: 1,
22411            head: "deadbee".to_owned(),
22412            verified_head: None,
22413            verified_at: None,
22414            reviews: vec![ReviewRecord {
22415                attempts: 0,
22416                reviewer: 1,
22417                agent: "alpha".to_owned(),
22418                summary: String::new(),
22419                findings: Vec::new(),
22420                vote: None,
22421                failed: None,
22422                duration_ms: 0,
22423            }],
22424            e2e: Vec::new(),
22425            verify_retried: false,
22426            e2e_deferred: false,
22427            e2e_defer_reason: None,
22428            fix: None,
22429            blocking: 0,
22430            answered: 1,
22431            expected: 1,
22432            clean: true,
22433            progressed: false,
22434            vote_split: false,
22435            reconsideration: Vec::new(),
22436            verdict: None,
22437        };
22438        let state = state_with_round(round);
22439        let body = pr_message(&state, 'A').body;
22440        assert!(!body.contains("Open review findings"), "{body}");
22441        assert!(!body.contains("Declined"), "{body}");
22442    }
22443
22444    fn state_with_summary(instruction: &str, summary: &str) -> RunState {
22445        let mut state = RunState::new(
22446            PathBuf::from("/repo"),
22447            "main".to_owned(),
22448            "abc1234".to_owned(),
22449            instruction.to_owned(),
22450            Config::default(),
22451        );
22452        // These fixtures test execution flow, independent of host disk capacity.
22453        state.config.disk.min_free_bytes = 0;
22454        state.candidates.push(Candidate {
22455            index: 0,
22456            label: 'A',
22457            agent: "alpha".to_owned(),
22458            branch: "magi/x/A".to_owned(),
22459            worktree: PathBuf::from("/wt"),
22460            summary: summary.to_owned(),
22461            stat: String::new(),
22462            files: 1,
22463            commits: 1,
22464            empty: false,
22465            failed: None,
22466            verified_noop: None,
22467            folded: false,
22468            duration_ms: 0,
22469        });
22470        state
22471    }
22472
22473    fn review_state(subjects: &[&str]) -> RunState {
22474        let mut state = state_with_summary(
22475            "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",
22476            "",
22477        );
22478        state.candidates[0].agent = EXISTING_BRANCH.to_owned();
22479        state.reviewed_commits = Some(subjects.iter().map(|s| (*s).to_owned()).collect());
22480        state
22481    }
22482
22483    /// A branch rebased onto a main that moved past the recorded
22484    /// `base_commit` is titled from its own first commit, never main's.
22485    #[tokio::test]
22486    async fn a_rebased_review_branch_is_titled_from_its_own_commits() {
22487        ask_test_home();
22488        let tmp = tempfile::tempdir().unwrap();
22489        let repo = tmp.path().join("repo");
22490        std::fs::create_dir_all(&repo).unwrap();
22491        init_repo(&repo);
22492        let origin = tmp.path().join("origin.git");
22493        let g = |dir: &Path, args: &[&str]| {
22494            let out = std::process::Command::new("git")
22495                .args(args)
22496                .current_dir(dir)
22497                .quiet()
22498                .output()
22499                .expect("spawn git");
22500            assert!(
22501                out.status.success(),
22502                "git {args:?}: {}",
22503                String::from_utf8_lossy(&out.stderr)
22504            );
22505        };
22506        g(
22507            tmp.path(),
22508            &[
22509                "clone",
22510                "--bare",
22511                "-q",
22512                repo.to_str().unwrap(),
22513                origin.to_str().unwrap(),
22514            ],
22515        );
22516        g(
22517            &repo,
22518            &["remote", "add", "origin", origin.to_str().unwrap()],
22519        );
22520        let c1 = git::rev_parse(&repo, "main").await.unwrap();
22521
22522        // Main moves on; the branch is built on top of the new main.
22523        std::fs::write(repo.join("dep.txt"), "bump\n").unwrap();
22524        g(&repo, &["add", "-A"]);
22525        g(
22526            &repo,
22527            &["commit", "-q", "-m", "chore(deps): update a crate"],
22528        );
22529        g(&repo, &["push", "-q", "origin", "main"]);
22530        g(&repo, &["checkout", "-q", "-b", "feat/own"]);
22531        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
22532        g(&repo, &["add", "-A"]);
22533        g(
22534            &repo,
22535            &["commit", "-q", "-m", "fix(daemon): apply a chosen action"],
22536        );
22537        g(&repo, &["checkout", "-q", "main"]);
22538
22539        let start = review_base(&repo, "origin", "main", &c1, "feat/own").await;
22540        assert_eq!(start, git::rev_parse(&repo, "main").await.unwrap());
22541        // Without a readable tracking ref the recorded base's merge base is used.
22542        let fallback = review_base(&repo, "nowhere", "main", &c1, "feat/own").await;
22543        assert_eq!(fallback, c1);
22544
22545        let mut state = review_state(&[
22546            "chore(deps): update a crate",
22547            "fix(daemon): apply a chosen action",
22548        ]);
22549        state.repo = repo.clone();
22550        state.base_branch = "main".to_owned();
22551        state.base_commit = c1;
22552        refresh_reviewed_commits(&mut state, "feat/own").await;
22553        assert_eq!(
22554            state.reviewed_commits,
22555            Some(vec!["fix(daemon): apply a chosen action".to_owned()])
22556        );
22557        assert_eq!(
22558            review_title(&state).as_deref(),
22559            Some("fix(daemon): apply a chosen action")
22560        );
22561        assert_eq!(
22562            leaked_subjects(&state, "feat/own").await,
22563            Some(vec!["chore(deps): update a crate".to_owned()])
22564        );
22565        // A stale tracking ref is still used when the fetch fails, but the
22566        // leak list is withheld.
22567        state.config.merge.remote = "nowhere".to_owned();
22568        assert_eq!(leaked_subjects(&state, "feat/own").await, None);
22569    }
22570
22571    /// A review-only run whose winner is `feat/own`, checked out in `repo`,
22572    /// with `origin/main` one commit behind it, and a summarizing agent that
22573    /// prints whatever `reply` holds.
22574    struct SummaryFixture {
22575        _tmp: tempfile::TempDir,
22576        repo: PathBuf,
22577        reply: PathBuf,
22578        runner: Runner,
22579    }
22580
22581    fn summary_fixture() -> SummaryFixture {
22582        ask_test_home();
22583        let tmp = tempfile::tempdir().unwrap();
22584        let repo = tmp.path().join("repo");
22585        std::fs::create_dir_all(&repo).unwrap();
22586        init_repo(&repo);
22587        let origin = tmp.path().join("origin.git");
22588        let g = |args: &[&str]| {
22589            let out = std::process::Command::new("git")
22590                .args(args)
22591                .current_dir(&repo)
22592                .quiet()
22593                .output()
22594                .expect("spawn git");
22595            assert!(
22596                out.status.success(),
22597                "git {args:?}: {}",
22598                String::from_utf8_lossy(&out.stderr)
22599            );
22600        };
22601        g(&["init", "-q", "--bare", origin.to_str().unwrap()]);
22602        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
22603        g(&["push", "-q", "origin", "main"]);
22604        g(&["checkout", "-q", "-b", "feat/own"]);
22605        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
22606        g(&["add", "-A"]);
22607        g(&["commit", "-q", "-m", "feat(own): add the own file"]);
22608        let reply = tmp.path().join("reply.txt");
22609        std::fs::write(
22610            &reply,
22611            "TITLE: feat(own): add the own file\nAdds `own.txt` so the first summary is read.",
22612        )
22613        .unwrap();
22614        let mut runner = runner_at(RunStatus::Gating);
22615        let mut state = review_state(&["feat(own): add the own file"]);
22616        state.repo = repo.clone();
22617        state.base_branch = "main".to_owned();
22618        state.candidates[0].branch = "feat/own".to_owned();
22619        state.candidates[0].worktree = repo.clone();
22620        let mut author = spec("alpha");
22621        author.command = vec!["sh".into(), "-c".into(), "cat \"$REPLY_FILE\"".into()];
22622        author
22623            .env
22624            .insert("REPLY_FILE".into(), reply.to_string_lossy().into_owned());
22625        state.config.agents = vec![author];
22626        runner.state = state;
22627        SummaryFixture {
22628            _tmp: tmp,
22629            repo,
22630            reply,
22631            runner,
22632        }
22633    }
22634
22635    async fn posted(f: &mut SummaryFixture) -> PrMessage {
22636        let winner = f.runner.state.candidates[0].clone();
22637        f.runner
22638            .guarded_pr_message(&winner, None, true)
22639            .await
22640            .unwrap()
22641            .expect("an English description never parks")
22642    }
22643
22644    fn clean_round_with_minor_findings() -> ReviewRound {
22645        let mut round = passing_round(2, None);
22646        round.verdict = Some(crate::verdict::ReviewVote::ApproveWithFindings);
22647        round.reviews = vec![ReviewRecord {
22648            attempts: 0,
22649            reviewer: 1,
22650            agent: "alpha".into(),
22651            summary: "内部レビュー".into(),
22652            findings: vec![
22653                finding("R2-1-1", Severity::Minor, "未修正の懸念その一"),
22654                finding("R2-1-2", Severity::Minor, "未修正の懸念その二"),
22655            ],
22656            vote: Some(crate::verdict::ReviewVote::ApproveWithFindings),
22657            failed: None,
22658            duration_ms: 0,
22659        }];
22660        round
22661    }
22662
22663    #[tokio::test]
22664    async fn public_descriptions_cover_minor_findings_from_clean_rounds_in_both_modes() {
22665        for review_only in [false, true] {
22666            let mut f = summary_fixture();
22667            if !review_only {
22668                f.runner.state.candidates[0].agent = "alpha".into();
22669            }
22670            f.runner.state.reviews = vec![clean_round_with_minor_findings()];
22671            assert!(f.runner.state.reviews[0].clean);
22672            assert!(f.runner.state.reviews[0].fix.is_none());
22673            assert!(f.runner.state.open_findings().is_empty());
22674            assert_eq!(
22675                crate::pr_outcome::required_finding_ids(&f.runner.state),
22676                ["R2-1-1", "R2-1-2"]
22677            );
22678            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
22679            let evidence = crate::pr_outcome::summary_evidence(
22680                &f.runner.state,
22681                crate::pr_outcome::FinalHead::At(&head),
22682            );
22683            assert!(
22684                evidence.contains("未修正の懸念その一") && evidence.contains("未修正の懸念その二")
22685            );
22686            // The ordinary reply omits both IDs: no cached description is adopted.
22687            let omitted = posted(&mut f).await;
22688            assert!(omitted.body.contains("No description"));
22689            assert!(omitted.body.contains("`R2-1-1` [Minor]"));
22690            assert!(omitted.body.contains("`R2-1-2` [Minor]"));
22691            assert!(f.runner.state.change_summary.is_none());
22692            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();
22693            let described = posted(&mut f).await;
22694            assert!(described.body.contains("improve documentation for callers"));
22695            assert!(described.body.contains("remaining edge case"));
22696            assert!(described.body.contains("## Open review findings"));
22697            assert!(!described.body.contains("未修正"));
22698        }
22699    }
22700
22701    async fn rewrite_fixture_with_findings(review_only: bool, reply: &str) -> SummaryFixture {
22702        let mut f = summary_fixture();
22703        if !review_only {
22704            f.runner.state.candidates[0].agent = "alpha".into();
22705        }
22706        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
22707        let mut fixed = round_with_notes(1, Some("日本語の内部修正報告"));
22708        fixed
22709            .fix
22710            .as_mut()
22711            .unwrap()
22712            .rejected
22713            .push(crate::verdict::Rejection {
22714                id: "R1-1-1".into(),
22715                why: "呼び出されないコードのため辞退".into(),
22716            });
22717        let mut clean = clean_round_with_minor_findings();
22718        clean.verified_head = Some(head.clone());
22719        f.runner.state.reviews = vec![fixed, clean];
22720        ok_gate(&mut f.runner.state, Some(&head));
22721        std::fs::write(&f.reply, "TITLE: fix: public description\n日本語の公開用説明です。R1-1-1 は辞退。R2-1-1 と R2-1-2 の懸念が残ります。").unwrap();
22722        f.runner.state.config.agents.push(scripted("beta", reply));
22723        f.runner.state.config.roles.language_judge =
22724            Some(crate::config::AgentChoice::One("beta".into()));
22725        f
22726    }
22727
22728    #[tokio::test]
22729    async fn posting_rewrite_retains_structured_evidence_and_finding_explanations() {
22730        for review_only in [false, true] {
22731            let mut f = rewrite_fixture_with_findings(review_only,
22732                "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;
22733            let m = posted(&mut f).await;
22734            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
22735            let expected =
22736                public_pr_evidence(&f.runner.state, crate::pr_outcome::FinalHead::At(&head));
22737            assert!(m.body.contains(&expected));
22738            assert!(m.body.contains("## Review rounds"));
22739            assert!(
22740                m.body
22741                    .contains("Gate (`verify.gate`): passed on the final commit")
22742            );
22743            assert!(
22744                m.body
22745                    .contains("Tests (`verify.e2e`): passed on the final commit")
22746            );
22747            let c = f.runner.state.change_summary.as_ref().unwrap();
22748            assert!(
22749                m.body
22750                    .contains(&format!("Evidence: final diff `{}`..`{}`", c.base, head))
22751            );
22752            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
22753            assert!(crate::pr_outcome::covers_required_findings(
22754                &f.runner.state,
22755                &m.body
22756            ));
22757            assert!(m.body.contains("documentation remains incomplete"));
22758            assert!(!m.body.contains("内部") && !m.body.contains("辞退"));
22759            assert_eq!(f.runner.state.seats["github-text-rewrite"].turns, 1);
22760            assert!(f.runner.state.github_text.is_none());
22761        }
22762    }
22763
22764    #[tokio::test]
22765    async fn posting_rewrite_missing_required_finding_context_is_not_offered_or_published() {
22766        for review_only in [false, true] {
22767            for reply in [
22768                "TITLE: fix: public description\nA short English description.",
22769                "TITLE: fix: public description\nR1-1-1 and R2-1-2 remain; R2-1-1-extra is a different ID.",
22770            ] {
22771                let mut f = rewrite_fixture_with_findings(review_only, reply).await;
22772                let winner = f.runner.state.candidates[0].clone();
22773                let posted = f
22774                    .runner
22775                    .guarded_pr_message(&winner, None, true)
22776                    .await
22777                    .unwrap();
22778                assert!(posted.is_none());
22779                assert!(f.runner.state.parked);
22780                let withheld = f.runner.state.github_text.as_ref().unwrap();
22781                assert!(
22782                    withheld.rewrite.is_none(),
22783                    "an incomplete rewrite must not be selectable"
22784                );
22785                let q = ask::Questions::open()
22786                    .get(withheld.question.as_ref().unwrap())
22787                    .unwrap();
22788                assert!(
22789                    !q.choices
22790                        .contains(&crate::github_text::USE_REWRITE.to_owned())
22791                );
22792                assert!(
22793                    q.detail.contains("R1-1-1")
22794                        && q.detail.contains("R2-1-1")
22795                        && q.detail.contains("R2-1-2")
22796                );
22797            }
22798        }
22799    }
22800
22801    #[tokio::test]
22802    async fn japanese_reports_stay_local_in_both_public_run_modes() {
22803        for review_only in [false, true] {
22804            let mut f = summary_fixture();
22805            if !review_only {
22806                f.runner.state.candidates[0].agent = "alpha".into();
22807            }
22808            f.runner.state.instruction = "内部タスクの説明".into();
22809            f.runner.state.candidates[0].summary = "内部の候補報告".into();
22810            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
22811            f.runner.state.reviews = vec![
22812                round_with_notes(1, Some("コミットできません。テストは実行できません。")),
22813                round_with_notes(2, Some("二回目の内部修正報告です。")),
22814                passing_round(3, Some(&head)),
22815            ];
22816            f.runner.state.reviews[0].fix.as_mut().unwrap().addressed = vec!["R1-1-1".into()];
22817            ok_gate(&mut f.runner.state, Some(&head));
22818            let captured = f.repo.join("public-prompt.txt");
22819            let author = &mut f.runner.state.config.agents[0];
22820            author.command = vec![
22821                "sh".into(),
22822                "-c".into(),
22823                "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
22824            ];
22825            author.env.insert(
22826                "PROMPT_FILE".into(),
22827                captured.to_string_lossy().into_owned(),
22828            );
22829            let m = posted(&mut f).await;
22830            assert!(m.body.contains("Adds `own.txt`"));
22831            assert!(m.body.contains("Round 1") && m.body.contains("Round 2"));
22832            assert!(m.body.contains("R1-1-1"));
22833            assert!(
22834                m.body
22835                    .contains("Gate (`verify.gate`): passed on the final commit")
22836            );
22837            assert!(
22838                m.body
22839                    .contains("Tests (`verify.e2e`): passed on the final commit")
22840            );
22841            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
22842            assert!(!m.body.contains("内部") && !m.body.contains("できません"));
22843            let prompt = std::fs::read_to_string(captured).unwrap();
22844            assert!(prompt.contains(&format!(
22845                "git diff {} {head}",
22846                f.runner.state.change_summary.as_ref().unwrap().base
22847            )));
22848            assert!(!prompt.contains("二回目") && !prompt.contains("コミットできません"));
22849            assert_eq!(
22850                f.runner.state.reviews[1].fix.as_ref().unwrap().notes,
22851                "二回目の内部修正報告です。"
22852            );
22853        }
22854    }
22855
22856    #[tokio::test]
22857    async fn public_generation_failure_never_falls_back_to_internal_notes_and_resume_retries() {
22858        for review_only in [false, true] {
22859            let mut f = summary_fixture();
22860            if !review_only {
22861                f.runner.state.candidates[0].agent = "alpha".into();
22862            }
22863            f.runner.state.candidates[0].summary = "内部報告を公開しない".into();
22864            f.runner.state.reviews = vec![round_with_notes(1, Some("日本語の修正報告"))];
22865            std::fs::write(&f.reply, "no usable description").unwrap();
22866            let failed = posted(&mut f).await;
22867            assert!(
22868                failed
22869                    .body
22870                    .contains("No description of what this change does could be generated")
22871            );
22872            assert!(failed.body.is_ascii());
22873            assert!(f.runner.state.github_text.is_none());
22874            assert!(f.runner.state.change_summary.is_none());
22875            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
22876            let evidence = crate::pr_outcome::summary_evidence(
22877                &f.runner.state,
22878                crate::pr_outcome::FinalHead::At(&head),
22879            );
22880            let fp = crate::pr_outcome::summary_fingerprint(&f.runner.state, &evidence);
22881            assert!(
22882                crate::run::artifact_path(&f.runner.state, &format!("public-description-{fp}.md"))
22883                    .exists()
22884            );
22885            f.runner.state =
22886                serde_json::from_str(&serde_json::to_string(&f.runner.state).unwrap()).unwrap();
22887            std::fs::write(
22888                &f.reply,
22889                "TITLE: feat(own): add the own file\nAdds the committed own file.",
22890            )
22891            .unwrap();
22892            let retried = posted(&mut f).await;
22893            assert!(retried.body.contains("Adds the committed own file."));
22894            assert_eq!(
22895                f.runner.state.reviews[0].fix.as_ref().unwrap().notes,
22896                "日本語の修正報告"
22897            );
22898        }
22899    }
22900
22901    #[tokio::test]
22902    async fn same_head_verification_and_findings_invalidate_public_prose() {
22903        let mut f = summary_fixture();
22904        posted(&mut f).await;
22905        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
22906        let original = f
22907            .runner
22908            .state
22909            .change_summary
22910            .as_ref()
22911            .unwrap()
22912            .evidence
22913            .clone();
22914        ok_gate(&mut f.runner.state, Some(&head));
22915        std::fs::write(
22916            &f.reply,
22917            "TITLE: feat(own): add the own file\nDescribes the now verified final change.",
22918        )
22919        .unwrap();
22920        let verified = posted(&mut f).await;
22921        assert!(verified.body.contains("now verified"));
22922        assert_ne!(
22923            f.runner.state.change_summary.as_ref().unwrap().evidence,
22924            original
22925        );
22926        let mut round = round_with_notes(1, Some("内部報告"));
22927        round.reviews.push(ReviewRecord {
22928            attempts: 0,
22929            reviewer: 1,
22930            agent: "alpha".into(),
22931            summary: "内部レビュー".into(),
22932            findings: vec![finding("R1-1-1", Severity::Minor, "残っている懸念")],
22933            vote: None,
22934            failed: None,
22935            duration_ms: 0,
22936        });
22937        round
22938            .fix
22939            .as_mut()
22940            .unwrap()
22941            .rejected
22942            .push(crate::verdict::Rejection {
22943                id: "R1-1-1".into(),
22944                why: "呼び出し元から到達できない".into(),
22945            });
22946        f.runner.state.reviews = vec![round];
22947        // A description omitting the required ID is unusable, even with a title.
22948        let omitted = posted(&mut f).await;
22949        assert!(omitted.body.contains("No description"));
22950        assert!(omitted.body.contains("R1-1-1"));
22951        assert!(!omitted.body.contains("到達"));
22952        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();
22953        let described = posted(&mut f).await;
22954        assert!(described.body.contains("unreachable from callers"));
22955        assert!(described.body.contains("R1-1-1"));
22956        assert!(!described.body.contains("到達"));
22957        let evidence = f
22958            .runner
22959            .state
22960            .change_summary
22961            .as_ref()
22962            .unwrap()
22963            .evidence
22964            .clone();
22965        f.runner.state.reviews[0].fix.as_mut().unwrap().rejected[0].why = "別の根拠".into();
22966        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: decline rationale updated after review.").unwrap();
22967        assert!(posted(&mut f).await.body.contains("rationale updated"));
22968        assert_ne!(
22969            f.runner.state.change_summary.as_ref().unwrap().evidence,
22970            evidence
22971        );
22972        // Old serialized summaries have no evidence fingerprint and must regenerate.
22973        f.runner
22974            .state
22975            .change_summary
22976            .as_mut()
22977            .unwrap()
22978            .evidence
22979            .clear();
22980        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: regenerated under the current specification.").unwrap();
22981        assert!(posted(&mut f).await.body.contains("current specification"));
22982    }
22983
22984    #[tokio::test]
22985    async fn a_review_only_run_with_no_fixer_gets_a_summary_of_the_final_diff() {
22986        let mut f = summary_fixture();
22987        let m = posted(&mut f).await;
22988        assert_eq!(m.title, "feat(own): add the own file");
22989        assert!(
22990            m.body
22991                .contains("## Summary\n\nAdds `own.txt` so the first summary is read."),
22992            "{}",
22993            m.body
22994        );
22995        assert!(!m.body.contains("## Review fixes"), "{}", m.body);
22996        assert!(m.body.contains("Evidence: final diff"), "{}", m.body);
22997        assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
22998        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
22999        let base = git::rev_parse(&f.repo, "origin/main").await.unwrap();
23000        let kept = f.runner.state.change_summary.as_ref().unwrap();
23001        assert_eq!(
23002            (kept.head.as_str(), kept.base.as_str()),
23003            (head.as_str(), base.as_str())
23004        );
23005        assert!(!f.runner.state.seats["change-summary"].key.is_empty());
23006    }
23007
23008    #[tokio::test]
23009    async fn review_only_summary_receives_the_configured_github_language() {
23010        let mut f = summary_fixture();
23011        f.runner.state.config.graph.github_language = "ja".into();
23012        let captured = f.repo.join("summary-prompt.txt");
23013        let author = &mut f.runner.state.config.agents[0];
23014        author.command = vec![
23015            "sh".into(),
23016            "-c".into(),
23017            "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
23018        ];
23019        author.env.insert(
23020            "PROMPT_FILE".into(),
23021            captured.to_string_lossy().into_owned(),
23022        );
23023        std::fs::write(
23024            &f.reply,
23025            "TITLE: feat(own): ファイルを追加\nown.txt を追加します。",
23026        )
23027        .unwrap();
23028        let m = posted(&mut f).await;
23029        let prompt = std::fs::read_to_string(captured).unwrap();
23030        assert!(prompt.contains("Write the TITLE line and the Markdown description in Japanese."));
23031        assert!(!prompt.contains("in English"));
23032        assert_eq!(m.title, "feat(own): ファイルを追加");
23033        assert!(m.body.contains("own.txt を追加します。"));
23034    }
23035
23036    #[tokio::test]
23037    async fn review_fixes_come_after_the_whole_change_summary() {
23038        let mut f = summary_fixture();
23039        f.runner.state.reviews = vec![
23040            round_with_notes(1, Some("handled the PATH case")),
23041            round_with_notes(2, None),
23042        ];
23043        let m = posted(&mut f).await;
23044        let summary = m.body.find("## Summary").expect("summary");
23045        let fixes = m.body.find("## Review rounds").expect("review rounds");
23046        assert!(summary < fixes, "{}", m.body);
23047        assert!(!m.body.contains("handled the PATH case"), "{}", m.body);
23048        assert!(m.body.contains("## Final verification"), "{}", m.body);
23049    }
23050
23051    #[tokio::test]
23052    async fn a_changed_final_diff_invalidates_the_earlier_summary() {
23053        let mut f = summary_fixture();
23054        let first = posted(&mut f).await;
23055        let first_head = f.runner.state.change_summary.clone().unwrap().head;
23056        // The same head reuses the record: a different reply is not read.
23057        std::fs::write(&f.reply, "TITLE: feat(own): other\nNot read yet.").unwrap();
23058        let again = posted(&mut f).await;
23059        assert_eq!((again.title, again.body), (first.title, first.body));
23060
23061        let g = |args: &[&str]| {
23062            let out = std::process::Command::new("git")
23063                .args(args)
23064                .current_dir(&f.repo)
23065                .quiet()
23066                .output()
23067                .expect("spawn git");
23068            assert!(out.status.success(), "git {args:?}");
23069        };
23070        std::fs::write(f.repo.join("more.txt"), "more\n").unwrap();
23071        g(&["add", "-A"]);
23072        g(&["commit", "-q", "-m", "fix(own): handle more"]);
23073        let second = posted(&mut f).await;
23074        let kept = f.runner.state.change_summary.clone().unwrap();
23075        assert_ne!(kept.head, first_head);
23076        assert!(second.body.contains("Not read yet."), "{}", second.body);
23077        assert!(!second.body.contains("so the first summary is read"));
23078        assert_eq!(second.title, "feat(own): other");
23079    }
23080
23081    #[tokio::test]
23082    async fn an_unavailable_summary_is_stated_and_never_invented() {
23083        let mut f = summary_fixture();
23084        std::fs::write(&f.reply, "no title line here").unwrap();
23085        let m = posted(&mut f).await;
23086        assert!(
23087            m.body
23088                .contains("No description of what this change does could be generated"),
23089            "{}",
23090            m.body
23091        );
23092        assert!(m.body.contains("internal reports remain in local records"));
23093        assert!(f.runner.state.change_summary.is_none());
23094        assert!(!m.body.contains("## Commits under review"), "{}", m.body);
23095        // A preview asks nobody and claims nothing.
23096        let winner = f.runner.state.candidates[0].clone();
23097        let preview = f
23098            .runner
23099            .guarded_pr_message(&winner, None, false)
23100            .await
23101            .unwrap()
23102            .unwrap();
23103        assert!(!preview.body.contains("## Summary"), "{}", preview.body);
23104    }
23105
23106    #[test]
23107    fn pr_message_review_single_commit_uses_its_subject() {
23108        let state = review_state(&["feat(nats): per-role user"]);
23109        let m = pr_message(&state, 'A');
23110        assert_eq!(m.title, "feat(nats): per-role user");
23111        assert!(!m.body.contains("Review the work already"), "{}", m.body);
23112        assert!(m.body.contains("## Commits under review"), "{}", m.body);
23113    }
23114
23115    #[test]
23116    fn pr_message_review_multi_commit_takes_the_oldest() {
23117        let state = review_state(&["feat: the change", "fix: typo", "fix: again"]);
23118        let m = pr_message(&state, 'A');
23119        assert_eq!(m.title, "feat: the change");
23120        for s in ["feat: the change", "fix: typo", "fix: again"] {
23121            assert!(m.body.contains(&format!("- {s}\n")), "{}", m.body);
23122        }
23123    }
23124
23125    #[test]
23126    fn pr_message_review_without_a_usable_first_subject_is_neutral() {
23127        for first in ["日本語の件名", "", "magi: candidate A (uncommitted work)"] {
23128            let mut state = review_state(&[first, "fix: later fixup"]);
23129            state.candidates[0].branch = "機能/ログイン".to_owned();
23130            let m = pr_message(&state, 'A');
23131            assert!(
23132                m.title.starts_with("chore: land candidate A of run"),
23133                "{}",
23134                m.title
23135            );
23136        }
23137    }
23138
23139    fn facts(commits: &[(&str, &str)], stat: &str) -> BranchFacts {
23140        BranchFacts {
23141            commits: commits
23142                .iter()
23143                .map(|(s, b)| ((*s).to_owned(), (*b).to_owned()))
23144                .collect(),
23145            stat: stat.to_owned(),
23146        }
23147    }
23148
23149    fn round_with_notes(round: usize, notes: Option<&str>) -> ReviewRound {
23150        let mut r = review_round(true, 0, 1, 1, true, true);
23151        r.round = round;
23152        r.fix = notes.map(|n| FixRecord {
23153            agent: "fixer".to_owned(),
23154            addressed: Vec::new(),
23155            rejected: Vec::new(),
23156            notes: n.to_owned(),
23157            committed: true,
23158            failed: None,
23159            duration_ms: 0,
23160            continuation: None,
23161        });
23162        r
23163    }
23164
23165    #[test]
23166    fn pr_message_review_with_branch_facts_uses_commits_and_stat() {
23167        let state = review_state(&["ignored"]);
23168        let f = facts(
23169            &[
23170                (
23171                    "fix(login): resolve PATH on macOS",
23172                    "Login shells skip rc files.",
23173                ),
23174                ("fix: address review", ""),
23175            ],
23176            " src/a.rs | 2 +-\n 1 file changed, 1 insertion(+), 1 deletion(-)",
23177        );
23178        let m = pr_message_with(&state, 'A', Some(&f));
23179        assert_eq!(m.title, "fix(login): resolve PATH on macOS");
23180        assert!(
23181            m.body
23182                .contains("- fix(login): resolve PATH on macOS\n  Login shells skip rc files.\n"),
23183            "{}",
23184            m.body
23185        );
23186        assert!(m.body.contains("- fix: address review\n"), "{}", m.body);
23187        assert!(m.body.contains("## Diff stat"), "{}", m.body);
23188        assert!(m.body.contains("src/a.rs | 2 +-"), "{}", m.body);
23189        for banned in [
23190            "Review the work already",
23191            "no task statement",
23192            "Original task",
23193        ] {
23194            assert!(!m.body.contains(banned), "{banned}: {}", m.body);
23195        }
23196        assert!(m.body.ends_with("magi:candidate-a\n"), "{}", m.body);
23197    }
23198
23199    #[test]
23200    fn pr_message_review_truncates_a_huge_first_commit_body() {
23201        let state = review_state(&["ignored"]);
23202        let f = facts(
23203            &[("feat: big", &"x".repeat(70_000)), ("fix: later", "")],
23204            "s",
23205        );
23206        let m = pr_message_with(&state, 'A', Some(&f));
23207        assert!(m.body.len() < 30_000, "{}", m.body.len());
23208        assert!(m.body.contains("(truncated)"), "{}", m.body.len());
23209        assert!(
23210            m.body.contains("- ... 1 more commit(s)"),
23211            "{}",
23212            m.body.len()
23213        );
23214        assert!(m.body.ends_with("magi:candidate-a\n"));
23215    }
23216
23217    #[test]
23218    fn pr_message_review_without_facts_falls_back_to_recorded_subjects() {
23219        let m = pr_message_with(&review_state(&["feat: x", "fix: y"]), 'A', None);
23220        assert_eq!(m.title, "feat: x");
23221        assert!(m.body.contains("- fix: y\n"), "{}", m.body);
23222        assert!(!m.body.contains("Diff stat"), "{}", m.body);
23223        assert!(!m.body.contains("no task statement"), "{}", m.body);
23224    }
23225
23226    #[test]
23227    fn pr_message_review_titles_from_the_branch_name_when_subjects_are_unusable() {
23228        let mut state = review_state(&["日本語の件名"]);
23229        state.candidates[0].branch = "fix/macos-login-path".to_owned();
23230        assert_eq!(pr_message(&state, 'A').title, "fix/macos-login-path");
23231        state.candidates[0].branch = "機能/ログイン".to_owned();
23232        assert!(
23233            pr_message(&state, 'A')
23234                .title
23235                .starts_with("chore: land candidate A")
23236        );
23237    }
23238
23239    #[test]
23240    fn pr_message_review_fixes_survive_a_clean_final_round() {
23241        let mut state = review_state(&["feat: x"]);
23242        state.reviews = vec![
23243            round_with_notes(1, Some("handled the PATH case")),
23244            round_with_notes(2, None),
23245        ];
23246        let body = pr_message(&state, 'A').body;
23247        assert!(
23248            body.contains("## Review rounds") && !body.contains("handled the PATH case"),
23249            "{body}"
23250        );
23251        assert!(body.contains("### Round 1"), "{body}");
23252
23253        state.reviews = vec![
23254            round_with_notes(1, Some("first fix")),
23255            round_with_notes(2, Some("")),
23256            round_with_notes(3, Some("second fix")),
23257            round_with_notes(4, None),
23258        ];
23259        let body = pr_message(&state, 'A').body;
23260        assert!(
23261            body.contains("### Round 1") && !body.contains("first fix"),
23262            "{body}"
23263        );
23264        assert!(
23265            body.contains("### Round 3") && !body.contains("second fix"),
23266            "{body}"
23267        );
23268        assert!(body.contains("### Round 2"), "{body}");
23269    }
23270
23271    const FINAL: &str = "abcdef1234567890";
23272
23273    fn passing_round(round: usize, verified: Option<&str>) -> ReviewRound {
23274        let mut r = round_with_notes(round, None);
23275        r.verified_head = verified.map(str::to_owned);
23276        r
23277    }
23278
23279    fn ok_gate(state: &mut RunState, head: Option<&str>) {
23280        state.gate = vec![CommandOutcome {
23281            command: "gate".to_owned(),
23282            code: Some(0),
23283            output_tail: String::new(),
23284            duration_ms: 0,
23285            resource_blocked: false,
23286        }];
23287        state.gate_ran = true;
23288        state.gate_head = head.map(str::to_owned);
23289    }
23290
23291    fn body_at(state: &RunState) -> String {
23292        pr_message_raw(
23293            state,
23294            'A',
23295            None,
23296            crate::pr_outcome::FinalHead::At(FINAL),
23297            ChangeNote::NotAsked,
23298        )
23299        .body
23300    }
23301
23302    const SANDBOXED: &str = "Handled the PATH case.\nI could not commit because of the sandbox. HTTP tests could not run in the sandbox.";
23303
23304    #[test]
23305    fn rescued_commit_and_later_verification_override_the_fixers_limits() {
23306        let mut state = review_state(&["feat: x"]);
23307        state.reviews = vec![
23308            round_with_notes(1, Some(SANDBOXED)),
23309            passing_round(2, Some(FINAL)),
23310        ];
23311        ok_gate(&mut state, Some(FINAL));
23312        let body = body_at(&state);
23313        assert!(!body.contains("Handled the PATH case."), "{body}");
23314        assert!(!body.contains("could not commit"), "{body}");
23315        assert!(!body.contains("could not run"), "{body}");
23316        assert!(
23317            body.contains("The fix is committed on the branch"),
23318            "{body}"
23319        );
23320        assert!(!body.contains("sandbox"), "{body}");
23321        assert!(
23322            body.contains("Tests (`verify.e2e`): passed on the final commit"),
23323            "{body}"
23324        );
23325        assert!(
23326            body.contains("Gate (`verify.gate`): passed on the final commit"),
23327            "{body}"
23328        );
23329        // The raw report is untouched in the record.
23330        assert!(
23331            state.reviews[0]
23332                .fix
23333                .as_ref()
23334                .unwrap()
23335                .notes
23336                .contains("could not commit")
23337        );
23338    }
23339
23340    #[test]
23341    fn unresolved_commit_and_test_limits_stay_and_nothing_claims_success() {
23342        let mut state = review_state(&["feat: x"]);
23343        let mut r1 = round_with_notes(1, Some(SANDBOXED));
23344        r1.fix.as_mut().unwrap().committed = false;
23345        let mut r2 = passing_round(2, Some(FINAL));
23346        r2.e2e[0].code = Some(1);
23347        state.reviews = vec![r1, r2];
23348        let body = body_at(&state);
23349        assert!(!body.contains("could not commit"), "{body}");
23350        assert!(!body.contains("could not run"), "{body}");
23351        assert!(body.contains("This round produced no commit"), "{body}");
23352        assert!(body.contains("Tests (`verify.e2e`): FAILED"), "{body}");
23353        assert!(body.contains("Gate (`verify.gate`): not run"), "{body}");
23354        assert!(!body.contains("passed"), "{body}");
23355    }
23356
23357    #[test]
23358    fn verification_on_an_earlier_commit_does_not_supersede_test_limits() {
23359        let mut state = review_state(&["feat: x"]);
23360        state.reviews = vec![
23361            round_with_notes(1, Some(SANDBOXED)),
23362            passing_round(2, Some("0123456789abcdef")),
23363        ];
23364        ok_gate(&mut state, Some("0123456789abcdef"));
23365        let body = body_at(&state);
23366        assert!(!body.contains("HTTP tests could not run"), "{body}");
23367        // The commit claim is still settled by the structured record.
23368        assert!(!body.contains("could not commit"), "{body}");
23369        assert!(
23370            body.contains("passed on an earlier commit (`0123456`)"),
23371            "{body}"
23372        );
23373        assert!(!body.contains("passed on the final commit"), "{body}");
23374
23375        // A gate recorded before `gate_head` existed is "not recorded".
23376        ok_gate(&mut state, None);
23377        let body = body_at(&state);
23378        assert!(
23379            body.contains("passed on a commit that was not recorded"),
23380            "{body}"
23381        );
23382    }
23383
23384    #[test]
23385    fn pr_message_implementation_run_keeps_its_shape_and_marker() {
23386        let state = state_with_summary(
23387            "add retries to the client",
23388            "TITLE: feat: retries\n\nDid it.",
23389        );
23390        let m = pr_message_with(&state, 'A', Some(&facts(&[("x", "")], "s")));
23391        assert_eq!(m.title, "feat: retries");
23392        assert!(
23393            m.body.contains("<summary>Original task</summary>"),
23394            "{}",
23395            m.body
23396        );
23397        assert!(!m.body.contains("Commits under review"), "{}", m.body);
23398        assert!(
23399            m.body
23400                .ends_with(&format!("magi:run/{} magi:candidate-a\n", state.id)),
23401            "{}",
23402            m.body
23403        );
23404    }
23405
23406    #[test]
23407    fn pr_message_review_bounds_a_long_english_subject() {
23408        let long = format!("feat: {}", "word ".repeat(100));
23409        let m = pr_message(&review_state(&[&long]), 'A');
23410        assert!(m.title.starts_with("feat: word"), "{}", m.title);
23411        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
23412    }
23413
23414    #[test]
23415    fn pr_message_implementation_run_is_unchanged_by_review_support() {
23416        let state = state_with_summary("add retries\n\ndetails", "- did some things");
23417        let m = pr_message(&state, 'A');
23418        assert_eq!(m.title, "add retries");
23419        assert!(m.body.contains("<summary>Original task</summary>"));
23420        assert!(!m.body.contains("Commits under review"));
23421        assert_eq!(landing_subject_source(&state), state.instruction);
23422    }
23423
23424    #[test]
23425    fn review_run_squash_subject_is_the_change_not_the_prompt() {
23426        let state = review_state(&["feat: the change", "fix: typo"]);
23427        let source = landing_subject_source(&state);
23428        assert_eq!(land::merge_subject("", &source), "feat: the change");
23429        assert_eq!(
23430            land::merge_subject("magi: candidate A (uncommitted work)", &source),
23431            "feat: the change"
23432        );
23433        // An operator's rename still wins.
23434        assert_eq!(
23435            land::merge_subject("feat: renamed by hand", &source),
23436            "feat: renamed by hand"
23437        );
23438        let blank = review_state(&["日本語"]);
23439        assert!(
23440            land::merge_subject("", &landing_subject_source(&blank)).starts_with("chore: land")
23441        );
23442    }
23443
23444    #[test]
23445    fn review_run_drops_a_prompt_shaped_pr_title_at_landing() {
23446        let state = review_state(&["feat: the change"]);
23447        let source = landing_subject_source(&state);
23448        let old = "Review the work already on branch `magi/x/A`. There is no task statement";
23449        assert_eq!(
23450            land::merge_subject(landing_title(&state, old), &source),
23451            "feat: the change"
23452        );
23453        assert_eq!(landing_title(&state, "feat: renamed"), "feat: renamed");
23454        let task = state_with_summary("add retries", "");
23455        assert_eq!(landing_title(&task, old), old);
23456    }
23457
23458    #[test]
23459    fn pr_message_describes_the_change_not_the_task() {
23460        let state = state_with_summary(
23461            "今回やってほしいこと: results projector を直す",
23462            "TITLE: fix(web): batch the runs list reads\n- reads run.json once\n- risk: none",
23463        );
23464        let m = pr_message(&state, 'A');
23465        assert_eq!(m.title, "fix(web): batch the runs list reads");
23466        assert!(
23467            m.body.starts_with("## Summary\n\n- reads run.json once"),
23468            "{}",
23469            m.body
23470        );
23471        assert!(!m.body.contains("TITLE:"), "{}", m.body);
23472        let task_at = m.body.find("今回やってほしいこと").unwrap();
23473        let details_at = m.body.find("<details>").unwrap();
23474        assert!(
23475            details_at < task_at,
23476            "the task lives inside <details>: {}",
23477            m.body
23478        );
23479        assert!(m.body.contains(&format!("magi:run/{}", state.id)));
23480        assert!(m.body.contains("magi:candidate-a"));
23481    }
23482
23483    #[test]
23484    fn pr_message_falls_back_to_the_task_without_a_title_line() {
23485        let state = state_with_summary("\n\nadd retries\n\ndetails", "- did some things");
23486        let m = pr_message(&state, 'A');
23487        assert_eq!(m.title, "add retries");
23488        assert!(
23489            m.body.contains("## Summary\n\n- did some things"),
23490            "{}",
23491            m.body
23492        );
23493
23494        let none = RunState::new(
23495            PathBuf::from("/repo"),
23496            "main".to_owned(),
23497            "abc1234".to_owned(),
23498            "add retries".to_owned(),
23499            Config::default(),
23500        );
23501        let m = pr_message(&none, 'A');
23502        assert_eq!(m.title, "add retries");
23503        assert!(!m.body.contains("## Summary"), "{}", m.body);
23504    }
23505
23506    #[test]
23507    fn pr_message_refuses_the_candidate_commit_subject() {
23508        for bad in [
23509            "TITLE: magi: candidate A (uncommitted work)",
23510            "TITLE: chore: stuff (uncommitted work)",
23511            "TITLE:   ",
23512        ] {
23513            let state = state_with_summary("add retries", bad);
23514            assert_eq!(pr_message(&state, 'A').title, "add retries", "{bad}");
23515        }
23516    }
23517
23518    #[test]
23519    fn pr_message_bounds_a_very_long_task_and_title() {
23520        let long = format!("fix the thing 🎉 {}", "x".repeat(5000));
23521        let state = state_with_summary(&long, "- nothing");
23522        let m = pr_message(&state, 'A');
23523        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
23524        assert!(!m.title.contains('\n'));
23525
23526        let state = state_with_summary("task", &format!("TITLE: feat: {}", "y".repeat(5000)));
23527        let m = pr_message(&state, 'A');
23528        assert!(m.title.starts_with("feat: "));
23529        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
23530        assert_eq!(m.commit_message().lines().next(), Some(m.title.as_str()));
23531    }
23532
23533    fn long_title_of(instruction: &str) -> String {
23534        pr_message(&state_with_summary(instruction, "- nothing"), 'A').title
23535    }
23536
23537    #[test]
23538    fn pr_message_cuts_a_long_english_line_at_its_first_sentence() {
23539        let first = "Make the landing path keep a readable title for long tasks";
23540        let line = format!(
23541            "{first}. {}",
23542            "And then keep going with more words ".repeat(20)
23543        );
23544        let t = long_title_of(&line);
23545        assert_eq!(t, first);
23546        assert!(!t.starts_with("chore: land"));
23547    }
23548
23549    #[test]
23550    fn pr_message_cuts_a_sentenceless_long_line_at_a_word() {
23551        let line = "word ".repeat(200);
23552        let t = long_title_of(&line);
23553        assert!(t.ends_with("word..."), "{t}");
23554        assert!(t.is_ascii() && t.chars().count() <= PR_TITLE_MAX, "{t}");
23555    }
23556
23557    #[test]
23558    fn pr_message_long_non_english_or_letterless_line_is_neutral() {
23559        for line in ["日本語のタスク ".repeat(80), "1234 ".repeat(100)] {
23560            assert!(long_title_of(&line).starts_with("chore: land"), "{line}");
23561        }
23562    }
23563
23564    #[test]
23565    fn pr_message_keeps_a_japanese_title_when_github_language_is_japanese() {
23566        let mut state = state_with_summary("再試行を追加する", "- nothing");
23567        assert!(pr_message(&state, 'A').title.starts_with("chore: land"));
23568        state.config.graph.github_language = "ja".into();
23569        assert_eq!(pr_message(&state, 'A').title, "再試行を追加する");
23570    }
23571
23572    #[test]
23573    fn pr_message_title_limit_is_exact() {
23574        let at = "a".repeat(PR_TITLE_MAX);
23575        assert_eq!(long_title_of(&at), at);
23576        let over = long_title_of(&"a".repeat(PR_TITLE_MAX + 1));
23577        assert!(over.ends_with("..."), "{over}");
23578        assert_eq!(over.chars().count(), PR_TITLE_MAX);
23579    }
23580
23581    #[test]
23582    fn pr_message_judges_the_kept_text_not_what_follows_the_cut() {
23583        let line = format!("{} \u{2014} tail", "alpha beta ".repeat(40));
23584        let t = long_title_of(&line);
23585        assert!(t.ends_with("..."), "{t}");
23586        assert!(t.is_ascii(), "{t}");
23587    }
23588
23589    #[test]
23590    fn pr_message_sentence_cut_skips_abbreviations_and_decimals() {
23591        let line = format!(
23592            "Support several shells, e.g. bash and zsh, at version 1.5 or newer when it matters {}",
23593            "plus more filler words ".repeat(20)
23594        );
23595        let t = long_title_of(&line);
23596        assert!(t.contains("e.g. bash") && t.contains("1.5 or newer"), "{t}");
23597    }
23598
23599    #[test]
23600    fn pr_message_long_title_survives_a_blank_first_line_and_the_squash_subject() {
23601        let line = format!("\n\n# {}", "title words ".repeat(40));
23602        let state = state_with_summary(&line, "- nothing");
23603        let m = pr_message(&state, 'A');
23604        assert!(m.title.starts_with("title words"), "{}", m.title);
23605        assert_eq!(
23606            land::merge_subject(&m.title, &landing_subject_source(&state)),
23607            m.title
23608        );
23609        // An operator's rename wins untouched.
23610        assert_eq!(
23611            land::merge_subject("feat: renamed by hand", &landing_subject_source(&state)),
23612            "feat: renamed by hand"
23613        );
23614    }
23615
23616    #[tokio::test]
23617    async fn github_text_rewrite_is_bounded_and_falls_back() {
23618        crate::run::pin_test_home();
23619        for (reply, accepted) in [
23620            (
23621                "TITLE: fix: retries\nAdd retries for failed requests.",
23622                true,
23623            ),
23624            (
23625                "TITLE: fix: retries\n日本語の説明をもう一度書きます。",
23626                false,
23627            ),
23628            (
23629                "TITLE: fix: retries\nAdd retries for failed requests. Use token=secret",
23630                true,
23631            ),
23632            (
23633                "TITLE: fix: retries\nAdd retries for failed requests. Example: password=\"prefix\\\"secret tail\"",
23634                true,
23635            ),
23636            (
23637                "TITLE: fix: retries token=secret\nAdd retries for failed requests. Example: password=\"日本語の秘密secret\"",
23638                true,
23639            ),
23640            (
23641                "TITLE: fix: retries\n日本語の説明です。 token=secret",
23642                false,
23643            ),
23644            ("TITLE: fix: retries\n", false),
23645        ] {
23646            let dir = tempfile::tempdir().unwrap();
23647            let mut runner = runner_at(RunStatus::Gating);
23648            runner.state = state_with_summary(
23649                "add retries",
23650                "TITLE: fix: retries\n日本語の説明を書きます。",
23651            );
23652            runner.state.repo = dir.path().to_owned();
23653            runner.state.candidates[0].worktree = dir.path().to_owned();
23654            let mut author = spec("alpha");
23655            author.command = vec![
23656                "sh".into(),
23657                "-c".into(),
23658                "printf '%s' \"$REWRITE_REPLY\"".into(),
23659            ];
23660            author.env.insert("REWRITE_REPLY".into(), reply.into());
23661            runner.state.config.agents = vec![author];
23662            seed_public_summary(&mut runner);
23663            let winner = runner.state.candidates[0].clone();
23664            let first = runner
23665                .guarded_pr_message(&winner, None, true)
23666                .await
23667                .unwrap();
23668            let message = if accepted {
23669                first.expect("a passing rewrite never asks")
23670            } else {
23671                // Withheld: the run parks on a question and posts nothing yet.
23672                assert!(first.is_none());
23673                assert!(runner.state.parked);
23674                let store = ask::Questions::open();
23675                let asked: Vec<_> = store
23676                    .list()
23677                    .into_iter()
23678                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
23679                    .collect();
23680                assert_eq!(asked.len(), 1);
23681                assert!(!asked[0].detail.contains("secret"));
23682                let rewrite = runner.state.github_text.as_ref().unwrap().rewrite.as_ref();
23683                assert_eq!(rewrite.is_some(), !reply.ends_with('\n'));
23684                assert_eq!(
23685                    asked[0]
23686                        .choices
23687                        .contains(&crate::github_text::USE_REWRITE.to_owned()),
23688                    rewrite.is_some()
23689                );
23690                // Silence: the question lapses and the neutral text is used,
23691                // without a second rewrite call or a second question.
23692                store
23693                    .update(&asked[0].id, |q| {
23694                        q.abandon("test");
23695                        Ok(())
23696                    })
23697                    .unwrap();
23698                let again = runner
23699                    .guarded_pr_message(&winner, None, true)
23700                    .await
23701                    .unwrap()
23702                    .expect("an abandoned question falls back");
23703                let n = store
23704                    .list()
23705                    .into_iter()
23706                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
23707                    .count();
23708                assert_eq!(n, 1, "asked once per rejected text");
23709                again
23710            };
23711            assert!(crate::github_text::check(&message.title, &message.body).is_empty());
23712            assert!(!message.body.contains("secret"));
23713            assert!(!message.body.contains("prefix"));
23714            assert!(!message.title.contains("secret"));
23715            assert_eq!(
23716                message.body.contains("Add retries for failed requests."),
23717                accepted
23718            );
23719            assert_eq!(
23720                runner.state.seats["github-text-rewrite"].turns, 1,
23721                "only one rewrite invocation"
23722            );
23723            assert!(runner.state.events.iter().any(|e| e.node == "github-text"));
23724            if accepted {
23725                assert!(runner.state.github_text.is_none());
23726                assert!(!runner.state.parked);
23727                assert!(!message.body.contains(crate::github_text::NEUTRAL_BODY));
23728                assert!(message.body.contains("## Final verification"));
23729                assert!(message.body.contains("Evidence: final diff"));
23730                assert!(
23731                    message
23732                        .body
23733                        .contains(&format!("magi:run/{}", runner.state.id))
23734                );
23735            }
23736            if !accepted {
23737                assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
23738                assert!(
23739                    message
23740                        .body
23741                        .contains(&format!("magi:run/{}", runner.state.id))
23742                );
23743            }
23744        }
23745    }
23746
23747    fn scripted(id: &str, reply: &str) -> AgentSpec {
23748        let mut a = spec(id);
23749        a.command = vec![
23750            "sh".into(),
23751            "-c".into(),
23752            "printf '%s' \"$REWRITE_REPLY\"".into(),
23753        ];
23754        a.env.insert("REWRITE_REPLY".into(), reply.into());
23755        a
23756    }
23757
23758    const JA_SUMMARY: &str = "TITLE: fix: retries\n日本語の説明を書きます。";
23759    const EN_REWRITE: &str = "TITLE: fix: retries\nAdd retries in `src/net.rs` for 3 failed requests.\n\n<details>kept</details>";
23760
23761    /// Gate tests inject generated public output, not internal reports.
23762    fn seed_public_summary(runner: &mut Runner) {
23763        let repo = &runner.state.repo;
23764        let g = |args: &[&str]| {
23765            let out = std::process::Command::new("git")
23766                .args(args)
23767                .current_dir(repo)
23768                .quiet()
23769                .output()
23770                .unwrap();
23771            assert!(out.status.success(), "git {args:?}");
23772            String::from_utf8_lossy(&out.stdout).trim().to_owned()
23773        };
23774        g(&["init", "-q", "-b", "main"]);
23775        g(&[
23776            "-c",
23777            "user.name=Test",
23778            "-c",
23779            "user.email=test@example.invalid",
23780            "commit",
23781            "-q",
23782            "--allow-empty",
23783            "-m",
23784            "feat: fixture",
23785        ]);
23786        let head = g(&["rev-parse", "HEAD"]);
23787        g(&["update-ref", "refs/remotes/origin/main", &head]);
23788        let evidence = crate::pr_outcome::summary_evidence(
23789            &runner.state,
23790            crate::pr_outcome::FinalHead::At(&head),
23791        );
23792        let generated = &runner.state.candidates[0].summary;
23793        runner.state.change_summary = Some(crate::run::ChangeSummary {
23794            base: head.clone(),
23795            head,
23796            evidence: crate::pr_outcome::summary_fingerprint(&runner.state, &evidence),
23797            title: summary_title(generated).unwrap(),
23798            body: summary_without_title(generated),
23799        });
23800    }
23801
23802    fn rewrite_runner(dir: &Path, review_only: bool, agents: Vec<AgentSpec>) -> Runner {
23803        let mut runner = runner_at(RunStatus::Gating);
23804        runner.state = state_with_summary("add retries", JA_SUMMARY);
23805        if review_only {
23806            runner.state.candidates[0].agent = EXISTING_BRANCH.to_owned();
23807        }
23808        runner.state.repo = dir.to_owned();
23809        runner.state.candidates[0].worktree = dir.to_owned();
23810        runner.state.config.agents = agents;
23811        seed_public_summary(&mut runner);
23812        runner
23813    }
23814
23815    fn gate_questions(runner: &Runner) -> usize {
23816        ask::Questions::open()
23817            .list()
23818            .into_iter()
23819            .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
23820            .count()
23821    }
23822
23823    #[tokio::test]
23824    async fn review_only_description_is_rewritten_by_the_language_judge_role() {
23825        crate::run::pin_test_home();
23826        let dir = tempfile::tempdir().unwrap();
23827        let mut runner = rewrite_runner(
23828            dir.path(),
23829            true,
23830            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
23831        );
23832        runner.state.config.roles.language_judge =
23833            Some(crate::config::AgentChoice::Chain(vec!["beta".into()]));
23834        let winner = runner.state.candidates[0].clone();
23835        let msg = runner
23836            .guarded_pr_message(&winner, None, true)
23837            .await
23838            .unwrap()
23839            .expect("an English rewrite posts without asking");
23840        assert!(msg.body.contains("`src/net.rs` for 3 failed requests"));
23841        assert!(msg.body.contains("<details>kept</details>"));
23842        assert!(msg.body.contains(&format!("magi:run/{}", runner.state.id)));
23843        assert_eq!(gate_questions(&runner), 0);
23844        assert!(runner.state.github_text.is_none());
23845        assert!(!runner.state.seats.contains_key("impl-A"));
23846        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
23847    }
23848
23849    #[tokio::test]
23850    async fn rewrite_without_an_implementer_session_uses_the_role_not_the_seat() {
23851        crate::run::pin_test_home();
23852        let dir = tempfile::tempdir().unwrap();
23853        let mut runner = rewrite_runner(
23854            dir.path(),
23855            false,
23856            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
23857        );
23858        runner.state.config.roles.language_judge =
23859            Some(crate::config::AgentChoice::One("beta".into()));
23860        runner.state.seats.insert(
23861            "impl-A".into(),
23862            SeatState::new("impl-A", "alpha", runner.state.seed),
23863        );
23864        let winner = runner.state.candidates[0].clone();
23865        let msg = runner
23866            .guarded_pr_message(&winner, None, true)
23867            .await
23868            .unwrap()
23869            .expect("rewritten");
23870        assert!(msg.body.contains("<details>kept</details>"));
23871        assert_eq!(runner.state.seats["impl-A"].turns, 0);
23872        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
23873        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
23874    }
23875
23876    #[tokio::test]
23877    async fn rewrite_reuses_a_resumable_implementer_session() {
23878        crate::run::pin_test_home();
23879        let dir = tempfile::tempdir().unwrap();
23880        let mut runner = rewrite_runner(
23881            dir.path(),
23882            false,
23883            vec![scripted("alpha", EN_REWRITE), scripted("beta", "nope")],
23884        );
23885        runner.state.config.roles.language_judge =
23886            Some(crate::config::AgentChoice::One("beta".into()));
23887        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
23888        seat.turns = 1;
23889        runner.state.seats.insert("impl-A".into(), seat);
23890        let winner = runner.state.candidates[0].clone();
23891        runner
23892            .guarded_pr_message(&winner, None, true)
23893            .await
23894            .unwrap()
23895            .expect("rewritten");
23896        assert_eq!(runner.state.seats["impl-A"].turns, 2);
23897        assert!(!runner.state.seats.contains_key("github-text-rewrite"));
23898    }
23899
23900    #[tokio::test]
23901    async fn a_failing_resumed_implementer_falls_back_to_the_language_judge_role() {
23902        // Runs 7861 / 344a: the winning implementer (agy) had a resumable
23903        // session, was out of quota, and nothing else was asked.
23904        crate::run::pin_test_home();
23905        let dir = tempfile::tempdir().unwrap();
23906        let mut exhausted = spec("alpha");
23907        exhausted.command = vec!["false".into()];
23908        let mut runner = rewrite_runner(
23909            dir.path(),
23910            false,
23911            vec![exhausted, scripted("beta", EN_REWRITE)],
23912        );
23913        // The implementer's own agent is in the role too: it is not asked twice.
23914        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
23915            "alpha".into(),
23916            "beta".into(),
23917        ]));
23918        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
23919        seat.turns = 1;
23920        runner.state.seats.insert("impl-A".into(), seat);
23921        let winner = runner.state.candidates[0].clone();
23922        let msg = runner
23923            .guarded_pr_message(&winner, None, true)
23924            .await
23925            .unwrap()
23926            .expect("the role rewrites after the implementer fails");
23927        assert!(msg.body.contains("`src/net.rs`"));
23928        assert_eq!(
23929            runner.state.seats["impl-A"].turns, 2,
23930            "the implementer was tried once"
23931        );
23932        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
23933        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
23934    }
23935
23936    #[tokio::test]
23937    async fn rewrite_chain_advances_past_a_failing_or_unparsable_agent() {
23938        crate::run::pin_test_home();
23939        let dir = tempfile::tempdir().unwrap();
23940        let mut broken = spec("bad");
23941        broken.command = vec!["false".into()];
23942        let mut runner = rewrite_runner(
23943            dir.path(),
23944            true,
23945            vec![
23946                broken,
23947                scripted("noformat", "Add retries."),
23948                scripted("good", EN_REWRITE),
23949            ],
23950        );
23951        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
23952            "bad".into(),
23953            "noformat".into(),
23954            "good".into(),
23955        ]));
23956        let winner = runner.state.candidates[0].clone();
23957        let msg = runner
23958            .guarded_pr_message(&winner, None, true)
23959            .await
23960            .unwrap()
23961            .expect("the third agent rewrites");
23962        assert!(msg.body.contains("`src/net.rs`"));
23963        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "good");
23964        assert!(runner.state.handovers.is_empty(), "no handover is recorded");
23965    }
23966
23967    #[tokio::test]
23968    async fn unsuccessful_review_only_rewrites_ask_the_owner_and_never_post_the_original() {
23969        crate::run::pin_test_home();
23970        // (agents, role): still Japanese; no TITLE; nothing resolvable.
23971        for (agents, role, saved) in [
23972            (
23973                vec![scripted("beta", "TITLE: fix: retries\n日本語の説明です。")],
23974                Some("beta"),
23975                true,
23976            ),
23977            (vec![scripted("beta", "Add retries.")], Some("beta"), false),
23978            (Vec::new(), None, false),
23979        ] {
23980            let dir = tempfile::tempdir().unwrap();
23981            let mut runner = rewrite_runner(dir.path(), true, agents);
23982            runner.state.config.roles.language_judge =
23983                role.map(|r| crate::config::AgentChoice::One(r.into()));
23984            let winner = runner.state.candidates[0].clone();
23985            let first = runner
23986                .guarded_pr_message(&winner, None, true)
23987                .await
23988                .unwrap();
23989            assert!(first.is_none(), "withheld text parks the run");
23990            assert!(runner.state.parked);
23991            assert_eq!(gate_questions(&runner), 1);
23992            let g = runner.state.github_text.as_ref().unwrap();
23993            assert_eq!(g.rewrite.is_some(), saved);
23994            assert!(g.choice.is_none() && !g.resolved, "nothing posts unasked");
23995        }
23996    }
23997
23998    #[tokio::test]
23999    async fn github_text_rejected_rewrite_survives_retry_and_posts_verbatim() {
24000        crate::run::pin_test_home();
24001        let dir = tempfile::tempdir().unwrap();
24002        let mut runner = runner_at(RunStatus::Gating);
24003        runner.state =
24004            state_with_summary("add retries", "TITLE: 日本語のタイトル\n日本語の説明です。");
24005        runner.state.repo = dir.path().to_owned();
24006        runner.state.candidates[0].worktree = dir.path().to_owned();
24007        let mut author = spec("alpha");
24008        author.command = vec![
24009            "sh".into(),
24010            "-c".into(),
24011            "printf '%s' \"$REWRITE_REPLY\"".into(),
24012        ];
24013        author.env.insert(
24014            "REWRITE_REPLY".into(),
24015            format!(
24016                "TITLE: fix: rewritten title\n{}\n日本語の説明です。",
24017                "English sentence. ".repeat(600)
24018            ),
24019        );
24020        runner.state.config.agents = vec![author];
24021        seed_public_summary(&mut runner);
24022        let winner = runner.state.candidates[0].clone();
24023        assert!(
24024            runner
24025                .guarded_pr_message(&winner, None, true)
24026                .await
24027                .unwrap()
24028                .is_none()
24029        );
24030        let record = runner.state.github_text.clone().unwrap();
24031        let rewrite = record.rewrite.clone().unwrap();
24032        assert_eq!(rewrite.failed, ["body-language"]);
24033        assert!(
24034            rewrite
24035                .body
24036                .ends_with(&format!("magi:run/{}", runner.state.id))
24037        );
24038        let store = ask::Questions::open();
24039        let q = store.get(record.question.as_ref().unwrap()).unwrap();
24040        assert!(
24041            q.choices
24042                .contains(&crate::github_text::USE_REWRITE.to_owned())
24043        );
24044        for label in [
24045            "ORIGINAL",
24046            "FALLBACK",
24047            "REWRITE",
24048            "Rules still failed: body-language",
24049            "truncated",
24050        ] {
24051            assert!(q.detail.contains(label), "{label}");
24052        }
24053        let artifact = std::fs::read_to_string(crate::run::artifact_path(
24054            &runner.state,
24055            &crate::github_text::artifact_name(&record.fingerprint),
24056        ))
24057        .unwrap();
24058        assert!(artifact.contains(&rewrite.title) && artifact.contains(&rewrite.body));
24059        // Restart from serialized state, then retry after a bad owner title.
24060        runner.state =
24061            serde_json::from_str(&serde_json::to_string(&runner.state).unwrap()).unwrap();
24062        store
24063            .update(&q.id, |q| {
24064                q.say("まだ日本語")?;
24065                q.answer(ask::Answer::Choice(crate::github_text::USE_MY_TEXT.into()))
24066            })
24067            .unwrap();
24068        assert!(
24069            runner
24070                .guarded_pr_message(&winner, None, true)
24071                .await
24072                .unwrap()
24073                .is_none()
24074        );
24075        let retry = runner.state.github_text.as_ref().unwrap();
24076        assert_eq!(retry.rewrite.as_ref(), Some(&rewrite));
24077        let q = store.get(retry.question.as_ref().unwrap()).unwrap();
24078        assert!(q.detail.contains("REWRITE") && q.detail.contains(&rewrite.title));
24079        assert!(
24080            q.posting_comparison
24081                .as_ref()
24082                .unwrap()
24083                .matches_detail(&q.detail)
24084        );
24085        store
24086            .update(&q.id, |q| {
24087                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
24088            })
24089            .unwrap();
24090        let message = runner
24091            .guarded_pr_message(&winner, None, true)
24092            .await
24093            .unwrap()
24094            .unwrap();
24095        assert_eq!(message.title, rewrite.title);
24096        assert_eq!(message.body, rewrite.body);
24097        assert_eq!(
24098            runner.state.github_text.as_ref().unwrap().choice,
24099            Some(GithubTextChoice::Rewrite)
24100        );
24101        let again = runner
24102            .guarded_pr_message(&winner, None, true)
24103            .await
24104            .unwrap()
24105            .unwrap();
24106        assert_eq!(again.title, message.title);
24107        assert_eq!(again.body, message.body);
24108        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24109        assert!(
24110            !runner
24111                .state
24112                .events
24113                .iter()
24114                .any(|e| e.message.contains(&rewrite.title)
24115                    || e.message.contains("English sentence."))
24116        );
24117    }
24118
24119    #[tokio::test]
24120    async fn historical_posting_reply_never_expires_into_fallback() {
24121        crate::run::pin_test_home();
24122        let dir = tempfile::tempdir().unwrap();
24123        let mut runner = runner_at(RunStatus::Gating);
24124        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
24125        runner.state.repo = dir.path().to_owned();
24126        runner.state.candidates[0].worktree = dir.path().to_owned();
24127        seed_public_summary(&mut runner);
24128        let winner = runner.state.candidates[0].clone();
24129        assert!(
24130            runner
24131                .guarded_pr_message(&winner, None, true)
24132                .await
24133                .unwrap()
24134                .is_none()
24135        );
24136        let id = runner
24137            .state
24138            .github_text
24139            .as_ref()
24140            .unwrap()
24141            .question
24142            .clone()
24143            .unwrap();
24144        let store = ask::Questions::open();
24145        let mut q = store.get(&id).unwrap();
24146        q.asked_at = "2020-01-01T00:00:00Z".parse().unwrap();
24147        q.answer(ask::Answer::Choice(
24148            crate::github_text::POST_ORIGINAL.into(),
24149        ))
24150        .unwrap();
24151        q.answer_delivered = true;
24152        store.put(&mut q).unwrap();
24153        let source = std::fs::read(store.path_of(&id)).unwrap();
24154        let migration = crate::run::home().join("notifications/task-chat-migration-v1");
24155        std::fs::create_dir_all(&migration).unwrap();
24156        std::fs::write(
24157            migration.join("state.json"),
24158            serde_json::to_vec(&serde_json::json!({
24159                "schema": 1, "sources": [id], "pending": [id]
24160            }))
24161            .unwrap(),
24162        )
24163        .unwrap();
24164        for _ in 0..2 {
24165            assert!(
24166                runner
24167                    .guarded_pr_message(&winner, None, true)
24168                    .await
24169                    .unwrap()
24170                    .is_none()
24171            );
24172            assert!(!runner.state.github_text.as_ref().unwrap().resolved);
24173            assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
24174        }
24175        let home = crate::run::home();
24176        crate::task_chat::sweep(
24177            &crate::queue::Queue::at(home.join("queue")),
24178            &crate::talk::Talks::at(home.join("talks")),
24179            &store,
24180            &home,
24181        );
24182        let outbox = crate::task_inquiry::Outbox::at(&home);
24183        outbox
24184            .update_decision(&id, |d| {
24185                d.accept(&format!("decision: {}", crate::github_text::POST_ORIGINAL))?;
24186                d.source_answer_at = q.answered_at;
24187                Ok(true)
24188            })
24189            .unwrap();
24190        outbox
24191            .settle(
24192                &id,
24193                "owner-chat",
24194                "Owner confirms no publication remains necessary",
24195                None,
24196            )
24197            .unwrap();
24198        assert!(
24199            runner
24200                .guarded_pr_message(&winner, None, true)
24201                .await
24202                .unwrap()
24203                .is_none()
24204        );
24205        assert!(!runner.state.github_text.as_ref().unwrap().resolved);
24206        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
24207    }
24208
24209    #[tokio::test]
24210    async fn github_text_rewrite_choice_without_saved_text_falls_back() {
24211        crate::run::pin_test_home();
24212        let dir = tempfile::tempdir().unwrap();
24213        let mut runner = runner_at(RunStatus::Gating);
24214        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
24215        runner.state.repo = dir.path().to_owned();
24216        runner.state.candidates[0].worktree = dir.path().to_owned();
24217        seed_public_summary(&mut runner);
24218        let winner = runner.state.candidates[0].clone();
24219        assert!(
24220            runner
24221                .guarded_pr_message(&winner, None, true)
24222                .await
24223                .unwrap()
24224                .is_none()
24225        );
24226        let record = runner.state.github_text.as_ref().unwrap();
24227        assert!(record.rewrite.is_none());
24228        // Records written before the additive field deserialize with no rewrite.
24229        let mut old = serde_json::to_value(record).unwrap();
24230        old.as_object_mut().unwrap().remove("rewrite");
24231        let old: crate::run::GithubTextAsk = serde_json::from_value(old).unwrap();
24232        assert!(old.rewrite.is_none());
24233        let id = record.question.clone().unwrap();
24234        ask::Questions::open()
24235            .update(&id, |q| {
24236                q.choices.push(crate::github_text::USE_REWRITE.into());
24237                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
24238            })
24239            .unwrap();
24240        let message = runner
24241            .guarded_pr_message(&winner, None, true)
24242            .await
24243            .unwrap()
24244            .unwrap();
24245        assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
24246        assert_eq!(
24247            runner.state.github_text.as_ref().unwrap().choice,
24248            Some(GithubTextChoice::Fallback)
24249        );
24250    }
24251
24252    #[tokio::test]
24253    async fn withheld_title_takes_the_owner_replacement_and_rechecks_it() {
24254        crate::run::pin_test_home();
24255        let dir = tempfile::tempdir().unwrap();
24256        let mut runner = runner_at(RunStatus::Gating);
24257        runner.state = state_with_summary("add retries", "TITLE: 日本語のタイトル\nAdd retries.");
24258        runner.state.repo = dir.path().to_owned();
24259        runner.state.candidates[0].worktree = dir.path().to_owned();
24260        seed_public_summary(&mut runner);
24261        let winner = runner.state.candidates[0].clone();
24262        assert!(
24263            runner
24264                .guarded_pr_message(&winner, None, true)
24265                .await
24266                .unwrap()
24267                .is_none()
24268        );
24269        let store = ask::Questions::open();
24270        let find = |run: &str| {
24271            store
24272                .list()
24273                .into_iter()
24274                .find(|q| q.run == run && q.node == crate::github_text::ASK_NODE && q.status.open())
24275                .unwrap()
24276        };
24277        let run = runner.state.id.clone();
24278        let q = find(&run);
24279        let fp = runner
24280            .state
24281            .github_text
24282            .as_ref()
24283            .unwrap()
24284            .fingerprint
24285            .clone();
24286        let name = crate::github_text::artifact_name(&fp);
24287        let path = crate::run::artifact_path(&runner.state, &name);
24288        assert!(q.detail.contains(&path.display().to_string()));
24289        assert!(q.detail.contains("title-language: title"));
24290        let saved = std::fs::read_to_string(&path).expect("artifact written");
24291        assert!(saved.contains("日本語のタイトル"));
24292        assert!(q.cwd.is_none());
24293        assert_eq!(q.choices, ["use fallback", "post original", "use my text"]);
24294        // A bad replacement is refused and asked about once more.
24295        let say = |id: &str, text: &str, choice: &str| {
24296            store
24297                .update(id, |q| {
24298                    q.thread.push(ask::Turn {
24299                        who: ask::Who::Operator,
24300                        body: text.to_owned(),
24301                        at: jiff::Timestamp::now(),
24302                        note: None,
24303                    });
24304                    q.answer(ask::Answer::Choice(choice.to_owned()))
24305                })
24306                .unwrap();
24307        };
24308        say(&q.id, "まだ日本語", "use my text");
24309        assert!(
24310            runner
24311                .guarded_pr_message(&winner, None, true)
24312                .await
24313                .unwrap()
24314                .is_none()
24315        );
24316        let second = find(&run);
24317        assert_ne!(second.id, q.id);
24318        assert!(second.detail.contains("did not pass"));
24319        // The retry still compares the original text; the rejected
24320        // replacement is named by category only.
24321        assert!(second.detail.contains("日本語のタイトル"));
24322        assert!(!second.detail.contains("まだ日本語"));
24323        assert!(second.detail.contains(&path.display().to_string()));
24324        say(&second.id, "fix: retry failed requests", "use my text");
24325        let message = runner
24326            .guarded_pr_message(&winner, None, true)
24327            .await
24328            .unwrap()
24329            .expect("a vetted replacement is posted");
24330        assert_eq!(message.title, "fix: retry failed requests");
24331        assert_eq!(
24332            runner
24333                .state
24334                .github_text
24335                .as_ref()
24336                .unwrap()
24337                .chosen_title
24338                .as_deref(),
24339            Some("fix: retry failed requests")
24340        );
24341        assert!(runner.state.github_text.as_ref().unwrap().resolved);
24342        // Resumed again: the saved decision is applied, nothing is re-asked.
24343        let again = runner
24344            .guarded_pr_message(&winner, None, true)
24345            .await
24346            .unwrap()
24347            .unwrap();
24348        assert_eq!(again.title, message.title);
24349        assert_eq!(
24350            store
24351                .list()
24352                .into_iter()
24353                .filter(|q| q.run == run && q.node == crate::github_text::ASK_NODE)
24354                .count(),
24355            2
24356        );
24357    }
24358
24359    #[test]
24360    fn pr_message_magi_text_is_english_and_the_task_is_verbatim() {
24361        // What magi itself writes stays English under any configured language,
24362        // so a future localisation of these headings fails here. (The agents'
24363        // own text is also checked by the posting gate.)
24364        let mut state = state_with_summary(
24365            "add retries",
24366            "TITLE: fix(web): batch reads\n- reads run.json once",
24367        );
24368        state.config.graph.language = "ja".to_owned();
24369        let m = pr_message(&state, 'A');
24370        assert!(crate::github_text::check(&m.title, &m.body).is_empty());
24371        assert!(m.title.is_ascii() && m.body.is_ascii(), "{}", m.body);
24372
24373        // The task is the operator's own text: it goes in untouched, and the
24374        // fallback title (no summary) may be in its language too.
24375        let task = "今回やってほしいこと: results projector を直す";
24376        let mut state = state_with_summary(task, "- no title line");
24377        state.config.graph.language = "ja".to_owned();
24378        let m = pr_message(&state, 'A');
24379        assert_eq!(
24380            m.title,
24381            format!("chore: land candidate A of run {}", state.id)
24382        );
24383        assert!(
24384            m.body.contains(&format!(
24385                "<summary>Original task</summary>\n\n{task}\n\n</details>"
24386            )),
24387            "{}",
24388            m.body
24389        );
24390    }
24391
24392    #[test]
24393    fn pr_message_scrubs_home_paths_and_addresses() {
24394        let state = state_with_summary(
24395            "fix it in /Users/someone/src/x",
24396            "TITLE: fix(x): y\n- edited /home/someone/repo/src/a.rs on 10.1.2.3",
24397        );
24398        let m = pr_message(&state, 'A');
24399        for leak in ["/Users/someone", "/home/someone", "10.1.2.3"] {
24400            assert!(!m.body.contains(leak), "{}", m.body);
24401        }
24402        assert!(m.body.contains("~/repo/src/a.rs"), "{}", m.body);
24403    }
24404
24405    #[test]
24406    fn pr_message_survives_a_task_that_closes_details() {
24407        let state = state_with_summary("a </details> b", "TITLE: fix: x");
24408        let m = pr_message(&state, 'A');
24409        assert_eq!(m.body.matches("</details>").count(), 1, "{}", m.body);
24410    }
24411
24412    #[test]
24413    fn manual_squash_subject_cannot_break_out_of_its_quotes() {
24414        let cmd = manual_merge_command(
24415            MergeStyle::Squash,
24416            Path::new("/repo"),
24417            "b",
24418            "fix: \"quoted\" $(x) `y`\n\nbody",
24419        );
24420        assert!(cmd.ends_with("commit -m \"fix: quoted (x) y\""), "{cmd}");
24421    }
24422
24423    #[test]
24424    fn manual_merge_command_matches_the_configured_style() {
24425        let repo = Path::new("/repo");
24426        let message = "Merge magi run 0832 (candidate A)\n\nadd retries";
24427
24428        let merge = manual_merge_command(MergeStyle::Merge, repo, "magi/0832/A", message);
24429        assert_eq!(merge, "git -C /repo merge --no-ff magi/0832/A");
24430
24431        let squash = manual_merge_command(MergeStyle::Squash, repo, "magi/0832/A", message);
24432        assert_eq!(
24433            squash,
24434            "git -C /repo merge --squash magi/0832/A && git -C /repo commit -m \
24435             \"Merge magi run 0832 (candidate A)\""
24436        );
24437
24438        let rebase = manual_merge_command(MergeStyle::Rebase, repo, "magi/0832/A", message);
24439        assert_eq!(rebase, "git -C /repo merge --ff-only magi/0832/A");
24440    }
24441
24442    #[test]
24443    fn a_nudge_gets_a_quarter_of_the_budget() {
24444        // The judge and implement budgets magi ships with.
24445        assert_eq!(retry_budget(secs(1200), true), secs(300));
24446        assert_eq!(retry_budget(secs(3600), true), secs(900));
24447    }
24448
24449    #[test]
24450    fn a_resent_prompt_keeps_the_whole_budget() {
24451        // The seat kept no context, so the retry is the original job again and
24452        // shortening it would only guarantee a second failure.
24453        assert_eq!(retry_budget(secs(1200), false), secs(1200));
24454        assert_eq!(retry_budget(secs(60), false), secs(60));
24455    }
24456
24457    #[test]
24458    fn the_floor_never_exceeds_the_original_budget() {
24459        // A short configured timeout must not be *raised* by the floor: the
24460        // operator asked for a bound, and a retry may not outlast the attempt
24461        // it is retrying.
24462        assert_eq!(retry_budget(secs(60), true), secs(60));
24463        assert_eq!(retry_budget(secs(480), true), secs(120));
24464        assert_eq!(retry_budget(secs(0), true), secs(0));
24465    }
24466
24467    fn evidence(exit_code: Option<i32>) -> agent::CommandEvidence {
24468        agent::CommandEvidence {
24469            id: "item1".to_owned(),
24470            description: "cargo test".to_owned(),
24471            exit_code,
24472            result_summary: String::new(),
24473            source: "codex".to_owned(),
24474        }
24475    }
24476
24477    #[test]
24478    fn a_reply_with_no_commands_at_all_is_not_unconfirmed() {
24479        // No evidence is not the same fact as unconfirmed evidence: a
24480        // backend with no adapter, or a reply that ran no commands at all,
24481        // must not be misread as carrying a dangling job.
24482        assert!(!has_unconfirmed_command(&[]));
24483    }
24484
24485    #[test]
24486    fn a_command_with_a_real_exit_code_is_confirmed_whatever_its_value() {
24487        // Deliberately not a check on the exit code's *value*: a fixer
24488        // legitimately runs something that fails mid-iteration before it
24489        // succeeds, and that must never by itself reopen a valid report.
24490        assert!(!has_unconfirmed_command(&[evidence(Some(0))]));
24491        assert!(!has_unconfirmed_command(&[evidence(Some(1))]));
24492        assert!(!has_unconfirmed_command(&[
24493            evidence(Some(0)),
24494            evidence(Some(101))
24495        ]));
24496    }
24497
24498    #[test]
24499    fn one_command_with_no_readable_exit_code_is_enough_to_flag_the_reply() {
24500        assert!(has_unconfirmed_command(&[
24501            evidence(Some(0)),
24502            evidence(None)
24503        ]));
24504    }
24505
24506    #[test]
24507    fn a_clean_usable_reply_with_the_marker_is_a_verified_claim() {
24508        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
24509        assert_eq!(
24510            verified_noop_claim(true, &[], text).as_deref(),
24511            Some("already fixed by b32cfc4, on main.")
24512        );
24513    }
24514
24515    #[test]
24516    fn an_unusable_reply_never_earns_the_benefit_of_the_doubt() {
24517        // A timeout or a bad exit code reads as the ordinary loss it is,
24518        // whatever the reply's own prose claims.
24519        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
24520        assert!(verified_noop_claim(false, &[], text).is_none());
24521    }
24522
24523    #[test]
24524    fn an_unconfirmed_command_disqualifies_the_claim_even_on_a_usable_reply() {
24525        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
24526        assert!(verified_noop_claim(true, &[evidence(None)], text).is_none());
24527        // A confirmed command alongside the marker is fine.
24528        assert!(verified_noop_claim(true, &[evidence(Some(0))], text).is_some());
24529    }
24530
24531    #[test]
24532    fn an_ordinary_reply_with_no_marker_is_never_a_claim() {
24533        assert!(verified_noop_claim(true, &[], "- did the thing\n- tested it").is_none());
24534    }
24535
24536    /// Sets `runner.state.candidates` to one candidate per `(empty, verified)`
24537    /// pair, in order, labelled A, B, C, ...
24538    fn set_candidates(runner: &mut Runner, shape: &[(bool, Option<&str>)]) {
24539        runner.state.candidates = shape
24540            .iter()
24541            .enumerate()
24542            .map(|(i, &(empty, verified))| Candidate {
24543                index: i,
24544                label: (b'A' + i as u8) as char,
24545                agent: "sonnet".to_owned(),
24546                branch: format!("magi/x/{}", (b'A' + i as u8) as char),
24547                worktree: PathBuf::from(format!("/wt/{i}")),
24548                summary: String::new(),
24549                stat: String::new(),
24550                files: 0,
24551                commits: 0,
24552                empty,
24553                failed: None,
24554                verified_noop: verified.map(str::to_owned),
24555                duration_ms: 0,
24556                folded: false,
24557            })
24558            .collect();
24559    }
24560
24561    #[test]
24562    fn after_implement_reads_all_candidates_verified_as_a_noop_not_a_failure() {
24563        ask_test_home();
24564        let mut runner = runner_at(RunStatus::Implementing);
24565        set_candidates(
24566            &mut runner,
24567            &[
24568                (true, Some("already on main at b32cfc4")),
24569                (true, Some("same fix, see the existing test")),
24570            ],
24571        );
24572
24573        runner
24574            .after_implement()
24575            .expect("a verified no-op is not an error");
24576
24577        assert_eq!(runner.state.status, RunStatus::VerifiedNoop);
24578    }
24579
24580    #[test]
24581    fn after_implement_does_not_accept_one_candidates_claim_next_to_an_ordinary_loss() {
24582        ask_test_home();
24583        let mut runner = runner_at(RunStatus::Implementing);
24584        // Candidate A declares a verified no-op; candidate B simply wrote
24585        // nothing and said nothing about why. One candidate's claim is not
24586        // the whole run's agreement.
24587        set_candidates(
24588            &mut runner,
24589            &[(true, Some("already on main at b32cfc4")), (true, None)],
24590        );
24591
24592        let err = runner
24593            .after_implement()
24594            .expect_err("an unverified empty candidate must still fail the run");
24595
24596        assert!(
24597            err.to_string().contains("no candidate produced a change"),
24598            "{err}"
24599        );
24600        assert_eq!(runner.state.status, RunStatus::Failed);
24601    }
24602
24603    #[test]
24604    fn after_implement_still_fails_an_ordinary_all_empty_run() {
24605        ask_test_home();
24606        let mut runner = runner_at(RunStatus::Implementing);
24607        set_candidates(&mut runner, &[(true, None), (true, None)]);
24608
24609        let err = runner
24610            .after_implement()
24611            .expect_err("no candidate declared anything; this is an ordinary failure");
24612
24613        assert!(
24614            err.to_string().contains("no candidate produced a change"),
24615            "{err}"
24616        );
24617        assert_eq!(runner.state.status, RunStatus::Failed);
24618    }
24619}
24620
24621/// A graft rollback whose restore could not be confirmed (see
24622/// [`Runner::graft`]).
24623#[derive(Debug)]
24624struct GraftRestoreFailed(String);
24625
24626impl std::fmt::Display for GraftRestoreFailed {
24627    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24628        write!(
24629            f,
24630            "could not restore the winner to its pre-graft commit: {}",
24631            self.0
24632        )
24633    }
24634}
24635
24636impl std::error::Error for GraftRestoreFailed {}
24637
24638/// The pre-spawn waits (shared build cache, parallelism slot) are infrastructure,
24639/// not the agent: they never draw on an agent's own timeout, and running out of
24640/// them never reads as an agent failure.
24641#[cfg(test)]
24642mod resource_wait_tests {
24643    use super::*;
24644    use std::collections::BTreeMap;
24645
24646    fn sh(id: &str, script: &str) -> AgentSpec {
24647        AgentSpec {
24648            id: id.to_owned(),
24649            kind: crate::config::AgentKind::Command,
24650            model: None,
24651            command: vec!["sh".to_owned(), "-c".to_owned(), script.to_owned()],
24652            extra_args: Vec::new(),
24653            env: BTreeMap::new(),
24654            prompt_delivery: None,
24655            max_turn_secs: None,
24656        }
24657    }
24658
24659    fn job(spec: AgentSpec, dir: &Path, timeout: Duration) -> SeatJob {
24660        SeatJob {
24661            seat: SeatState::new("impl-A", &spec.id, 1),
24662            spec,
24663            cwd: dir.to_path_buf(),
24664            prompt: "do it".to_owned(),
24665            timeout,
24666            allow_write: true,
24667            sessions: false,
24668            artifacts: dir.join("art"),
24669            stem: "impl-A".to_owned(),
24670            handover: None,
24671        }
24672    }
24673
24674    fn state(resource_wait_secs: u64) -> RunState {
24675        let mut config = Config::default();
24676        config.graph.timeout_resource_wait = resource_wait_secs;
24677        RunState::new(
24678            PathBuf::from("/repo"),
24679            "main".to_owned(),
24680            "abc1234".to_owned(),
24681            "task".to_owned(),
24682            config,
24683        )
24684    }
24685
24686    fn hold(cache: &Path) -> crate::cache::Guard {
24687        let owner = crate::cache::Owner::here("other-run", "e2e", "e2e", cache, "deadbeef");
24688        match crate::cache::try_acquire(&crate::run::home(), cache, &owner).expect("io") {
24689            crate::cache::AcquireOutcome::Acquired(g) => g,
24690            crate::cache::AcquireOutcome::Busy(b) => panic!("lease was not free: {b:?}"),
24691        }
24692    }
24693
24694    async fn run(
24695        jobs: Vec<SeatJob>,
24696        sem: Arc<Semaphore>,
24697        cache: Option<&Path>,
24698        st: &mut RunState,
24699    ) -> Vec<(usize, SeatState, AgentOutcome)> {
24700        let prompts = Prompts::default();
24701        let ctx = WaveCtx {
24702            run: "r",
24703            node: "implement",
24704            prompts: &prompts,
24705            cache,
24706            round: None,
24707            carry_seats: false,
24708            pauses: None,
24709        };
24710        wave(jobs, sem, &ctx, st, 0).await
24711    }
24712
24713    #[tokio::test]
24714    async fn isolated_editing_seat_wait_releases_only_after_its_own_target_is_free() {
24715        crate::run::pin_test_home();
24716        let home = crate::run::home();
24717        let tmp = tempfile::tempdir().unwrap();
24718        let repo = tmp.path().join("repo");
24719        let checkout = tmp.path().join("checkout");
24720        std::fs::create_dir(&repo).unwrap();
24721        git::git(&repo, &["init"]).await.unwrap();
24722        git::git(
24723            &repo,
24724            &[
24725                "-c",
24726                "user.name=Fixture",
24727                "-c",
24728                "user.email=fixture@example.invalid",
24729                "commit",
24730                "--allow-empty",
24731                "-m",
24732                "initial",
24733            ],
24734        )
24735        .await
24736        .unwrap();
24737        git::worktree_add_detached(&repo, &checkout, "HEAD")
24738            .await
24739            .unwrap();
24740        let target = crate::build_target::resolve(&home, &checkout).unwrap();
24741        let target_lease = hold(&target);
24742        let shared = tmp.path().join("unrelated");
24743        let _shared_lease = hold(&shared);
24744        let mut st = state(0);
24745        st.repo = repo.clone();
24746        st.config.verify.build_cache = crate::config::BuildCache::Isolated;
24747        st.config.verify.e2e = vec![format!(
24748            "CARGO_TARGET_DIR='{}' cargo test",
24749            git::path_arg(&shared)
24750        )];
24751        let config = tmp.path().join("config.toml");
24752        std::fs::write(&config, toml::to_string(&st.config).unwrap()).unwrap();
24753        let prompts = Prompts::default();
24754        let run_id = st.id.clone();
24755        let ctx = WaveCtx {
24756            run: &run_id,
24757            node: "implement",
24758            prompts: &prompts,
24759            cache: None,
24760            round: None,
24761            carry_seats: false,
24762            pauses: None,
24763        };
24764        let writer = job(sh("writer", "exit 99"), &checkout, Duration::from_secs(30));
24765        let results = wave(vec![writer], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0).await;
24766        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
24767        assert_eq!(results[0].1.turns, 0);
24768        let saved = RunState::load_under(&run_id, &home).unwrap();
24769        let block = saved.resource_block.unwrap();
24770        assert!(matches!(
24771            block.cause,
24772            crate::run::ResourceBlockCause::IsolatedCacheTimeout { target: ref actual, .. }
24773                if actual == &target
24774        ));
24775        let queue = crate::queue::Queue::at(tmp.path().join("queue"));
24776        let mut task = crate::queue::Task::new(
24777            "build".into(),
24778            "build".into(),
24779            repo,
24780            crate::queue::Source::Human,
24781        );
24782        task.runs.push(run_id);
24783        task.hold_machine(Some(format!(
24784            "{}{}",
24785            crate::cache::RESOURCE_HOLD,
24786            block.description()
24787        )));
24788        queue.put(&mut task).unwrap();
24789        let questions = crate::ask::Questions::at(tmp.path().join("questions"));
24790        let triage =
24791            || crate::triage::run_once(&queue, &questions, Some(&config), Timestamp::now());
24792        let pending = triage();
24793        assert!(pending.resumed.is_empty() && pending.asked.is_empty());
24794        assert_eq!(
24795            queue.get(&task.id).unwrap().status,
24796            crate::queue::TaskStatus::Held
24797        );
24798        drop(target_lease);
24799        assert_eq!(triage().resumed, vec![task.id.clone()]);
24800        assert_eq!(
24801            queue.get(&task.id).unwrap().status,
24802            crate::queue::TaskStatus::Queued
24803        );
24804        assert!(crate::cache::in_use(&home, &shared));
24805    }
24806
24807    #[tokio::test]
24808    async fn verification_cache_wait_preserves_the_command_budget() {
24809        crate::run::pin_test_home();
24810        let tmp = tempfile::tempdir().unwrap();
24811        let cache = tmp.path().join("target");
24812        let guard = hold(&cache);
24813        let release = tokio::spawn(async move {
24814            tokio::time::sleep(Duration::from_millis(100)).await;
24815            guard.release();
24816        });
24817        let mut st = state(10);
24818        let budget = Duration::from_millis(50);
24819        let wait = repository_wait(&st, None);
24820        let (outcomes, _) = with_cache_lease(
24821            &mut st,
24822            Some(&cache),
24823            "gate",
24824            "gate",
24825            tmp.path(),
24826            "abc1234",
24827            budget,
24828            "test gate",
24829            &wait,
24830            |_, available| async move {
24831                assert_eq!(
24832                    available, budget,
24833                    "contention must not shorten verification"
24834                );
24835                (Vec::new(), false, Vec::new())
24836            },
24837        )
24838        .await
24839        .unwrap();
24840        release.await.unwrap();
24841        assert!(outcomes.is_empty(), "{outcomes:?}");
24842        assert!(
24843            st.events
24844                .iter()
24845                .any(|event| event.message.contains("waiting for"))
24846        );
24847        assert!(st.resource_wait.is_none());
24848        // The verification body no longer owns the lease after returning.
24849        hold(&cache).release();
24850    }
24851
24852    #[tokio::test]
24853    async fn verification_cache_wait_expires_without_starting_commands() {
24854        crate::run::pin_test_home();
24855        let tmp = tempfile::tempdir().unwrap();
24856        let cache = tmp.path().join("target");
24857        let _held = hold(&cache);
24858        let mut st = state(0);
24859        let wait = repository_wait(&st, None);
24860        let (outcomes, _) = with_cache_lease(
24861            &mut st,
24862            Some(&cache),
24863            "gate",
24864            "gate",
24865            tmp.path(),
24866            "abc1234",
24867            Duration::from_secs(60),
24868            "test gate",
24869            &wait,
24870            |_, _| async { panic!("commands must not start without the cache lease") },
24871        )
24872        .await
24873        .unwrap();
24874        assert_eq!(outcomes.len(), 1);
24875        assert!(outcomes[0].resource_blocked);
24876        assert!(st.resource_wait.is_none());
24877        assert!(matches!(
24878            st.resource_block.unwrap().cause,
24879            crate::run::ResourceBlockCause::Timeout { limit_secs: 0, .. }
24880        ));
24881    }
24882
24883    #[tokio::test]
24884    async fn verification_resource_error_does_not_claim_an_elapsed_timeout() {
24885        crate::run::pin_test_home();
24886        let tmp = tempfile::tempdir().unwrap();
24887        std::fs::write(tmp.path().join("Cargo.toml"), "[invalid").unwrap();
24888        let cache = tmp.path().join("cache");
24889        let mut state = state(21600);
24890        let wait = repository_wait(&state, None);
24891        let (outcomes, _) = with_cache_lease(
24892            &mut state,
24893            Some(&cache),
24894            "gate",
24895            "gate",
24896            tmp.path(),
24897            "head",
24898            Duration::from_secs(60),
24899            "gate",
24900            &wait,
24901            |_, _| async { panic!("freshness failure must not start verification") },
24902        )
24903        .await
24904        .unwrap();
24905        assert_eq!(outcomes.len(), 1);
24906        assert!(outcomes[0].resource_blocked);
24907        let block = state.resource_block.unwrap();
24908        assert_eq!(block.cause, crate::run::ResourceBlockCause::Other);
24909        assert!(!block.description().contains("timed out"));
24910    }
24911
24912    #[tokio::test]
24913    async fn cancelled_cache_wait_preserves_the_park_cause_without_starting_an_agent() {
24914        crate::run::pin_test_home();
24915        let tmp = tempfile::tempdir().unwrap();
24916        let cache = tmp.path().join("cache");
24917        let _held = hold(&cache);
24918        let mut state = state(21600);
24919        let pause = Pause::new();
24920        let interrupt = Pause::new();
24921        let cause = ParkCause::Operator;
24922        pause.park_for(cause.clone());
24923        let prompts = Prompts::default();
24924        let ctx = WaveCtx {
24925            run: "test",
24926            node: "fix",
24927            prompts: &prompts,
24928            cache: Some(&cache),
24929            round: None,
24930            carry_seats: false,
24931            pauses: Some((&pause, &interrupt)),
24932        };
24933        let result = wave(
24934            vec![job(
24935                sh("writer", "exit 99"),
24936                tmp.path(),
24937                Duration::from_secs(1),
24938            )],
24939            Arc::new(Semaphore::new(1)),
24940            &ctx,
24941            &mut state,
24942            0,
24943        )
24944        .await;
24945        assert!(matches!(result[0].2, AgentOutcome::ResourceBlocked(_)));
24946        assert_eq!(result[0].1.turns, 0);
24947        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
24948        assert_eq!(
24949            state.resource_block.unwrap().cause,
24950            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
24951        );
24952        assert!(state.active.is_empty());
24953    }
24954
24955    #[tokio::test]
24956    async fn a_cache_wait_longer_than_the_agent_budget_leaves_the_budget_whole() {
24957        crate::run::pin_test_home();
24958        let tmp = tempfile::tempdir().unwrap();
24959        let cache = tmp.path().join("target-a");
24960        let guard = hold(&cache);
24961        // Held for longer than the agent's whole 1s budget.
24962        tokio::spawn(async move {
24963            tokio::time::sleep(Duration::from_millis(1500)).await;
24964            guard.release();
24965        });
24966        let mut st = state(60);
24967        let results = run(
24968            vec![job(
24969                sh("alpha", "echo ok"),
24970                tmp.path(),
24971                Duration::from_secs(1),
24972            )],
24973            Arc::new(Semaphore::new(1)),
24974            Some(&cache),
24975            &mut st,
24976        )
24977        .await;
24978        assert!(
24979            matches!(results[0].2, AgentOutcome::Ok(_)),
24980            "the wait must not be charged to the agent"
24981        );
24982        assert!(st.resource_block.is_none());
24983        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
24984        assert!(st.resource_wait.is_none() && st.active.is_empty());
24985    }
24986
24987    #[tokio::test]
24988    #[cfg(unix)]
24989    async fn repository_wait_in_a_wave_is_a_bounded_cancellable_resource_block() {
24990        use std::os::fd::AsRawFd as _;
24991        crate::run::pin_test_home();
24992        let tmp = tempfile::tempdir().unwrap();
24993        crate::git::git(tmp.path(), &["init"]).await.unwrap();
24994        let common = tmp.path().join(".git");
24995        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
24996        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
24997        assert_eq!(
24998            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
24999            0
25000        );
25001        let mut st = state(1);
25002        st.config.coordination = crate::config::test_coordination();
25003        let mut reader = job(
25004            sh("reader", "echo must-not-run"),
25005            tmp.path(),
25006            Duration::from_secs(30),
25007        );
25008        reader.allow_write = false;
25009        let results = run(
25010            vec![reader.clone()],
25011            Arc::new(Semaphore::new(1)),
25012            None,
25013            &mut st,
25014        )
25015        .await;
25016        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
25017        assert_eq!(results[0].1.turns, 0);
25018        assert!(FailClass::of(&results[0].2).is_none());
25019        assert_eq!(
25020            st.resource_block.as_ref().unwrap().kind,
25021            "repository coordination"
25022        );
25023        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
25024        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
25025        drop(external);
25026        let editor = crate::repo_lock::SeatLease::for_checkout(
25027            tmp.path(),
25028            true,
25029            crate::config::test_coordination().as_ref(),
25030        )
25031        .await
25032        .unwrap();
25033        let pause = Pause::new();
25034        let interrupt = Pause::new();
25035        let prompts = Prompts::default();
25036        let ctx = WaveCtx {
25037            run: "r",
25038            node: "review",
25039            prompts: &prompts,
25040            cache: None,
25041            round: None,
25042            carry_seats: false,
25043            pauses: Some((&pause, &interrupt)),
25044        };
25045        let (results, ()) = tokio::join!(
25046            wave(vec![reader], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0),
25047            async {
25048                tokio::time::sleep(Duration::from_millis(50)).await;
25049                pause.park();
25050            }
25051        );
25052        assert!(
25053            matches!(&results[0].2, AgentOutcome::ResourceBlocked(why) if why.contains("parking"))
25054        );
25055        assert_eq!(results[0].1.turns, 0);
25056        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
25057        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
25058        drop(editor);
25059    }
25060
25061    #[tokio::test]
25062    async fn an_expired_cache_wait_blocks_without_asking_or_rotating_the_agent() {
25063        crate::run::pin_test_home();
25064        let tmp = tempfile::tempdir().unwrap();
25065        let cache = tmp.path().join("target-b");
25066        let _held = hold(&cache);
25067        let mut st = state(1);
25068        let results = run(
25069            vec![job(
25070                sh("alpha", "echo ok"),
25071                tmp.path(),
25072                Duration::from_secs(1),
25073            )],
25074            Arc::new(Semaphore::new(1)),
25075            Some(&cache),
25076            &mut st,
25077        )
25078        .await;
25079        let (_, seat, out) = &results[0];
25080        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
25081        assert!(wave_blocked(&results));
25082        assert_eq!(seat.agent, "alpha", "the chosen agent is kept");
25083        assert_eq!(seat.turns, 0, "nothing was asked");
25084        assert!(
25085            !tmp.path().join("art").join("impl-A.prompt.md").exists(),
25086            "no agent was spawned"
25087        );
25088        assert!(FailClass::of(out).is_none(), "not a failure class");
25089        let block = st.resource_block.as_ref().expect("recorded for the resume");
25090        assert_eq!(block.kind, "shared build cache");
25091        assert!(matches!(
25092            block.cause,
25093            crate::run::ResourceBlockCause::Timeout { limit_secs: 1, .. }
25094        ));
25095        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
25096        assert!(st.active.is_empty());
25097    }
25098
25099    #[tokio::test]
25100    async fn a_semaphore_with_no_permits_ends_as_a_bounded_resource_block() {
25101        crate::run::pin_test_home();
25102        let tmp = tempfile::tempdir().unwrap();
25103        let mut st = state(1);
25104        let results = run(
25105            vec![job(
25106                sh("alpha", "echo ok"),
25107                tmp.path(),
25108                Duration::from_secs(1),
25109            )],
25110            Arc::new(Semaphore::new(0)),
25111            None,
25112            &mut st,
25113        )
25114        .await;
25115        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
25116        assert_eq!(st.resource_block.as_ref().unwrap().kind, "parallel slot");
25117        assert!(!tmp.path().join("art").join("impl-A.prompt.md").exists());
25118    }
25119
25120    #[tokio::test]
25121    async fn an_agent_that_really_hangs_still_times_out_and_hands_over() {
25122        crate::run::pin_test_home();
25123        let tmp = tempfile::tempdir().unwrap();
25124        let mut st = state(60);
25125        let results = run(
25126            vec![job(
25127                sh("alpha", "sleep 30"),
25128                tmp.path(),
25129                Duration::from_secs(1),
25130            )],
25131            Arc::new(Semaphore::new(1)),
25132            None,
25133            &mut st,
25134        )
25135        .await;
25136        let out = &results[0].2;
25137        assert!(matches!(out, AgentOutcome::Failed(e) if e == TIMED_OUT));
25138        let class = FailClass::of(out).expect("a failure");
25139        assert_eq!(class, FailClass::Timeout);
25140        assert!(should_hand_over(None, &class), "existing handover policy");
25141        assert!(st.resource_block.is_none());
25142    }
25143}