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#[doc(hidden)]
603pub struct ExecutionLeaseGuard {
604    _lease: crate::driver::ExecutionLease,
605}
606
607#[doc(hidden)]
608pub fn hold_execution_lease_for_test(home: &Path, run_id: &str) -> Result<ExecutionLeaseGuard> {
609    Ok(ExecutionLeaseGuard {
610        _lease: crate::driver::maintenance(home, run_id)?,
611    })
612}
613
614/// Holds the mutable runner as well as its durable lease: cancellation must
615/// clear both copies of ownership, including state a caller may save later.
616struct DriverExecution<'a> {
617    runner: &'a mut Runner,
618    driver: crate::driver::DriverGuard,
619}
620
621impl Drop for DriverExecution<'_> {
622    fn drop(&mut self) {
623        self.driver.release_local(&mut self.runner.state);
624    }
625}
626
627fn startup_stage(state: &mut RunState, stage: &str) -> Result<()> {
628    if let Some(startup) = &mut state.startup {
629        startup.stage = stage.to_owned();
630    }
631    state.save()
632}
633
634/// Keep a reservation visible as blocked until startup finishes. A killed process
635/// leaves the same explicit incomplete marker; dropping a cancelled future records it.
636struct StartupGuard {
637    id: String,
638    armed: bool,
639}
640
641impl StartupGuard {
642    fn reserve(state: &mut RunState, kind: &str, branch: Option<&str>) -> Result<Self> {
643        state.startup = Some(crate::run::Startup {
644            kind: kind.to_owned(),
645            branch: branch.map(str::to_owned),
646            stage: "reserved".to_owned(),
647            complete: false,
648            failure: None,
649        });
650        state.status = RunStatus::Blocked;
651        state.reserve()?;
652        Ok(Self {
653            id: state.id.clone(),
654            armed: true,
655        })
656    }
657
658    fn stage(&self, state: &mut RunState, stage: &str) -> Result<()> {
659        startup_stage(state, stage)
660    }
661
662    fn finish(mut self, state: &mut RunState, result: Result<()>) -> Result<()> {
663        let result = result.and_then(|()| {
664            state.startup.as_mut().expect("reserved startup").complete = true;
665            state.save()
666        });
667        self.armed = false;
668        match result {
669            Ok(()) => Ok(()),
670            Err(error) => {
671                let startup = state.startup.as_mut().expect("reserved startup");
672                startup.complete = false;
673                startup.failure = Some(format!("{error:#}"));
674                let context = crate::run::StartupFailure {
675                    run: state.id.clone(),
676                    stage: startup.stage.clone(),
677                };
678                // Repository assets may remain. Never infer that a failed startup
679                // is safe to resume or that an earlier owner has been restored.
680                state.status = RunStatus::Failed;
681                state.driver_exited = true;
682                state.event(
683                    "startup-failed",
684                    format!("{context}: {error:#}; retained assets require inspection"),
685                );
686                if let Err(save) = state.save() {
687                    tracing::warn!(
688                        "run {}: could not save terminal startup record: {save:#}; reservation requires reconciliation",
689                        state.id
690                    );
691                }
692                Err(error.context(context))
693            }
694        }
695    }
696}
697
698impl Drop for StartupGuard {
699    fn drop(&mut self) {
700        if self.armed
701            && let Ok(mut state) = RunState::load(&self.id)
702        {
703            state.status = RunStatus::Blocked;
704            state.driver_exited = true;
705            if let Some(startup) = &mut state.startup {
706                startup.failure = Some("startup interrupted; reconciliation required".to_owned());
707            }
708            state.event(
709                "startup-interrupted",
710                "startup did not finish; inspect retained assets before recovery",
711            );
712            if let Err(error) = state.save() {
713                tracing::error!(
714                    "could not record interrupted startup {}: {error:#}",
715                    self.id
716                );
717            }
718        }
719    }
720}
721
722impl Runner {
723    /// A queue-side failure after construction must not strand an unexecuted run.
724    pub(crate) fn fail_startup(&mut self, stage: &str, error: anyhow::Error) -> anyhow::Error {
725        if !self.state.passes.is_empty() || self.state.driver_claimed != Some(false) {
726            return error;
727        }
728        if let Some(startup) = &mut self.state.startup {
729            startup.stage = stage.to_owned();
730        } else {
731            // A resumed run already has execution history: do not rewrite it.
732            return error;
733        }
734        StartupGuard {
735            id: self.state.id.clone(),
736            armed: true,
737        }
738        .finish(&mut self.state, Err(error))
739        .expect_err("startup failed")
740    }
741
742    /// Start a fresh run against `repo`.
743    pub async fn start(
744        repo: &Path,
745        instruction: String,
746        config: Config,
747        origin: Origin,
748    ) -> Result<Self> {
749        Self::start_naming(repo, instruction, "", config, origin).await
750    }
751
752    /// [`Runner::start`] for a queued task. Titles and instructions never
753    /// select implementation sources. The title argument is retained for callers.
754    pub async fn start_naming(
755        repo: &Path,
756        instruction: String,
757        _also_scan: &str,
758        config: Config,
759        origin: Origin,
760    ) -> Result<Self> {
761        let repo = git::toplevel(repo).await?;
762        let missing = agent::missing_programs(&config.agents);
763        if !missing.is_empty() {
764            bail!(
765                "these agent programs are not on PATH: {}. Fix the roster in \
766                 magi.toml or install them.",
767                missing.join(", ")
768            );
769        }
770        let base_branch =
771            git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
772                .await?;
773        let fetched_base = resolve_base(
774            &repo,
775            &base_branch,
776            &config.merge.remote,
777            config.coordination.as_ref(),
778        )
779        .await?;
780        let base_commit = fetched_base.commit.clone();
781        let roles = config.resolve_roles()?;
782        let max_parallel = config.graph.max_parallel.max(1);
783        let mut state = RunState::new(repo, base_branch, base_commit, instruction, config);
784        // Capture task identity and repository assignment before the first
785        // save, so publication scope survives crashes and later task moves.
786        state.fetched_base = Some(fetched_base);
787        state.set_origin(origin)?;
788        let startup = StartupGuard::reserve(&mut state, "implementation", None)?;
789        state.status = RunStatus::Prep;
790        state.event("start", format!("run {} created", state.id));
791        startup.finish(&mut state, Ok(()))?;
792        Ok(Self {
793            state,
794            roles,
795            sem: Arc::new(Semaphore::new(max_parallel)),
796            pause: Pause::new(),
797            interrupt: Pause::new(),
798        })
799    }
800
801    /// Open a review-only run against work that already exists on `branch`.
802    ///
803    /// The expensive half of the graph is the implement wave — measured at
804    /// 111 and 134 internal tool-loop turns on this repository, against a
805    /// handful for a judge or a reviewer. The cheap half is worth running on
806    /// hand-written work too, and there was no way to reach it.
807    ///
808    /// No new state and no schema change are needed: a run with **one** viable
809    /// candidate and a tally already decided degrades `execute` to exactly
810    /// review → gate → merge, because `judge` skips a single-candidate field,
811    /// `deliberate` has fewer than two first choices to reconcile, `vote`
812    /// returns early, `tally` is already present and `fold_losers` has no
813    /// losers. Resuming such a run therefore does the right thing as well.
814    pub async fn review(repo: &Path, branch: &str, config: Config, origin: Origin) -> Result<Self> {
815        Self::review_taking_over(repo, branch, config, None, origin).await
816    }
817
818    /// [`Runner::review`] for a queued task's retry: when an earlier attempt
819    /// at the same task still has `branch` checked out, its worktree is
820    /// released first if that is safe (see [`crate::handover`]), and the
821    /// review refuses with the reason if it is not. `None` is a hand-run
822    /// review: it has no earlier attempts, so only a worktree of a dead run
823    /// magi recorded itself can be released.
824    pub async fn review_taking_over(
825        repo: &Path,
826        branch: &str,
827        config: Config,
828        takeover: Option<crate::handover::Takeover>,
829        origin: Origin,
830    ) -> Result<Self> {
831        let repo = git::toplevel(repo).await?;
832        let missing = agent::missing_programs(&config.agents);
833        if !missing.is_empty() {
834            bail!(
835                "these agent programs are not on PATH: {}. Fix the roster in \
836                 magi.toml or install them.",
837                missing.join(", ")
838            );
839        }
840        let base_branch =
841            git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
842                .await?;
843        if base_branch == branch {
844            bail!("`{branch}` is the base branch; there is nothing to review against");
845        }
846        let fetched_base = resolve_base(
847            &repo,
848            &base_branch,
849            &config.merge.remote,
850            config.coordination.as_ref(),
851        )
852        .await?;
853        let base_commit = fetched_base.commit.clone();
854
855        let roles = config.resolve_roles()?;
856        let max_parallel = config.graph.max_parallel.max(1);
857        let mut state = RunState::new(
858            repo.clone(),
859            base_branch,
860            base_commit.clone(),
861            format!("Review the work already on branch `{branch}`."),
862            config,
863        );
864        state.fetched_base = Some(fetched_base);
865        state.set_origin(origin)?;
866        state.task_instruction = takeover.as_ref().and_then(|t| t.task_instruction.clone());
867        let startup = StartupGuard::reserve(&mut state, "review", Some(branch))?;
868        let opened = async {
869            startup.stage(&mut state, "handover")?;
870
871            // Released before anything else touches the branch: a stale local
872            // branch is moved with `git branch -f`, which git refuses while an
873            // earlier attempt's worktree still has it checked out. Everything
874            // after this point that can fail puts the old run back.
875            // A hand-run review has no task, hence no earlier attempts, but a
876            // worktree of a dead run magi made may still be released.
877            let takeover = takeover.unwrap_or_else(|| crate::handover::Takeover {
878                earlier: Vec::new(),
879                home: crate::run::home(),
880                choice: None,
881                task_instruction: None,
882            });
883            let wait = repository_wait(&state, None);
884            let coordination_config = state.config.coordination.clone();
885            let coordination =
886                crate::repo_lock::SeatLease::operation_with(&repo, coordination_config.as_ref(), &wait)
887                    .await?;
888            let released = crate::handover::release(&repo, branch, &state.id, &takeover).await?;
889            if let Some(released) = &released {
890                state.event(
891                    "release",
892                    format!(
893                        "took `{branch}` over from run {}: its worktree was released: {}",
894                        crate::run::short_of(&released.old_id),
895                        released.audit
896                    ),
897                );
898            }
899            let opened = async {
900                startup.stage(&mut state, "review-preflight")?;
901                // The owner's answer to an earlier divergence question is applied
902                // here: after the release (git will not move a checked-out branch)
903                // and before the sync that would otherwise ask again.
904                state.foreign_checkout = crate::handover::preflight_review(
905                    &repo,
906                    branch,
907                    &takeover.home,
908                    &state.config.merge.remote,
909                )
910                .await?;
911                if state.foreign_checkout.is_some() && takeover.choice.is_some() {
912                    bail!("cannot reconcile a foreign checkout automatically; resolve its branch first");
913                }
914                if let Some(choice) = takeover.choice.as_ref()
915                    && let Err(e) =
916                        crate::reconcile::apply_choice(&repo, &state.config.merge.remote, branch, choice)
917                            .await
918                {
919                    return Err(e.context("applying the owner's answer about the diverged branch"));
920                }
921                // An earlier attempt of this task that published the task head, and
922                // whose work is the branch under review, hands that head over: the
923                // review run updates the same pull request. Without one (a legacy
924                // `magi/<run>/<label>` PR, a hand-named branch) the branch keeps its
925                // own head and its own open pull request is adopted as before.
926                for id in takeover.earlier.iter().rev() {
927                    if let Ok(old) = RunState::load_under(id, &takeover.home)
928                        && let Some(head) = old.pr_head.clone()
929                        && (head == branch || old.winner().is_some_and(|w| w.branch == branch))
930                    {
931                        state.pr_head = Some(head);
932                        break;
933                    }
934                }
935                drop(coordination);
936                startup.stage(&mut state, "open-review")?;
937                Self::open_review(&repo, branch, &mut state, base_commit, &takeover).await
938            }
939            .await;
940            if opened.is_err()
941                && let Some(released) = &released
942            {
943                // Restoration is ownership checked and best effort. Keep the original
944                // startup cause even if reacquiring coordination is no longer possible.
945                match crate::repo_lock::SeatLease::operation_with(
946                    &repo,
947                    coordination_config.as_ref(),
948                    &wait,
949                )
950                .await
951                {
952                    Ok(_coordination) => {
953                        released.restore(&repo, branch).await;
954                        let outcome = RunState::load_under(&released.old_id, &takeover.home)
955                            .map(|old| {
956                                format!(
957                                    "predecessor released_to={:?}; candidate path exists={}",
958                                    old.released_to,
959                                    old.candidates.iter().any(|c| {
960                                        c.branch == branch && c.worktree.exists()
961                                    }),
962                                )
963                            })
964                            .unwrap_or_else(|error| format!("predecessor could not be inspected: {error:#}"));
965                        state.event("startup-restore", format!("ownership-checked restoration attempted: {outcome}; retained successor assets require inspection"));
966                    }
967                    Err(error) => {
968                        tracing::warn!(
969                            "run {}: could not take the repository lease to restore `{branch}`: {error:#}",
970                            state.id
971                        );
972                        state.event(
973                            "startup-restore",
974                            format!("restoration not attempted: {error:#}"),
975                        );
976                    }
977                }
978            }
979            opened
980        }
981        .await;
982        startup.finish(&mut state, opened)?;
983        Ok(Self {
984            state,
985            roles,
986            sem: Arc::new(Semaphore::new(max_parallel)),
987            pause: Pause::new(),
988            interrupt: Pause::new(),
989        })
990    }
991
992    /// Recover exactly the operator-selected public implementation, without touching old sources.
993    pub async fn recover_pr(
994        repo: &Path,
995        task: &str,
996        selection: crate::pr_recovery::Selection,
997        mut config: Config,
998    ) -> Result<Self> {
999        selection.configure(&mut config)?;
1000        let assignment = crate::run::task_assignment_for(task)?;
1001        selection.check_task_assignment(task, &selection.instruction, assignment)?;
1002        let base_branch =
1003            git::merge_base_branch(repo, &config.merge.remote, config.merge.base.as_deref())
1004                .await?;
1005        let fetched_base = resolve_base(
1006            repo,
1007            &base_branch,
1008            &config.merge.remote,
1009            config.coordination.as_ref(),
1010        )
1011        .await?;
1012        let base_commit = fetched_base.commit.clone();
1013        selection
1014            .verify(repo, &config.merge.remote, &base_branch, &selection.head)
1015            .await?;
1016        Box::pin(selection.verify_source(repo)).await?;
1017        if let Some(proof) = &selection.source_proof {
1018            anyhow::ensure!(
1019                git::is_ancestor(repo, &proof.new_base, &base_commit).await,
1020                "source rebase base is outside the fetched landing base"
1021            );
1022        }
1023        let roles = config.resolve_roles()?;
1024        let max_parallel = config.graph.max_parallel.max(1);
1025        let mut state = RunState::new(
1026            repo.to_path_buf(),
1027            base_branch,
1028            base_commit.clone(),
1029            selection.instruction.clone(),
1030            config,
1031        );
1032        state.fetched_base = Some(fetched_base);
1033        state.set_origin(crate::run::Origin::queue(task))?;
1034        state.pr_head = Some(selection.branch.clone());
1035        state.pr_recovery = Some(selection.clone());
1036        Self::open_selected(repo, state, roles, max_parallel, base_commit, selection).await
1037    }
1038
1039    async fn open_selected(
1040        repo: &Path,
1041        mut state: RunState,
1042        roles: ResolvedRoles,
1043        max_parallel: usize,
1044        base_commit: String,
1045        selection: crate::pr_recovery::Selection,
1046    ) -> Result<Self> {
1047        let startup = StartupGuard::reserve(&mut state, "pr-recovery", Some(&selection.branch))?;
1048        let opened = async {
1049            startup.stage(&mut state, "predecessors")?;
1050            crate::pr_head::check_predecessors(&state, &selection.branch).await?;
1051            startup.stage(&mut state, "open-selected")?;
1052            let branch = state.branch_for('A');
1053            let wait = repository_wait(&state, None);
1054            let prepared = async {
1055                let coordination = coordinate_operation(&mut state, repo, &wait).await?;
1056                git::git(repo, &["branch", &branch, selection.source()]).await?;
1057                drop(coordination);
1058                anyhow::Ok(())
1059            }
1060            .await;
1061            prepared?;
1062            state.event(
1063                "recovery",
1064                format!(
1065                    "selected implementation {} for {} (public lease {})",
1066                    selection.source(),
1067                    selection.url,
1068                    selection.head
1069                ),
1070            );
1071            let takeover = crate::handover::Takeover {
1072                earlier: Vec::new(),
1073                home: crate::run::home(),
1074                choice: None,
1075                task_instruction: Some(selection.instruction.clone()),
1076            };
1077            state.save()?;
1078            Self::open_review(repo, &branch, &mut state, base_commit, &takeover).await
1079        }
1080        .await;
1081        startup.finish(&mut state, opened)?;
1082        Ok(Self {
1083            state,
1084            roles,
1085            sem: Arc::new(Semaphore::new(max_parallel)),
1086            pause: Pause::new(),
1087            interrupt: Pause::new(),
1088        })
1089    }
1090
1091    /// What the newest earlier attempt that reviewed `branch` leaves for this
1092    /// run (see [`crate::recovery`]). `None` for a hand-run review, which has
1093    /// no earlier attempts. Reads the earlier record only: ownership of its
1094    /// worktree and branch is [`crate::handover`]'s business.
1095    async fn inherit(
1096        repo: &Path,
1097        branch: &str,
1098        base_commit: &str,
1099        takeover: &crate::handover::Takeover,
1100    ) -> Option<crate::recovery::RecoveryRecord> {
1101        use crate::recovery::{Relation, assess};
1102        let newest = takeover.earlier.last()?;
1103        let mut chosen = None;
1104        for id in takeover.earlier.iter().rev() {
1105            if let Ok(old) = RunState::load_under(id, &takeover.home)
1106                && !old.reviews.is_empty()
1107                && (old.winner().is_some_and(|w| w.branch == branch)
1108                    || old.pr_head.as_deref() == Some(branch))
1109            {
1110                chosen = Some(old);
1111                break;
1112            }
1113        }
1114        let tip = git::rev_parse(repo, &format!("refs/heads/{branch}"))
1115            .await
1116            .unwrap_or_default();
1117        let relation = match chosen.as_ref().and_then(|o| o.reviews.last()) {
1118            Some(last) if last.head == tip => Relation::Same,
1119            Some(last) if git::is_ancestor(repo, &last.head, &tip).await => Relation::Descendant,
1120            _ => Relation::Diverged,
1121        };
1122        let from = chosen.as_ref().map_or(newest.as_str(), |o| o.id.as_str());
1123        Some(assess(from, chosen.as_ref(), base_commit, relation))
1124    }
1125
1126    /// The half of [`Runner::review_taking_over`] that can fail after an
1127    /// earlier attempt's worktree was released.
1128    async fn open_review(
1129        repo: &Path,
1130        branch: &str,
1131        state: &mut RunState,
1132        base_commit: String,
1133        takeover: &crate::handover::Takeover,
1134    ) -> Result<()> {
1135        startup_stage(state, "review-sync")?;
1136        let wait = repository_wait(state, None);
1137        let _coordination = coordinate_operation(state, repo, &wait).await?;
1138        if state.foreign_checkout.is_some() {
1139            // Never reconcile or force-move a ref checked out by the operator.
1140            if state.pr_head.is_none() {
1141                state.pr_head = Some(branch.to_owned());
1142            }
1143        } else if state.pr_recovery.is_none() {
1144            sync_review_branch(repo, branch, &state.config.merge.remote, &base_commit).await?;
1145        }
1146        // The commit subjects are the closest thing to a task statement that
1147        // existing work carries, and the reviewers are told as much.
1148        let start = review_base(
1149            repo,
1150            &state.config.merge.remote,
1151            &state.base_branch,
1152            &base_commit,
1153            branch,
1154        )
1155        .await;
1156        let log = git::log_oneline(repo, &start, branch)
1157            .await
1158            .unwrap_or_default();
1159        let log_text = if log.trim().is_empty() {
1160            "(no commit messages)"
1161        } else {
1162            log.trim()
1163        };
1164        let mut instruction = format!(
1165            "Review the work already on branch `{branch}`. There is no task \
1166             statement: what the change claims to do is whatever its commits \
1167             say.\n\n{log_text}"
1168        );
1169        // A retry of a task whose earlier attempt left reviews behind carries
1170        // that attempt's evidence, and the task's own statement with it: the
1171        // completion criteria are the task's, not whatever the commits claim.
1172        if let Some(mut rec) = Self::inherit(repo, branch, &base_commit, takeover).await {
1173            if let Some(task) = takeover
1174                .task_instruction
1175                .as_deref()
1176                .filter(|t| !t.trim().is_empty())
1177                && rec.reviewed_head.is_some()
1178            {
1179                instruction = format!(
1180                    "{}\n\n# Work already on branch `{branch}` (commit subjects)\n\n{log_text}",
1181                    task.trim()
1182                );
1183                rec.criteria_inherited = true;
1184            }
1185            state.event("recovery", rec.summary());
1186            state.recovery = Some(rec);
1187        }
1188        if let Some(selected) = &state.pr_recovery {
1189            instruction = selected.instruction.clone();
1190        }
1191        state.task_instruction = takeover.task_instruction.clone();
1192        state.instruction = instruction;
1193        state.reviewed_commits = Some(
1194            git::subjects(repo, &start, branch)
1195                .await
1196                .unwrap_or_default(),
1197        );
1198
1199        // A takeover must not forget a hold that a previous review observed,
1200        // even if repairs have since removed it from the branch.
1201        for id in &takeover.earlier {
1202            if let Ok(old) = RunState::load_under(id, &takeover.home)
1203                && old.repo == state.repo
1204                && (old.pr_head.as_deref() == Some(branch)
1205                    || old.winner().is_some_and(|w| w.branch == branch))
1206            {
1207                for hold in old.branch_owner_holds {
1208                    if !state.branch_owner_holds.contains(&hold) {
1209                        state.event(
1210                            "approval-policy",
1211                            format!(
1212                                "inherited {}=true from the reviewed branch's {} at {} (run {id})",
1213                                hold.control.key(),
1214                                hold.file,
1215                                hold.head
1216                            ),
1217                        );
1218                        state.branch_owner_holds.push(hold);
1219                    }
1220                }
1221            }
1222        }
1223        // Select the actual review tip before observing owner policy. A foreign
1224        // checkout can lag its remote descendant, and repairs must not erase
1225        // holds introduced only on that selected commit.
1226        let reviewed_head = if let Some(checkout) = &state.foreign_checkout {
1227            let tracking = format!("{}/{branch}", state.config.merge.remote);
1228            // A surviving tracking ref is not evidence that the remote still
1229            // offers this tip. Adopt it only after a successful fetch here.
1230            let fetched = git::fetch(repo, &state.config.merge.remote, branch).await;
1231            let mut head = checkout.synced_head.clone();
1232            if matches!(fetched, Ok(out) if out.ok()) {
1233                let remote = git::rev_parse(repo, &tracking).await?;
1234                if git::is_ancestor(repo, &checkout.synced_head, &remote).await {
1235                    head = remote;
1236                }
1237            }
1238            head
1239        } else {
1240            git::rev_parse(repo, branch).await?
1241        };
1242        state.observe_branch_owner_holds(&reviewed_head).await;
1243
1244        // An attached worktree, so the fixer's commits land on the branch under
1245        // review rather than on a detached head nobody will look at again.
1246        let worktree = state.worktree_root().join("under-review");
1247        if let Some(parent) = worktree.parent() {
1248            tokio::fs::create_dir_all(parent).await.ok();
1249        }
1250        let path = worktree.to_string_lossy().to_string();
1251        let review_branch = if state.foreign_checkout.is_some() {
1252            let shadow = format!("magi/{}/review", state.short());
1253            git::git(repo, &["branch", &shadow, &reviewed_head]).await?;
1254            shadow
1255        } else {
1256            branch.to_owned()
1257        };
1258        startup_stage(state, "review-checkout")?;
1259        git::git(repo, &["worktree", "add", &path, &review_branch])
1260            .await
1261            .with_context(|| {
1262                format!("checking out `{branch}` at {path} (is it checked out elsewhere?)")
1263            })?;
1264
1265        startup_stage(state, "worktree-setup")?;
1266        let setup = match ensure_setup_config(state, repo).await {
1267            Ok(()) => {
1268                worktree_setup::prepare_with(
1269                    &state.config,
1270                    repo,
1271                    &worktree,
1272                    crate::build_target::Coordination::Held(_coordination.as_ref()),
1273                )
1274                .await
1275            }
1276            Err(e) => Err(e),
1277        };
1278        if let Err(e) = setup {
1279            git::worktree_remove_clean(repo, &worktree).await.ok();
1280            return Err(e);
1281        }
1282        let commits = git::commits_ahead(&worktree, &base_commit, "HEAD")
1283            .await
1284            .unwrap_or(0);
1285        if commits == 0 {
1286            git::worktree_remove_clean(repo, &worktree).await.ok();
1287            bail!("`{branch}` has no commits beyond {}", short(&base_commit));
1288        }
1289        let files = git::changed_files(&worktree, &base_commit, "HEAD")
1290            .await
1291            .map(|f| f.len())
1292            .unwrap_or(0);
1293        if files == 0
1294            && let (Ok(head_tree), Ok(base_tree)) = (
1295                git::tree_of(&worktree, "HEAD").await,
1296                git::tree_of(&worktree, &base_commit).await,
1297            )
1298            && head_tree == base_tree
1299        {
1300            let head = git::rev_parse(&worktree, "HEAD").await.unwrap_or_default();
1301            git::worktree_remove_clean(repo, &worktree).await.ok();
1302            bail!(
1303                "`{branch}` at {} has a tree identical to base {}; this usually means \
1304                 the branch ref is stale (check `git rev-parse refs/heads/{branch}` \
1305                 against `{}/{branch}`) rather than an empty change",
1306                short(&head),
1307                short(&base_commit),
1308                state.config.merge.remote
1309            );
1310        }
1311        let stat = git::diff_stat(&worktree, &base_commit, "HEAD")
1312            .await
1313            .unwrap_or_default();
1314
1315        state.candidates.push(Candidate {
1316            index: 0,
1317            label: 'A',
1318            // Not an agent id on purpose: nothing in the roster wrote this, and
1319            // the stats tables must not credit anyone with a win for it.
1320            agent: EXISTING_BRANCH.to_owned(),
1321            branch: review_branch,
1322            worktree,
1323            summary: String::new(),
1324            stat,
1325            files,
1326            commits,
1327            empty: false,
1328            failed: None,
1329            verified_noop: None,
1330            duration_ms: 0,
1331            folded: false,
1332        });
1333        state.tally = Some(Tally {
1334            first_choice: BTreeMap::from([('A', 0)]),
1335            borda: BTreeMap::new(),
1336            winner: 'A',
1337            rankings: 0,
1338            unanimous_initial: false,
1339            deliberated: false,
1340            changed_votes: 0,
1341            unanimous_final: false,
1342            tie_break: None,
1343            // No panel sat, so no quorum applies. Zero judges is the correct
1344            // number for work that never competed, and must not be reported as
1345            // a collapsed panel.
1346            judges: 0,
1347            present: 0,
1348            quorum: 0,
1349            met_quorum: true,
1350            uncontested: Some("review-only run: nothing competed".to_owned()),
1351        });
1352        state.status = RunStatus::Reviewing;
1353        state.prep_complete = Some(true);
1354        state.event(
1355            "start",
1356            format!(
1357                "review-only run {} on `{branch}` ({files} files, {commits} commits)",
1358                state.id
1359            ),
1360        );
1361        Ok(())
1362    }
1363
1364    /// Authorize one bounded synchronization interval, under the caller's queue task
1365    /// claim and the same owner/execution locks used by run maintenance.
1366    pub async fn authorize_base_recovery(home: &Path, id: &str, task: &str) -> Result<()> {
1367        Self::authorize_base_recovery_request(home, id, task, false, None).await
1368    }
1369
1370    /// Queue release uses its durable approval generation exactly once.
1371    pub(crate) async fn authorize_base_recovery_from_resumption(
1372        home: &Path,
1373        id: &str,
1374        task: &str,
1375    ) -> Result<()> {
1376        Self::authorize_base_recovery_request(home, id, task, true, None).await
1377    }
1378
1379    pub(crate) async fn authorize_base_recovery_control(
1380        home: &Path,
1381        task: &str,
1382        control: &mut crate::base_recovery_control::Transaction,
1383    ) -> Result<()> {
1384        let id = control.request.run.clone();
1385        Self::authorize_base_recovery_request(home, &id, task, false, Some(control)).await
1386    }
1387
1388    async fn authorize_base_recovery_request(
1389        home: &Path,
1390        id: &str,
1391        task: &str,
1392        resumption: bool,
1393        mut control: Option<&mut crate::base_recovery_control::Transaction>,
1394    ) -> Result<()> {
1395        let _owner = crate::pr_head::owner_lock(home, id)?;
1396        let mut state = RunState::load_under(id, home)?;
1397        crate::pr_head::ensure_owner(&state)?;
1398        let queued = crate::queue::Queue::at(home.join("queue")).get(task)?;
1399        anyhow::ensure!(
1400            queued.execution_runs().last().is_some_and(|run| run == id)
1401                && queued.status != crate::queue::TaskStatus::Done
1402                && !queued.fresh_start
1403                && queued.review_branch.is_none(),
1404            "run task ownership changed"
1405        );
1406        anyhow::ensure!(
1407            state
1408                .origin
1409                .as_ref()
1410                .and_then(|o| o.task.as_deref())
1411                .is_none_or(|owner| owner == task),
1412            "run belongs to another task"
1413        );
1414        let claimed = crate::daemon::is_working_on_other(home, id, Timestamp::now())?;
1415        anyhow::ensure!(
1416            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
1417            "run is live or its ownership is unknown"
1418        );
1419        // Judge the previous driver's lease before acquiring our maintenance
1420        // lease. The owner lock excludes new driver claims across both steps.
1421        let _execution = crate::driver::maintenance(home, id)?;
1422        anyhow::ensure!(
1423            state.status.resumable()
1424                && state.released_to.is_none()
1425                && state.retired_to.is_none()
1426                && state.pr_taken_over_by.is_none(),
1427            "run ownership is final"
1428        );
1429        anyhow::ensure!(state.base_sync_blocked(), "run has no base-sync stop");
1430        anyhow::ensure!(
1431            !state.pr_publication_pending
1432                && !crate::handover::landing_checkpoint(&state)
1433                && state.merge_decision.is_none(),
1434            "publication or landing has its own retained checkpoint; base recovery cannot replace it"
1435        );
1436        let winner = state.winner().context("run has no retained winner")?;
1437        anyhow::ensure!(
1438            git::is_clean(&winner.worktree).await?,
1439            "retained worktree has uncommitted changes"
1440        );
1441        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
1442        anyhow::ensure!(
1443            git::rev_parse(&state.repo, &format!("refs/heads/{}", winner.branch)).await? == head,
1444            "retained worktree does not match the winner branch"
1445        );
1446        if let Some(control) = control.as_ref() {
1447            anyhow::ensure!(
1448                head.starts_with(&control.request.head),
1449                "retained HEAD changed since the owner request"
1450            );
1451            anyhow::ensure!(
1452                state
1453                    .base_sync_recovery
1454                    .stop
1455                    .as_ref()
1456                    .is_none_or(|stop| stop.head == head),
1457                "retained HEAD differs from the recorded stop head; inspect it first"
1458            );
1459        }
1460        state.ensure_base_episode();
1461        state.record_base_sync_stop(&head);
1462        anyhow::ensure!(
1463            state
1464                .base_sync_recovery
1465                .stop
1466                .as_ref()
1467                .is_some_and(|s| s.kind == crate::base_sync_recovery::StopKind::Exhausted),
1468            "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"
1469        );
1470        let fetched =
1471            git::fetch(&state.repo, &state.config.merge.remote, &state.base_branch).await?;
1472        anyhow::ensure!(
1473            fetched.ok(),
1474            "cannot authorize base recovery without a fetched base"
1475        );
1476        let approved_tip = git::rev_parse(
1477            &state.repo,
1478            &format!("{}/{}", state.config.merge.remote, state.base_branch),
1479        )
1480        .await?;
1481        if let Some(control) = control.as_deref_mut() {
1482            let queue = crate::queue::Queue::at(home.join("queue"));
1483            control.prepare(&queue, &state, &queued, &head, &approved_tip)?;
1484            if let Some(prior) = state
1485                .base_sync_recovery
1486                .authorizations
1487                .iter()
1488                .find(|a| a.request.as_deref() == Some(&control.key()))
1489            {
1490                anyhow::ensure!(
1491                    !prior.consumed && prior.invalidated.is_none() && state.base_recovery_pending(),
1492                    "recovery request was consumed or invalidated; it cannot queue again"
1493                );
1494                return control.enqueue(&queue);
1495            }
1496        }
1497        if resumption {
1498            anyhow::ensure!(
1499                crate::daemon::compatible_run_instruction(&state, &queued),
1500                "resumption instruction does not match the retained run"
1501            );
1502            let approval = queued
1503                .resumption
1504                .as_ref()
1505                .context("no operator resumption")?;
1506            anyhow::ensure!(
1507                approval.instruction == queued.instruction,
1508                "resumption approval does not match the current task instruction"
1509            );
1510            state.authorize_base_sync_resumption(task, approval)?;
1511        } else {
1512            state.authorize_base_sync(task)?;
1513        }
1514        let episode = state.base_sync_recovery.episodes.last().unwrap().id;
1515        state
1516            .base_sync_recovery
1517            .authorizations
1518            .last_mut()
1519            .unwrap()
1520            .scope = Some(crate::base_sync_recovery::Scope {
1521            tip: approved_tip,
1522            instruction: queued.instruction.clone(),
1523            episode,
1524        });
1525        if let Some(control) = control.as_deref_mut() {
1526            let authorization = state.base_sync_recovery.authorizations.last_mut().unwrap();
1527            authorization.request = Some(control.key());
1528            authorization.generation = control.generation();
1529            authorization.decision = control.decision();
1530            authorization.question = control
1531                .request
1532                .decision
1533                .as_ref()
1534                .map(|_| control.request.request.clone());
1535        }
1536        state.event(
1537            "base-recovery",
1538            "owner authorized a bounded base synchronization interval; fresh verification required",
1539        );
1540        state.save_under(home)?;
1541        if let Some(control) = control {
1542            control.enqueue(&crate::queue::Queue::at(home.join("queue")))?;
1543        }
1544        Ok(())
1545    }
1546
1547    /// Reopen an existing run.
1548    pub fn resume(id: &str) -> Result<Self> {
1549        let state = RunState::load(id)?;
1550        crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &state.id)?;
1551        if state.startup.as_ref().is_some_and(|s| !s.complete)
1552            || (state.status == RunStatus::Prep
1553                && state.instruction.trim().is_empty()
1554                && state.candidates.is_empty()
1555                && state.prep_complete == Some(false))
1556        {
1557            bail!(
1558                "run {id} did not finish startup; inspect its startup evidence and retained assets, then start an explicitly authorized review or recovery"
1559            );
1560        }
1561        crate::pr_head::ensure_owner(&state)?;
1562        if state.pr_recovery.is_some() && state.reviewed_commits.is_none() {
1563            bail!(
1564                "selected public-head recovery did not finish setup; use `magi task recover-pr` after correcting the cause"
1565            );
1566        }
1567        if let Some(to) = &state.released_to {
1568            bail!(
1569                "run {} cannot be resumed: its worktree was released to run {}",
1570                state.short(),
1571                crate::run::short_of(to)
1572            );
1573        }
1574        let roles = state.config.resolve_roles()?;
1575        if let Some(id) = &state.config.graph.selected_implementer
1576            && state.candidates.iter().any(|c| c.agent != *id)
1577        {
1578            bail!(
1579                "replacement implementer pin does not match the saved candidates; task must stay held"
1580            );
1581        }
1582        let max_parallel = state.config.graph.max_parallel.max(1);
1583        Ok(Self {
1584            state,
1585            roles,
1586            sem: Arc::new(Semaphore::new(max_parallel)),
1587            pause: Pause::new(),
1588            interrupt: Pause::new(),
1589        })
1590    }
1591
1592    /// Walk the graph to a terminal state, skipping nodes already recorded.
1593    ///
1594    /// Every way a run is driven - the queue loop, `magi run`, a resume from
1595    /// the phone - ends here, so this is the one place a run that ended
1596    /// Blocked / Stalled / Failed, or died with an error, is announced to the
1597    /// attention-report outbox. Best-effort: see [`crate::notices::raise`].
1598    pub fn execute(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
1599        // Allocate before polling: boxing inside an async wrapper would still
1600        // retain its construction frame while the nested graph is polled.
1601        Box::pin(self.execute_inner(None))
1602    }
1603
1604    pub(crate) async fn execute_sync_only(
1605        &mut self,
1606        request: crate::base_sync_only::Request,
1607    ) -> Result<()> {
1608        Box::pin(self.execute_inner(Some(request))).await
1609    }
1610
1611    async fn execute_inner(
1612        &mut self,
1613        sync_only: Option<crate::base_sync_only::Request>,
1614    ) -> Result<()> {
1615        anyhow::ensure!(
1616            self.state.startup.as_ref().is_none_or(|s| s.complete),
1617            "startup incomplete; inspect retained evidence before explicit recovery"
1618        );
1619        if let Some(selection) = &self.state.pr_recovery
1620            && (selection.source_proof.is_some() || selection.source_run.is_some())
1621        {
1622            Box::pin(selection.verify_source(&self.state.repo)).await?;
1623        }
1624        // Queue claims cover daemon work; this also serializes manual drivers
1625        // consuming a repair answer, including the new review and decision.
1626        let _repair_claim = if self.state.config.graph.selected_implementer.is_some()
1627            || self.state.land_approval.is_some()
1628            || self.state.merge_decision.is_some()
1629            || !self.state.merge_repairs.is_empty()
1630            || (self.state.status == RunStatus::Landing && land::repair_available(&self.state))
1631        {
1632            let claim = FixClaim::acquire(&self.state.dir())?;
1633            crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &self.state.id)?;
1634            let disk = RunState::load(&self.state.id)?;
1635            let checkpoint = |s: &RunState| {
1636                (
1637                    s.merge_repairs.len(),
1638                    s.merge_repairs
1639                        .last()
1640                        .map(|r| (r.question.clone(), r.phase)),
1641                    s.land_approval
1642                        .as_ref()
1643                        .map(|a| (a.question.clone(), a.head.clone())),
1644                )
1645            };
1646            if checkpoint(&disk) != checkpoint(&self.state) {
1647                bail!(
1648                    "repair decision changed since this run was loaded; reload and resume the existing run, never start a second repair"
1649                );
1650            }
1651            Some(claim)
1652        } else {
1653            None
1654        };
1655        let base_only = sync_only.is_some();
1656        let mut execution = self.claim_driver(sync_only).await?;
1657        let runner = &mut *execution.runner;
1658        let wait = runner.repository_wait();
1659        // Keep the graph's large future off the callers' stack, including
1660        // standalone task attempts running on a default-sized test thread.
1661        let result = if base_only {
1662            wait.scope(Box::pin(async {
1663                let repo = runner.state.repo.clone();
1664                let result = async {
1665                    let _coordination = runner.coordinate(&repo).await?;
1666                    anyhow::ensure!(
1667                        !runner.pause.parked() && !runner.interrupt.parked(),
1668                        "paused before base synchronization"
1669                    );
1670                    crate::base_sync_only::sync(&mut runner.state).await
1671                }
1672                .await;
1673                let pass = runner.state.sync_only_passes.last_mut().unwrap();
1674                pass.result = match result {
1675                    Ok(outcome) => outcome,
1676                    Err(error) => crate::base_sync_only::Outcome::Stopped(format!("{error:#}")),
1677                };
1678                let summary = pass.summary();
1679                runner.state.event("base-sync-only", summary);
1680                runner.state.save()
1681            }))
1682            .await
1683        } else {
1684            wait.scope(Box::pin(runner.execute_graph())).await
1685        };
1686        let result = match result {
1687            Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
1688                record_repository_block(&mut runner.state, &e);
1689                runner.park_here()?;
1690                Ok(())
1691            }
1692            other => other,
1693        };
1694        execution.driver.finish(&mut runner.state).await?;
1695        let ended = if result.is_err() {
1696            Some({
1697                let mut notice = crate::notices::run_stopped(&runner.state.id, &runner.state);
1698                if let Err(error) = &result {
1699                    notice.message = format!(
1700                        "Run {} stopped with an error: {}",
1701                        runner.state.id,
1702                        error.to_string().lines().next().unwrap_or("unknown error")
1703                    );
1704                }
1705                notice
1706            })
1707        } else {
1708            crate::notices::run_ended(&runner.state)
1709        };
1710        if let Some(notice) = ended {
1711            crate::notices::raise(notice);
1712        }
1713        result
1714    }
1715
1716    fn repository_wait(&self) -> crate::repo_lock::WaitPolicy {
1717        repository_wait(&self.state, Some((&self.pause, &self.interrupt)))
1718    }
1719
1720    async fn coordinate(&mut self, cwd: &Path) -> Result<Option<crate::repo_lock::SeatLease>> {
1721        let wait = self.repository_wait();
1722        coordinate_operation(&mut self.state, cwd, &wait).await
1723    }
1724
1725    /// Validate ownership and persist the driver claim in one critical section.
1726    async fn claim_driver(
1727        &mut self,
1728        sync_only: Option<crate::base_sync_only::Request>,
1729    ) -> Result<DriverExecution<'_>> {
1730        let owner = match crate::pr_head::owner_lock_wait(
1731            &crate::run::home(),
1732            &self.state.id,
1733            Duration::from_secs(self.state.config.graph.timeout_resource_wait),
1734        )
1735        .await
1736        {
1737            Ok(owner) => owner,
1738            Err(error) => {
1739                let detail = format!("worktree maintenance or ownership update: {error:#}");
1740                // Admission did not own run.json: retain this resource outcome
1741                // in memory for queue settlement without overwriting a concurrent
1742                // retirement or publication transaction.
1743                self.state.resource_block = Some(crate::run::ResourceBlock {
1744                    cause: crate::run::ResourceBlockCause::Other,
1745                    node: "start".into(),
1746                    kind: "worktree maintenance".into(),
1747                    detail: detail.clone(),
1748                    at: Timestamp::now(),
1749                });
1750                return Err(crate::repo_lock::ResourceBlocked(detail).into());
1751            }
1752        };
1753        let disk = RunState::load(&self.state.id)?;
1754        crate::pr_head::ensure_owner(&disk)?;
1755        let claimed =
1756            crate::daemon::is_working_on_other(&crate::run::home(), &disk.id, Timestamp::now())?;
1757        // Only proven-live ownership refuses here. Unknown records (legacy runs
1758        // with no claim marker or process identity) fall through to the
1759        // exclusive execution lease taken just below, which is what actually
1760        // keeps a second driver out.
1761        anyhow::ensure!(
1762            disk.liveness(claimed) != crate::run::Liveness::Live,
1763            "run already has a live driver; wait for its execution to end"
1764        );
1765        if let Some(to) = &disk.released_to {
1766            bail!(
1767                "run {} cannot continue: its worktree was released to run {}",
1768                self.state.short(),
1769                crate::run::short_of(to)
1770            );
1771        }
1772        anyhow::ensure!(
1773            serde_json::to_value(&disk.base_sync_recovery)?
1774                == serde_json::to_value(&self.state.base_sync_recovery)?,
1775            "base recovery changed since this run was loaded; reload the saved run"
1776        );
1777        anyhow::ensure!(
1778            disk.sync_only_passes == self.state.sync_only_passes,
1779            "base-only synchronization changed since this run was loaded; reload the saved run"
1780        );
1781        let driver = crate::driver::DriverGuard::acquire(&crate::run::home(), &disk)?;
1782        let mut execution = DriverExecution {
1783            runner: self,
1784            driver,
1785        };
1786        // Declare after the execution guard: on any claim error this short
1787        // lock must drop before that guard reloads and releases ownership.
1788        let _owner = owner;
1789        if let Some(request) = sync_only {
1790            crate::base_sync_only::validate_run(&disk, &crate::run::home())?;
1791            anyhow::ensure!(
1792                request.run == disk.id,
1793                "sync-base-only request targets a different run"
1794            );
1795            let state = &mut execution.runner.state;
1796            let task_entry = state.next_pass_task_entry;
1797            *state = disk;
1798            state.next_pass_task_entry = task_entry;
1799            if state.pending_sync_only().is_some() {
1800                let pass_index = state.passes.len();
1801                let pass = state.sync_only_passes.last_mut().unwrap();
1802                anyhow::ensure!(
1803                    pass.request == request,
1804                    "interrupted base-only synchronization belongs to a different request"
1805                );
1806                pass.pass_index = pass_index;
1807            } else {
1808                let pass = crate::base_sync_only::Pass::new(request, state);
1809                state.sync_only_passes.push(pass);
1810            }
1811            if state.status == RunStatus::Failed {
1812                state.status = RunStatus::Blocked;
1813            }
1814        } else {
1815            anyhow::ensure!(
1816                disk.pending_sync_only().is_none(),
1817                "base-only synchronization has not succeeded; resume with --sync-base-only before verifying"
1818            );
1819            crate::repair_budget::apply(&crate::run::home(), &mut execution.runner.state, &disk)
1820                .await?;
1821        }
1822        let state = &mut execution.runner.state;
1823        // Moving again, so it is no longer parked. Set before the walk rather
1824        // than in `resume`, so every way of re-entering the graph clears it
1825        // and a card cannot claim a run is waiting to be resumed while the
1826        // agents are already working.
1827        state.parked = false;
1828        state.resource_wait = None;
1829        state.resource_block = None;
1830        // Any seat this state still lists as answering belongs to whatever
1831        // process last drove this run — this one included, if it crashed
1832        // mid-wave. Cleared and flushed immediately, before anything else
1833        // runs, so a resume can never show a seat as live when nothing is
1834        // asking it anything yet; the node that actually dispatches the next
1835        // wave repopulates it.
1836        state.clear_active();
1837        // Recorded in the same spot, and flushed together with the clear
1838        // above: this is the pid a reader checks (`RunState::liveness`) when
1839        // no daemon claim exists to answer "is a process still driving this
1840        // run" — a plain `magi run` / `magi review` typed into a terminal
1841        // claims nothing there. Always overwritten, never only-if-absent, so
1842        // a resumed run's stale pid from a previous, possibly-dead process
1843        // can never survive into this one's own report. Unlike
1844        // `clear_active`, this changes on every single `execute()` call, so
1845        // the save below is now unconditional rather than only-if-cleared.
1846        //
1847        // `driver_started_at` is recorded in the same breath, from this same
1848        // pid, so `liveness` can tell a live pid that is genuinely still us
1849        // apart from one the OS has since handed to an unrelated process —
1850        // see that field's own doc for why the pid alone is not enough.
1851        let pid = std::process::id();
1852        state.driver_pid = Some(pid);
1853        state.driver_started_at = crate::proc::process_started_at(pid);
1854        state.driver_exited = false;
1855        state.driver_claimed = Some(true);
1856        state.begin_pass();
1857        execution.driver.bind(state);
1858        state.save()?;
1859        execution.driver.record(state)?;
1860        Ok(execution)
1861    }
1862
1863    /// No conflict checkpoint proves dispatch was never reached. End that
1864    /// consumed generation so an owner can explicitly authorize a fresh one.
1865    async fn repair_base_conflict(&mut self, dispatch: bool) -> Result<()> {
1866        let result = crate::base_conflict::repair(&mut self.state, dispatch).await;
1867        if let Err(error) = &result
1868            && !error.is::<crate::repo_lock::ResourceBlocked>()
1869            && self
1870                .state
1871                .repair_grants
1872                .last()
1873                .is_some_and(|g| g.conflict.is_none())
1874        {
1875            self.state.repair_grants.last_mut().unwrap().phase =
1876                crate::repair_budget::Phase::Complete;
1877            self.state.status = RunStatus::Blocked;
1878            self.state.save()?;
1879            bail!(
1880                "{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",
1881                self.state.passes.last().map_or(0, |p| p.index)
1882            );
1883        }
1884        result
1885    }
1886
1887    /// A grant owns only these repair attempts. Confirmation reviews cannot
1888    /// create another fixer allowance, and every operation is restart-checkpointed.
1889    async fn execute_granted_repair(&mut self) -> Result<()> {
1890        use crate::repair_budget::{Kind, Phase};
1891        let index = self.state.repair_grants.len() - 1;
1892        let winner = self
1893            .state
1894            .winner()
1895            .cloned()
1896            .context("repair winner missing")?;
1897        loop {
1898            let grant = self.state.repair_grants[index].clone();
1899            match grant.phase {
1900                Phase::Pending => {
1901                    if grant.spent >= grant.receipt.request.rounds {
1902                        self.state.repair_grants[index].phase = Phase::Complete;
1903                        self.state.status = RunStatus::Blocked;
1904                        self.state.save()?;
1905                        return Ok(());
1906                    }
1907                    // Reserve before dispatch. A crash can consume an attempt,
1908                    // but can never duplicate it or reset saved fixer history.
1909                    self.state.repair_grants[index].spent += 1;
1910                    self.state.repair_grants[index].phase = Phase::Fixing;
1911                    self.state.save()?;
1912                    match grant.receipt.request.kind {
1913                        Kind::BaseConflict => self.repair_base_conflict(true).await?,
1914                        Kind::Gate => {
1915                            let failed = self.state.gate.clone();
1916                            let _ = self.gate_fix_round(&winner, &failed).await?;
1917                        }
1918                        Kind::Review => {
1919                            let mut record = self
1920                                .state
1921                                .reviews
1922                                .last()
1923                                .cloned()
1924                                .context("review failure missing")?;
1925                            let round = record.round;
1926                            let step = self.run_fix_round(&winner, &mut record).await?;
1927                            self.state.reviews[round - 1] = record;
1928                            if matches!(step, FixStep::Recorded { report_lost: true }) {
1929                                self.state.repair_grants[index].phase = Phase::Complete;
1930                                self.state.status = RunStatus::Blocked;
1931                                self.state.event("repair-grant", "fixer continuation remains unresolved; repair grant cannot bypass its stop");
1932                                self.state.save()?;
1933                                return Ok(());
1934                            }
1935                            if matches!(step, FixStep::Resource) {
1936                                self.stop_for_resource()?;
1937                                return Ok(());
1938                            }
1939                            self.state.save()?;
1940                        }
1941                    }
1942                    if self.resource_halt()? {
1943                        return Ok(());
1944                    }
1945                }
1946                Phase::Fixing => {
1947                    if grant.receipt.request.kind == Kind::BaseConflict {
1948                        self.repair_base_conflict(false).await?;
1949                    }
1950                    // Interrupted fixers may have left source changes or an
1951                    // unpushed commit. Preserve them before fresh assessment.
1952                    let _coordination = self.coordinate(&winner.worktree).await?;
1953                    let rescued = git::rescue_commit(
1954                        &winner.worktree,
1955                        "magi: preserve interrupted granted repair",
1956                    )
1957                    .await?;
1958                    self.state.note_withheld("repair-grant", &rescued.withheld);
1959                    // Fresh checks must supersede even a same-head failure.
1960                    // Archive rather than erase failure evidence or counters.
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: self.state.gate_head.take(),
1968                            gate_ran: std::mem::take(&mut self.state.gate_ran),
1969                            gate: std::mem::take(&mut self.state.gate),
1970                            e2e: self.state.head_e2e.take(),
1971                        });
1972                    if let Some(e2e) = self.state.gate_repair_e2e.take() {
1973                        self.state
1974                            .verification_history
1975                            .push(crate::run::VerificationEvidence {
1976                                superseded_by: None,
1977                                archived_at: Some(Timestamp::now()),
1978                                fixes_spent: Some(self.state.gate_fixes.len()),
1979                                gate_head: None,
1980                                gate_ran: false,
1981                                gate: Vec::new(),
1982                                e2e: Some(e2e),
1983                            });
1984                    }
1985                    self.state.repair_grants[index].review_start = self.state.reviews.len();
1986                    self.state.repair_grants[index].head =
1987                        git::rev_parse(&winner.worktree, "HEAD").await?;
1988                    self.state.repair_grants[index].phase = Phase::Reviewing;
1989                    if grant.receipt.request.kind == Kind::BaseConflict {
1990                        self.state.base_sync_recovery.stop = None;
1991                        if let Some(sync) = &mut self.state.base_sync {
1992                            sync.tip = grant
1993                                .receipt
1994                                .request
1995                                .tip
1996                                .clone()
1997                                .context("repair base tip missing")?;
1998                            sync.conflict = None;
1999                            sync.behind = 0;
2000                        }
2001                        refresh_reviewed_commits(&mut self.state, &winner.branch).await;
2002                    }
2003                    self.state.save()?;
2004                }
2005                Phase::Reviewing => {
2006                    self.review_loop_pass().await?;
2007                    if self.resource_halt()? {
2008                        return Ok(());
2009                    }
2010                    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
2011                    let clean = self.state.reviews.len() > grant.review_start
2012                        && self.state.reviews.last().is_some_and(|r| {
2013                            r.head == head
2014                                && r.clean
2015                                && r.expected > 0
2016                                && r.answered == r.expected
2017                                && matches!(
2018                                    r.e2e_status(),
2019                                    E2eStatus::Passed | E2eStatus::NotConfigured
2020                                )
2021                        });
2022                    if !clean {
2023                        // A confirmation review carries no additional fix budget.
2024                        self.state.repair_grants[index].phase = if grant.receipt.request.kind
2025                            == Kind::Review
2026                            && grant.spent < grant.receipt.request.rounds
2027                            && self.state.reviews.last().is_some_and(|r| {
2028                                r.fix.is_none()
2029                                    && (r.blocking > 0 || r.e2e_status() == E2eStatus::Failed)
2030                            }) {
2031                            Phase::Pending
2032                        } else {
2033                            Phase::Complete
2034                        };
2035                        self.state.status = RunStatus::Blocked;
2036                        self.state.event(
2037                            "repair-grant",
2038                            "fresh review did not clear the repaired head; no publication",
2039                        );
2040                        self.state.save()?;
2041                        if self.state.repair_grants[index].phase == Phase::Pending {
2042                            continue;
2043                        }
2044                        return Ok(());
2045                    }
2046                    self.state.repair_grants[index].phase = Phase::Gating;
2047                    self.state.save()?;
2048                }
2049                Phase::Gating => {
2050                    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
2051                    self.state.reconcile_verification_head(&head);
2052                    let wait = self.repository_wait();
2053                    if self
2054                        .state
2055                        .reviews
2056                        .last()
2057                        .is_none_or(|r| r.head != head || !r.clean)
2058                    {
2059                        self.state.status = RunStatus::Blocked;
2060                        self.state.repair_grants[index].phase = Phase::Complete;
2061                        self.state.event(
2062                            "repair-grant",
2063                            "head changed since fresh review; repair held",
2064                        );
2065                        self.state.save()?;
2066                        return Ok(());
2067                    }
2068                    if !verify_current_head(&mut self.state, &winner, &wait).await? {
2069                        return Ok(());
2070                    }
2071                    let outcomes = self.run_gate(&winner).await?;
2072                    if verify_inconclusive(&outcomes) {
2073                        return Ok(());
2074                    }
2075                    let after = git::rev_parse(&winner.worktree, "HEAD").await?;
2076                    if after != head {
2077                        self.state.repair_grants[index].review_start = self.state.reviews.len();
2078                        self.state.repair_grants[index].head = after;
2079                        self.state.repair_grants[index].phase = Phase::Reviewing;
2080                        self.state.status = RunStatus::Blocked;
2081                        self.state.event("repair-grant", "pre-gate changed the reviewed head; resume for fresh review before publication");
2082                        self.state.save()?;
2083                        return Ok(());
2084                    }
2085                    let passed = outcomes.iter().all(CommandOutcome::ok);
2086                    // Follow-up grants owe the same guarded checkout delivery
2087                    // as the conflict repair that introduced the new head.
2088                    if passed
2089                        && !crate::foreign_checkout::write_back(&mut self.state, &head).await?
2090                    {
2091                        return Ok(());
2092                    }
2093                    self.state.repair_grants[index].succeeded = passed;
2094                    self.state.gate = outcomes;
2095                    self.state.gate_ran = true;
2096                    self.state.status = if passed {
2097                        RunStatus::Gating
2098                    } else {
2099                        RunStatus::Blocked
2100                    };
2101                    self.state.repair_grants[index].phase = if !passed
2102                        && grant.receipt.request.kind == Kind::Gate
2103                        && grant.spent < grant.receipt.request.rounds
2104                    {
2105                        Phase::Pending
2106                    } else {
2107                        Phase::Complete
2108                    };
2109                    if passed && self.state.config.merge.mode == MergeMode::Pr {
2110                        // Persist publication debt with the successful checkpoint.
2111                        self.state.pr_publication_pending = true;
2112                    } else if passed {
2113                        self.state.status = RunStatus::Ready;
2114                    }
2115                    self.state.save()?;
2116                    if !passed {
2117                        continue;
2118                    }
2119                    // Existing PR ownership and push lease stay in place. The
2120                    // normal publisher owes the new reviewed/gated SHA, and
2121                    // land's fresh owner approval remains mandatory.
2122                    if self.state.config.merge.mode != MergeMode::Pr {
2123                        self.state.status = RunStatus::Ready;
2124                        self.state.event(
2125                            "repair-grant",
2126                            "repair verified locally; grant carries no merge authorization",
2127                        );
2128                        self.state.save()?;
2129                        return Ok(());
2130                    }
2131                    return self.merge().await;
2132                }
2133                Phase::Complete => return Ok(()),
2134            }
2135        }
2136    }
2137
2138    async fn execute_graph(&mut self) -> Result<()> {
2139        // Even a terminal run may reenter through an explicit recovery action.
2140        // Restore before prep shortcuts, saved conversations or graph nodes use
2141        // a disposable path; GC may already have removed its original objects.
2142        let archive_home = crate::run::home().canonicalize()?;
2143        if crate::retention::has_archived_seats(&archive_home, &self.state)? {
2144            let repo = self.state.repo.clone();
2145            let _coordination = self.coordinate(&repo).await?;
2146            ensure_setup_config(&mut self.state, &repo).await?;
2147            crate::retention::restore_execution_seats(
2148                &archive_home,
2149                &self.state,
2150                _coordination.as_ref(),
2151            )
2152            .await?;
2153        }
2154        self.state.configure_recovery_resume()?;
2155        if self
2156            .state
2157            .repair_grants
2158            .last()
2159            .is_some_and(|g| g.phase != crate::repair_budget::Phase::Complete)
2160        {
2161            return self.execute_granted_repair().await;
2162        }
2163        if self
2164            .state
2165            .repair_grants
2166            .last()
2167            .is_some_and(|g| !g.succeeded)
2168        {
2169            self.state.status = RunStatus::Blocked;
2170            self.state.save()?;
2171            return Ok(());
2172        }
2173        // Preservation may invalidate an old empty classification. Resolve it
2174        // before any resume shortcut can reuse a verdict or publish a branch.
2175        self.persist_candidates().await?;
2176        // A saved base stop outranks stage markers, including legacy Voting.
2177        // Recovery never reenters implementation, deliberation or voting.
2178        if self.state.base_sync_blocked() {
2179            self.sync_to_base().await?;
2180            if !self.state.base_sync_blocked()
2181                && self.state.status != RunStatus::AlreadyInBase
2182                && !self.resource_halt()?
2183            {
2184                self.finish_after_tally().await?;
2185            }
2186            return Ok(());
2187        }
2188        if self
2189            .state
2190            .merge_decision
2191            .as_ref()
2192            .is_some_and(|decision| !decision.closed)
2193            && self.state.status != RunStatus::Landing
2194        {
2195            if crate::merge_decision::resumable_hold(&self.state) {
2196                self.state.merge = Some(MergeOutcome {
2197                    mode: MergeMode::Pr,
2198                    ok: false,
2199                    detail: self
2200                        .state
2201                        .merge_decision
2202                        .as_ref()
2203                        .unwrap()
2204                        .target
2205                        .pr
2206                        .clone(),
2207                    empty: false,
2208                });
2209                self.run_land().await?;
2210                self.settle_questions();
2211                return Ok(());
2212            }
2213            bail!(
2214                "owner stop decision is held; inspect the existing PR and request an explicit fresh review/decision before further work"
2215            );
2216        }
2217        if self.state.config.graph.selected_implementer.is_some()
2218            && self.state.status == RunStatus::Blocked
2219            && self.state.tally.is_none()
2220            && self.state.candidate_preservation.is_empty()
2221            && self.state.interrupted_implementations.is_empty()
2222        {
2223            bail!(
2224                "selected implementation is held; explicitly release the owning task to retry it"
2225            );
2226        }
2227
2228        if self.state.merge_repairs.last().is_some_and(|r| {
2229            matches!(
2230                r.phase,
2231                crate::run::MergeRepairPhase::Requested
2232                    | crate::run::MergeRepairPhase::Fixing
2233                    | crate::run::MergeRepairPhase::Reviewing
2234            )
2235        }) {
2236            if self.repair_merge_review().await? {
2237                self.run_land().await?;
2238            }
2239            self.settle_questions();
2240            return Ok(());
2241        }
2242        // Publication already passed review and gate. Resume only that node:
2243        // syncing to a newer base here could change the verified commit.
2244        if self.state.pr_publication_pending {
2245            self.merge().await?;
2246            if self.resource_halt()? {
2247                return Ok(());
2248            }
2249            self.state.save()?;
2250            self.settle_questions();
2251            return Ok(());
2252        }
2253        // A run that already lost its quorum never resumes into the verdict
2254        // machinery: `deliberate` and `vote` would otherwise clobber the
2255        // stalled marker back to Voting and the run would keep going past a
2256        // verdict that is no longer trustworthy. Everything already recorded is
2257        // kept, so the run stays resumable (or foldable) for a human to pick up.
2258        //
2259        // On --resume the run gets one chance to repair itself: the seats a
2260        // rate limit took out are re-asked. If their quota has since reset and
2261        // the quorum is restored, the run picks up and finishes; otherwise it
2262        // stays stale and still-resumable for a later retry. If it does not
2263        // recover, the returned status stays `Stalled` and nothing was
2264        // clobbered (the recovery only mutates entries for the lost seats).
2265        if self.state.status == RunStatus::Stalled {
2266            if self.recover_stall().await? {
2267                self.finish_after_tally().await?;
2268            } else {
2269                // Still below quorum: persist the marker and stay resumable.
2270                self.state.save()?;
2271            }
2272            return Ok(());
2273        }
2274        // A run parked inside `land` - watching CI, mid fix-round, or
2275        // waiting on the owner's merge approval - resumes directly into it,
2276        // never back through `prep`. Everything before `merge` already
2277        // concluded; that is the only way `status` reaches `Landing` in the
2278        // first place. Re-walking `review_loop` first would also be actively
2279        // wrong: its own status recomputation (see its doc) treats any
2280        // clean round as reason to set `status` to `Gating`, which would
2281        // clobber this marker before `merge` ever ran, and this run would
2282        // never find its way back into `land` at all.
2283        if self.state.status == RunStatus::Landing
2284            || crate::handover::landing_checkpoint(&self.state)
2285        {
2286            self.state.land_sync_pending = true;
2287            self.state.save()?;
2288            self.run_land().await?;
2289            // `run_land` may have settled the run right here - CI came back
2290            // green and the PR merged, say - without ever passing back
2291            // through `merge`'s own trailing call. Whatever it left `status`
2292            // as is what this has to read.
2293            self.settle_questions();
2294            return Ok(());
2295        }
2296        // A run parked at `merge` on the owner's word about a withheld PR text
2297        // resumes straight into `merge`. Re-walking the tail would sync to the
2298        // base again (possibly rebasing, possibly spending the fixer) after the
2299        // gate had passed, and then push a tree nobody reviewed or gated.
2300        if self.state.github_text.is_some()
2301            && self.state.merge.is_none()
2302            && self.state.status == RunStatus::Gating
2303        {
2304            self.merge().await?;
2305            if self.resource_halt()? {
2306                return Ok(());
2307            }
2308            self.state.save()?;
2309            return Ok(());
2310        }
2311        if let Err(e) = self.prep().await {
2312            if e.is::<crate::repo_lock::ResourceBlocked>() {
2313                return Err(e);
2314            }
2315            self.state.status = RunStatus::Blocked;
2316            self.state
2317                .prep_failure
2318                .get_or_insert_with(|| format!("{e:#}"));
2319            self.state
2320                .event("prep", format!("preparation stopped: {e:#}"));
2321            self.state.save()?;
2322            return Err(e);
2323        }
2324        if self.park_here()? {
2325            return Ok(());
2326        }
2327        self.advise().await?;
2328        if self.park_here()? {
2329            return Ok(());
2330        }
2331        self.implement().await?;
2332        if self.park_here()? {
2333            return Ok(());
2334        }
2335        // `after_implement` already saved the state and settled any open
2336        // questions when it set this; nothing later in the graph has
2337        // anything to judge.
2338        if self.state.status == RunStatus::VerifiedNoop {
2339            return Ok(());
2340        }
2341        self.judge().await?;
2342        if self.park_here()? {
2343            return Ok(());
2344        }
2345        self.deliberate().await?;
2346        if self.park_here()? {
2347            return Ok(());
2348        }
2349        self.vote().await?;
2350        if self.park_here()? {
2351            return Ok(());
2352        }
2353        self.tally()?;
2354        // A verdict that lost its quorum is not trustworthy: do not review,
2355        // gate, or merge on it. Everything already done is kept, so the run
2356        // stays resumable (or foldable); the human can replace the agent that
2357        // ran out of quota and pick it up.
2358        if self.state.status == RunStatus::Stalled {
2359            // Persist the stalled marker now — the normal end-of-execute save
2360            // below is below this early return, and without it a resumed run
2361            // would reload a pre-tally status and keep going.
2362            self.state.save()?;
2363            return Ok(());
2364        }
2365        self.finish_after_tally().await?;
2366        Ok(())
2367    }
2368
2369    /// A wave could not start its agents because a shared resource stayed busy
2370    /// (see [`RunState::resource_block`]): leave the run `Blocked` and
2371    /// resumable. Unstarted seats have no result; completed peers retain
2372    /// their saved candidate state.
2373    fn stop_for_resource(&mut self) -> Result<()> {
2374        // Resource acquisition observes cancellation inside a node. Complete
2375        // the same durable park as every other node boundary before returning.
2376        if self.pause.parked() || self.interrupt.parked() {
2377            self.park_here()?;
2378            return Ok(());
2379        }
2380        if self.state.resource_block.is_some() {
2381            self.state.status = RunStatus::Blocked;
2382        }
2383        self.state.save()
2384    }
2385
2386    /// Stop walking the graph if a node ended on a resource block.
2387    fn resource_halt(&mut self) -> Result<bool> {
2388        if self.state.resource_block.is_none() {
2389            return Ok(false);
2390        }
2391        self.stop_for_resource()?;
2392        Ok(true)
2393    }
2394
2395    /// Park here if asked to, recording it in the run's own timeline.
2396    ///
2397    /// Returns whether the caller should stop walking the graph. The state is
2398    /// saved either way by the node that just finished; this adds the event so
2399    /// the operator's card says why a run that is neither finished nor moving
2400    /// is sitting where it is.
2401    fn park_here(&mut self) -> Result<bool> {
2402        let parking = self.pause.parked() || self.interrupt.parked();
2403        if !parking && self.state.resource_block.is_some() {
2404            self.stop_for_resource()?;
2405            return Ok(true);
2406        }
2407        // Either handle asking is enough - see `Pause`'s own doc for why
2408        // they are never the same one. `interrupt` is checked second so a
2409        // reason it carries is preferred in the message below over a plain
2410        // shutdown park racing it at the same boundary.
2411        if !self.pause.parked() && !self.interrupt.parked() {
2412            return Ok(false);
2413        }
2414        if self.state.parked {
2415            return Ok(true);
2416        }
2417        let cause = self.interrupt.cause().or_else(|| self.pause.cause());
2418        if let Some(block) = &mut self.state.resource_block
2419            && matches!(
2420                block.cause,
2421                crate::run::ResourceBlockCause::Cancelled { .. }
2422            )
2423        {
2424            block.cause = crate::run::ResourceBlockCause::Cancelled {
2425                park: cause.clone(),
2426            };
2427        }
2428        let why = match cause.as_ref().map(ParkCause::label) {
2429            Some(reason) => format!(
2430                "parked after `{}` ({reason}) — resume to carry on from here",
2431                self.state.status.as_str()
2432            ),
2433            None => format!(
2434                "parked after `{}` — resume to carry on from here",
2435                self.state.status.as_str()
2436            ),
2437        };
2438        self.state.event("park", why);
2439        self.state
2440            .end_pass_parked(cause.unwrap_or(ParkCause::Unspecified));
2441        self.state.parked = true;
2442        self.state.save()?;
2443        Ok(true)
2444    }
2445
2446    /// Only a new explicit operator approval may retry failed preparation.
2447    pub fn retry_preparation(&mut self, approval_at: jiff::Timestamp) -> Result<()> {
2448        if self.state.prep_failure.is_none() {
2449            return Ok(());
2450        }
2451        let failed_at = self
2452            .state
2453            .events
2454            .iter()
2455            .rev()
2456            .find(|event| event.node == "prep")
2457            .map_or(self.state.updated_at, |event| event.at);
2458        anyhow::ensure!(
2459            approval_at > failed_at,
2460            "preparation retry requires a new explicit release after the failure"
2461        );
2462        self.state.prep_failure = None;
2463        self.state.prep_complete = Some(false);
2464        self.state
2465            .event("prep-retry", "operator approved retry of preparation");
2466        Ok(())
2467    }
2468
2469    /// Hand the runner the pause `magi serve`'s own shutdown watches.
2470    pub fn on_pause(&mut self, pause: Pause) {
2471        self.pause = pause;
2472    }
2473
2474    /// Hand the runner a second, independent pause: `magi serve`'s interrupt
2475    /// scheduler asking this one run - and no other - to park so a task
2476    /// marked [`crate::queue::Task::interrupt`] can run alone. See
2477    /// [`Pause`]'s own doc for why this is never [`Runner::on_pause`]'s
2478    /// handle.
2479    pub fn watch_interrupt(&mut self, pause: Pause) {
2480        self.interrupt = pause;
2481    }
2482
2483    /// Abandon this run's own open questions, once `status` has actually
2484    /// settled rather than merely paused.
2485    ///
2486    /// `Blocked` and `Stalled` are `RunStatus::resumable` — a human can pick
2487    /// either back up with the candidates, the review round and the seat
2488    /// sessions already on disk, so a question an implementer asked mid-round
2489    /// may still get a real answer read by a real resume. Only the statuses
2490    /// `resumable` excludes are actually final: the run merged, it reached
2491    /// `Ready` with nothing left to do, it failed outright with no
2492    /// established point to continue from, or every candidate agreed, with
2493    /// evidence, that nothing belonged in the worktree (`VerifiedNoop`). In
2494    /// every one of those the seat that asked is gone for good, exactly like
2495    /// the run being deleted under `magi run rm` - so the same cleanup
2496    /// applies, worded for what actually happened instead of "the run was
2497    /// deleted".
2498    ///
2499    /// Best-effort and silent on success: called from every place `status`
2500    /// can land on one of those three, including ones a resumed run revisits,
2501    /// so it must cost nothing when there was nothing open to begin with.
2502    fn settle_questions(&mut self) {
2503        if let Err(e) = ask::Questions::open().settle_run(&self.state.id, self.state.status) {
2504            tracing::warn!("abandon questions for {}: {e:#}", self.state.id);
2505        }
2506    }
2507
2508    /// The tail of the graph after a trustworthy tally: fold losers, review,
2509    /// gate, merge, and persist.
2510    fn finish_after_tally(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
2511        Box::pin(self.finish_after_tally_inner())
2512    }
2513
2514    async fn finish_after_tally_inner(&mut self) -> Result<()> {
2515        // Before the losers are folded: their branches are what the graft
2516        // reads from.
2517        self.graft().await?;
2518        if self.resource_halt()? {
2519            return Ok(());
2520        }
2521        self.fold_losers().await?;
2522        // Before review starts, and again right before the gate: a run's
2523        // review rounds can themselves take long enough for the base to move
2524        // a second time, and the gate is the one node whose "green" gets
2525        // acted on.
2526        self.sync_to_base().await?;
2527        if self.hold_base_sync().await? || self.resource_halt()? {
2528            return Ok(());
2529        }
2530        if self.state.status == RunStatus::AlreadyInBase {
2531            return Ok(());
2532        }
2533        self.review_loop().await?;
2534        if self.resource_halt()? {
2535            return Ok(());
2536        }
2537        self.sync_to_base().await?;
2538        if self.hold_base_sync().await? || self.resource_halt()? {
2539            return Ok(());
2540        }
2541        if self.state.status == RunStatus::AlreadyInBase {
2542            return Ok(());
2543        }
2544        self.gate().await?;
2545        self.merge().await?;
2546        if self.resource_halt()? {
2547            return Ok(());
2548        }
2549        self.state.save()?;
2550        Ok(())
2551    }
2552
2553    // ---------------------------------------------------------------- prep
2554
2555    /// Run `[worktree] setup` in a seat's fresh worktree. A failure blocks the
2556    /// run with the step and its output in the event; it is never swallowed.
2557    /// During `prep` (`in_prep`) the whole preparation is rolled back, so a
2558    /// resume starts over instead of finding candidates and missing seats.
2559    async fn setup_seat_worktree(
2560        &mut self,
2561        repo: &Path,
2562        wt: &Path,
2563        in_prep: bool,
2564        coordination: Option<&crate::repo_lock::SeatLease>,
2565    ) -> Result<()> {
2566        let result = match ensure_setup_config(&mut self.state, repo).await {
2567            Ok(()) => {
2568                worktree_setup::prepare_with(
2569                    &self.state.config,
2570                    repo,
2571                    wt,
2572                    crate::build_target::Coordination::Held(coordination),
2573                )
2574                .await
2575            }
2576            Err(e) => Err(e),
2577        };
2578        if let Err(e) = result {
2579            git::worktree_remove_clean(repo, wt).await.ok();
2580            if in_prep {
2581                self.rollback_prep(repo).await;
2582            }
2583            self.state.status = RunStatus::Blocked;
2584            self.state.event(
2585                "setup",
2586                format!("worktree setup failed in {}: {e:#}", wt.display()),
2587            );
2588            self.state.save()?;
2589            return Err(e);
2590        }
2591        Ok(())
2592    }
2593
2594    /// Undo everything `prep` created, so a resume re-runs it whole.
2595    async fn rollback_prep(&mut self, repo: &Path) {
2596        let root = self.state.worktree_root();
2597        for c in std::mem::take(&mut self.state.candidates) {
2598            if matches!(
2599                git::worktree_remove_clean(repo, &c.worktree).await,
2600                Ok(true)
2601            ) {
2602                git::branch_delete(repo, &c.branch).await.ok();
2603            } else {
2604                self.state.candidates.push(c);
2605            }
2606        }
2607        let seats = self.roles.judges.len().max(self.state.config.graph.judges);
2608        for j in 1..=seats {
2609            remove_read_seat_worktree(&mut self.state, &root.join(format!("judge-{j}")))
2610                .await
2611                .ok();
2612        }
2613        for k in 1..=self.state.config.graph.advisors {
2614            remove_read_seat_worktree(&mut self.state, &root.join(format!("advisor-{k}")))
2615                .await
2616                .ok();
2617        }
2618    }
2619
2620    async fn prep(&mut self) -> Result<()> {
2621        if let Some(reason) = &self.state.prep_failure {
2622            bail!(
2623                "candidate preparation previously failed: {reason}; correct the source before retrying"
2624            );
2625        }
2626        if self
2627            .state
2628            .prep_complete
2629            .unwrap_or(!self.state.candidates.is_empty())
2630        {
2631            return Ok(());
2632        }
2633        let repo = self.state.repo.clone();
2634        // Includes rollback, config, refs, checkout creation and setup. No
2635        // repository mutation may precede the real shared lock acquisition.
2636        let _coordination = self.coordinate(&repo).await?;
2637        let base = self.state.base_commit.clone();
2638        let plan = self.state.sources.plan(&repo, &base).await?;
2639        self.rollback_prep(&repo).await;
2640        if !self.state.candidates.is_empty() {
2641            bail!(
2642                "preparation rollback retained worktrees; recover their uncommitted work before retrying"
2643            );
2644        }
2645        self.state.prep_complete = Some(false);
2646        self.state.status = RunStatus::Prep;
2647        self.state.save()?;
2648        let repo = self.state.repo.clone();
2649        let start = plan.start.clone().unwrap_or_else(|| base.clone());
2650        let root = self.state.worktree_root();
2651        let labels = blind::assign_labels(self.roles.implementers.len(), self.state.seed);
2652
2653        // The hook is the write-time half of the blindness contract; the
2654        // presentation filter in `blind` is the half that cannot be bypassed.
2655        let hooks_dir = self.state.dir().join("hooks");
2656        if self.state.config.blind.commit_msg_hook {
2657            std::fs::create_dir_all(&hooks_dir)
2658                .with_context(|| format!("create {}", hooks_dir.display()))?;
2659            let script = blind::commit_msg_hook(&self.state.config.blind.strip_lines);
2660            let path = hooks_dir.join("commit-msg");
2661            std::fs::write(&path, script).with_context(|| format!("write {}", path.display()))?;
2662            make_executable(&path)?;
2663            // Ref-counted rather than a plain idempotent set: with more than
2664            // one run able to be in flight in the same repository at once
2665            // (see `Config::daemon.max_concurrent_runs`), a bare "already
2666            // true?" check cannot tell "another run of mine still needs
2667            // this" from "nobody does", and the run that happens to finish
2668            // first would disable the hook out from under a sibling still
2669            // relying on it.
2670            git::acquire_worktree_config(&repo).await?;
2671            self.state.enabled_worktree_config = true;
2672        }
2673
2674        // `[worktree] setup` hides its products per worktree, which needs the
2675        // same per-worktree config the hook does. Held until fold, like it.
2676        ensure_setup_config(&mut self.state, &repo).await?;
2677
2678        for (index, (spec, label)) in self
2679            .roles
2680            .implementers
2681            .clone()
2682            .into_iter()
2683            .zip(labels)
2684            .enumerate()
2685        {
2686            let branch = self.state.branch_for(label);
2687            let worktree = root.join(format!("cand-{label}"));
2688            // Persist intent before Git can leave a partially created tree.
2689            // Candidate registration follows setup, so it cannot inventory
2690            // crashes or refusals during creation itself.
2691            self.state.event(
2692                "prep-intent",
2693                serde_json::json!({
2694                    "branch": branch,
2695                    "worktree": worktree,
2696                    "start": start,
2697                    "picks": plan.picks,
2698                })
2699                .to_string(),
2700            );
2701            self.state.save()?;
2702            git::worktree_add_branch(&repo, &worktree, &branch, &start).await?;
2703            if self.state.config.blind.commit_msg_hook {
2704                git::set_worktree_hooks_path(&worktree, &hooks_dir).await?;
2705            }
2706            git::local_exclude(&worktree, "/.magi/").await?;
2707            if let Err(e) = worktree_setup::prepare_with(
2708                &self.state.config,
2709                &repo,
2710                &worktree,
2711                crate::build_target::Coordination::Held(_coordination.as_ref()),
2712            )
2713            .await
2714            {
2715                // Nothing of this prep may survive: a resume must start over,
2716                // not find half the candidates and skip the rest.
2717                git::worktree_remove_clean(&repo, &worktree).await.ok();
2718                git::branch_delete(&repo, &branch).await.ok();
2719                self.rollback_prep(&repo).await;
2720                self.state.status = RunStatus::Blocked;
2721                self.state
2722                    .event("prep", format!("worktree setup failed: {e:#}"));
2723                if !e.is::<crate::repo_lock::ResourceBlocked>() {
2724                    self.state.prep_failure = Some(format!("worktree setup failed: {e:#}"));
2725                }
2726                self.state.save()?;
2727                return Err(e);
2728            }
2729            self.state.candidates.push(Candidate {
2730                index,
2731                label,
2732                agent: spec.id.clone(),
2733                branch,
2734                worktree,
2735                summary: String::new(),
2736                stat: String::new(),
2737                files: 0,
2738                commits: 0,
2739                empty: false,
2740                failed: None,
2741                verified_noop: None,
2742                duration_ms: 0,
2743                folded: false,
2744            });
2745            self.state.save()?;
2746            for pick in &plan.picks {
2747                if let Err(e) = git::cherry_pick(&self.state.candidates[index].worktree, pick).await
2748                {
2749                    self.state.status = RunStatus::Blocked;
2750                    self.state.prep_failure = Some(format!("cannot apply referenced commit: {e}"));
2751                    self.state
2752                        .event("prep", format!("cannot apply referenced commit: {e}"));
2753                    self.state.save()?;
2754                    return Err(e);
2755                }
2756            }
2757        }
2758
2759        for j in 1..=self.roles.judges.len() {
2760            let wt = root.join(format!("judge-{j}"));
2761            if !wt.exists() {
2762                git::worktree_add_detached(&repo, &wt, &base).await?;
2763                self.setup_seat_worktree(&repo, &wt, true, _coordination.as_ref())
2764                    .await?;
2765            }
2766        }
2767
2768        // Disposable, detached checkouts for the design-deliberation stage's
2769        // advisor seats — the same shape as the judges' above, at the same
2770        // base commit, since advisors also only ever read. Sized off the
2771        // configured count directly rather than a resolved roster: unlike
2772        // `implementers`/`judges`/`reviewers`, advisor seats are resolved
2773        // lazily inside `advise` itself (see `Config::advisors`'s doc), so
2774        // `prep` has no `ResolvedRoles` field to read a count from here.
2775        if self.state.config.graph.advise {
2776            for k in 1..=self.state.config.graph.advisors {
2777                let wt = root.join(format!("advisor-{k}"));
2778                if !wt.exists() {
2779                    git::worktree_add_detached(&repo, &wt, &base).await?;
2780                    self.setup_seat_worktree(&repo, &wt, true, _coordination.as_ref())
2781                        .await?;
2782                }
2783            }
2784        }
2785
2786        // A judge cannot tell it is looking at its own patch — the seats keep
2787        // separate conversations — but a panel that shares agents with the
2788        // field is less independent than it looks, and that is worth saying out
2789        // loud once per run rather than leaving it in the config.
2790        let authors: Vec<&str> = self
2791            .roles
2792            .implementers
2793            .iter()
2794            .map(|a| a.id.as_str())
2795            .collect();
2796        let overlap: Vec<String> = self
2797            .roles
2798            .judges
2799            .iter()
2800            .enumerate()
2801            .filter(|(_, j)| authors.contains(&j.id.as_str()))
2802            .map(|(i, j)| format!("judge {} = {}", i + 1, j.id))
2803            .collect();
2804        if !overlap.is_empty() {
2805            let note = format!(
2806                "{} also authored a candidate; blind, but the panel is less \
2807                 independent than {} distinct agents would be",
2808                overlap.join(", "),
2809                self.roles.judges.len()
2810            );
2811            self.state.event("prep", note);
2812        }
2813
2814        self.state.event(
2815            "prep",
2816            format!(
2817                "{} candidates, {} judges, base {} ({})",
2818                self.state.candidates.len(),
2819                self.roles.judges.len(),
2820                &self.state.base_commit[..7.min(self.state.base_commit.len())],
2821                self.state.base_branch
2822            ),
2823        );
2824        self.state.prep_complete = Some(true);
2825        self.state.status = RunStatus::Implementing;
2826        self.state.save()?;
2827        Ok(())
2828    }
2829
2830    // -------------------------------------------------------------- advise
2831
2832    /// The design-deliberation stage: independent, read-only advisor seats
2833    /// each sketch a design before any implementer touches the repository,
2834    /// and (when at least one produced a usable proposal) a synthesis seat
2835    /// blends them into a brief `implement` carries in every candidate's
2836    /// prompt.
2837    ///
2838    /// `[graph] advise` is the on/off switch, on by default; `[graph]
2839    /// advisors` is the proposal count. Everything here is best-effort and
2840    /// non-fatal to the run: a misconfigured `[roles] advisors`, a roster
2841    /// that cannot reach quota, or a synthesis seat that produced nothing
2842    /// usable all leave `implement` exactly as it was before this stage
2843    /// existed — the task instruction alone — rather than failing the whole
2844    /// competition over an enrichment stage. Every outcome is still recorded
2845    /// as an event, so a run that got nothing from this stage says why.
2846    ///
2847    /// [`RunState::advise_attempted`] is this node's idempotency marker, the
2848    /// same role [`RunState::judge_skipped`] plays for `judge`: without it a
2849    /// resumed run whose stage failed would re-run it, and re-spend the
2850    /// agent calls, on every reentry before `implement`.
2851    ///
2852    /// Also skipped once any candidate shows implementation progress — the
2853    /// exact predicate `implement` itself uses to decide a candidate is no
2854    /// longer "todo" (see its own `todo` filter). `advise_attempted` alone
2855    /// is not enough: a run created by an older binary that predates this
2856    /// field deserializes it as `false` (`#[serde(default)]`), so resuming
2857    /// an already-`Implementing`-or-later run under this build would
2858    /// otherwise walk straight back through `prep` (a no-op once candidates
2859    /// exist) into this node and spawn every advisor seat against worktrees
2860    /// `prep` never recreated — after implementation has already started,
2861    /// which is exactly the invariant this stage exists to guarantee.
2862    async fn advise(&mut self) -> Result<()> {
2863        let implement_untouched = self
2864            .state
2865            .candidates
2866            .iter()
2867            .all(|c| c.commits == 0 && c.failed.is_none() && !c.empty);
2868        if !self.state.config.graph.advise || self.state.advise_attempted {
2869            return Ok(());
2870        }
2871        if !implement_untouched {
2872            self.state.event(
2873                "advise",
2874                "skipping the design-deliberation stage: at least one \
2875                 candidate already shows implementation progress, so this \
2876                 run is past the point the stage exists to run before"
2877                    .to_owned(),
2878            );
2879            self.state.advise_attempted = true;
2880            self.state.save()?;
2881            return Ok(());
2882        }
2883        let run_id = self.state.id.clone();
2884        let prompts = self.state.config.prompts.clone();
2885        let instruction = self.state.instruction.clone();
2886        let language = self.state.config.graph.language.clone();
2887        let root = self.state.worktree_root();
2888        let n = self.state.config.graph.advisors;
2889        let where_recorded = self.state.dir().join("run.json");
2890
2891        let seats = match self.state.config.advisors() {
2892            Ok(seats) if !seats.is_empty() => seats,
2893            Ok(_) => {
2894                self.state.event(
2895                    "advise",
2896                    format!(
2897                        "[graph] advisors is 0; skipping the design-deliberation \
2898                         stage and continuing without a synthesis brief (see {})",
2899                        where_recorded.display()
2900                    ),
2901                );
2902                self.state.advise_attempted = true;
2903                self.state.save()?;
2904                return Ok(());
2905            }
2906            Err(e) => {
2907                self.state.event(
2908                    "advise",
2909                    format!(
2910                        "could not resolve advisor seats ({e:#}); continuing \
2911                         without a design-deliberation brief (see {})",
2912                        where_recorded.display()
2913                    ),
2914                );
2915                self.state.advise_attempted = true;
2916                self.state.save()?;
2917                return Ok(());
2918            }
2919        };
2920
2921        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
2922        let artifacts = agent::artifacts_dir(&self.state.dir());
2923        let worktrees: Vec<PathBuf> = (1..=n).map(|k| root.join(format!("advisor-{k}"))).collect();
2924
2925        let mut jobs = Vec::new();
2926        for (i, spec) in seats.iter().cloned().enumerate() {
2927            let seat_key = format!("advisor-{}", i + 1);
2928            let seat = self.seat(&seat_key, &spec.id);
2929            jobs.push(SeatJob {
2930                prompt: prompt::advisor(&instruction, i + 1, seats.len(), &language),
2931                spec,
2932                seat,
2933                cwd: worktrees[i % worktrees.len()].clone(),
2934                timeout,
2935                allow_write: false,
2936                sessions: false,
2937                artifacts: artifacts.clone(),
2938                stem: seat_key,
2939                handover: None,
2940            });
2941        }
2942
2943        self.state.event(
2944            "advise",
2945            format!(
2946                "{} advisor seat(s) sketching a design in parallel",
2947                jobs.len()
2948            ),
2949        );
2950        let mut quota_losses = Vec::new();
2951        let cache = self.state.config.cache_dir();
2952        let ctx = WaveCtx {
2953            carry_seats: false,
2954            pauses: Some((&self.pause, &self.interrupt)),
2955            run: &run_id,
2956            node: "advise",
2957            prompts: &prompts,
2958            cache: cache.as_deref(),
2959            round: None,
2960        };
2961        let advisor_roster = self.state.config.advisor_roster().unwrap_or_default();
2962        let results = ask_json_wave::<Proposal>(
2963            jobs,
2964            Arc::clone(&self.sem),
2965            self.state.config.graph.retries,
2966            &advisor_roster,
2967            &ctx,
2968            &mut quota_losses,
2969            &mut self.state,
2970            &|p: &Proposal| p.validate(),
2971        )
2972        .await;
2973        if self.state.resource_block.is_some() {
2974            return self.stop_for_resource();
2975        }
2976        self.state.quota.extend(quota_losses);
2977
2978        let mut records = Vec::with_capacity(results.len());
2979        for (i, (seat, res, _attempts)) in results.into_iter().enumerate() {
2980            let agent_id = seat.agent.clone();
2981            self.state.seats.insert(seat.key.clone(), seat);
2982            match res {
2983                Ok((proposal, out)) => {
2984                    self.state
2985                        .event("advise", format!("advisor-{} proposed a design", i + 1));
2986                    records.push(advise::AdvisorRecord::proposed(
2987                        i + 1,
2988                        agent_id,
2989                        proposal,
2990                        out.duration_ms,
2991                    ));
2992                }
2993                Err(e) => {
2994                    self.state.event(
2995                        "advise",
2996                        format!("advisor-{} produced no usable proposal: {e:#}", i + 1),
2997                    );
2998                    records.push(advise::AdvisorRecord::failed(
2999                        i + 1,
3000                        agent_id,
3001                        e.to_string(),
3002                    ));
3003                }
3004            }
3005        }
3006
3007        let mut advice = advise::Advice {
3008            records,
3009            synthesis: None,
3010        };
3011        if advice.proposals().is_empty() {
3012            self.state.event(
3013                "advise",
3014                "no advisor produced a usable proposal; continuing without a \
3015                 synthesis brief"
3016                    .to_owned(),
3017            );
3018        } else {
3019            match self
3020                .synthesize_brief(
3021                    &advice,
3022                    &instruction,
3023                    &language,
3024                    &worktrees[0],
3025                    &artifacts,
3026                    &run_id,
3027                    &prompts,
3028                    cache.as_deref(),
3029                )
3030                .await
3031            {
3032                Ok(Some(text)) => {
3033                    self.state.event(
3034                        "advise",
3035                        "synthesized a design brief for the implementer".to_owned(),
3036                    );
3037                    advice.synthesis = Some(text);
3038                }
3039                Ok(None) => {
3040                    self.state.event(
3041                        "advise",
3042                        "the synthesis seat produced nothing usable; continuing \
3043                         without a design brief"
3044                            .to_owned(),
3045                    );
3046                }
3047                Err(e) => {
3048                    if e.is::<crate::repo_lock::ResourceBlocked>() {
3049                        return Err(e);
3050                    }
3051                    self.state.event(
3052                        "advise",
3053                        format!("could not synthesize a design brief: {e:#}"),
3054                    );
3055                }
3056            }
3057        }
3058        advise::apply_reflection(&mut advice);
3059
3060        self.state.advice = Some(advice);
3061        self.state.advise_attempted = true;
3062        self.state.save()?;
3063        Ok(())
3064    }
3065
3066    /// The synthesis seat: reads every advisor's proposal and blends them
3067    /// into the design brief `advise` stores on [`RunState::advice`]. Split
3068    /// out of [`Runner::advise`] only for readability — it is not called
3069    /// anywhere else.
3070    ///
3071    /// Picked the same way [`crate::talk`]'s standing conversation and
3072    /// [`crate::bump`]'s release-bump decision are: [`agent::pick`], with
3073    /// `[roles] synthesizer` checked first and [`agent::pick`]'s own default
3074    /// order (a claude seat, else the first runnable agent in roster order)
3075    /// used when that field is unset — see `[roles] synthesizer`'s own doc
3076    /// in [`crate::config`] for why a dedicated field exists here at all.
3077    #[allow(clippy::too_many_arguments)]
3078    async fn synthesize_brief(
3079        &mut self,
3080        advice: &advise::Advice,
3081        instruction: &str,
3082        language: &str,
3083        cwd: &Path,
3084        artifacts: &Path,
3085        run_id: &str,
3086        prompts: &Prompts,
3087        cache: Option<&Path>,
3088    ) -> Result<Option<String>> {
3089        let chain = agent::pick_chain(
3090            &self.state.config.agents,
3091            self.state.config.roles.synthesizer.as_ref(),
3092            &agent::installed,
3093            "synthesizer",
3094        )?;
3095        let proposals = advice.proposals();
3096        let mut prompt = prompt::with_overlay(
3097            prompt::synthesize_brief(instruction, &proposals, language),
3098            prompts.overlay("advise"),
3099        );
3100        if cache.is_some() {
3101            // This seat never writes, so it is never handed `CARGO_TARGET_DIR`
3102            // below — see `prompt::build_cache_note`'s doc for why telling a
3103            // read-only seat to build through the shared cache is exactly how
3104            // a sandbox's write refusal gets misread as a defect.
3105            prompt.push('\n');
3106            prompt.push_str(&prompt::build_cache_note("advise", false));
3107        }
3108        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
3109        // Each id is tried once, in order; a quota hit, error or unusable
3110        // answer moves to the next. The seat is single-turn (`sessions:
3111        // false`) and the prompt is the whole context, so a fallback agent
3112        // needs nothing carried over.
3113        let mut last = None;
3114        for (n, spec) in chain.iter().enumerate() {
3115            if n > 0 {
3116                self.state
3117                    .event("advise", format!("synthesis falling back to {}", spec.id));
3118            }
3119            let mut seat = self.seat("advise-synthesis", &spec.id);
3120            let wait = self.repository_wait();
3121            let outcome = wait
3122                .scope(agent::invoke(
3123                    spec,
3124                    &mut seat,
3125                    &Invocation {
3126                        coordination: self.state.config.coordination.as_ref(),
3127                        fetched_base: None,
3128                        cwd,
3129                        prompt: &prompt,
3130                        timeout,
3131                        allow_write: false,
3132                        sessions: false,
3133                        artifacts,
3134                        stem: &if n == 0 {
3135                            "advise-synthesis".to_owned()
3136                        } else {
3137                            format!("advise-synthesis-{}", spec.id)
3138                        },
3139                        run: run_id,
3140                        node: "advise",
3141                        cache_dir: None,
3142                        attachments: &[],
3143                        writable: &[],
3144                    },
3145                ))
3146                .await;
3147            if outcome.is_ok() {
3148                self.state.seats.insert(seat.key.clone(), seat);
3149            }
3150            let advance = agent::chain_advances(&outcome);
3151            last = Some(outcome);
3152            if !advance {
3153                break;
3154            }
3155        }
3156        // Exhausted: the last attempt's result is what a single failed seat
3157        // would have produced.
3158        let out = last.expect("a chain holds at least one agent")?;
3159        if !out.usable() {
3160            return Ok(None);
3161        }
3162        let text =
3163            verdict::section(&out.text, "synthesis").unwrap_or_else(|| out.text.trim().to_owned());
3164        Ok((!text.trim().is_empty()).then_some(text))
3165    }
3166
3167    // ----------------------------------------------------------- implement
3168
3169    async fn implement(&mut self) -> Result<()> {
3170        self.persist_candidates().await?;
3171        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
3172        // agent files with `magi task add` name the run that paid for it. The
3173        // prompt overlay is cloned alongside it because the waves borrow it
3174        // while `self` is mutably borrowed by the node's own bookkeeping.
3175        let run_id = self.state.id.clone();
3176        let prompts = self.state.config.prompts.clone();
3177        let todo: Vec<usize> = self
3178            .state
3179            .candidates
3180            .iter()
3181            .enumerate()
3182            .filter(|(_, c)| {
3183                (c.commits == 0 || self.state.interrupted_implementations.contains(&c.label))
3184                    && c.failed.is_none()
3185                    && !c.empty
3186            })
3187            .map(|(i, _)| i)
3188            .collect();
3189        if todo.is_empty() {
3190            return self.after_implement();
3191        }
3192        self.state.status = RunStatus::Implementing;
3193
3194        let language = self.state.config.graph.language.clone();
3195        let github_language = self.state.config.graph.github_language.clone();
3196        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
3197        let sessions = self.state.config.graph.sessions;
3198        let artifacts = agent::artifacts_dir(&self.state.dir());
3199        // The design-deliberation stage's blended brief, when `advise` found
3200        // one — carried into every implementer's prompt the same way
3201        // regardless of which candidate it is.
3202        let brief = self
3203            .state
3204            .advice
3205            .as_ref()
3206            .and_then(|a| a.synthesis.as_deref())
3207            .map(str::to_owned);
3208        let attachments = self.state.attachments.clone();
3209
3210        let mut jobs = Vec::new();
3211        for &i in &todo {
3212            let (index, label, worktree) = {
3213                let c = &self.state.candidates[i];
3214                (c.index, c.label, c.worktree.clone())
3215            };
3216            let spec = self.roles.implementers[index].clone();
3217            let seat_key = format!("impl-{label}");
3218            let seat = self.seat(&seat_key, &spec.id);
3219            let instruction = seeded_instruction(&self.state);
3220            jobs.push(SeatJob {
3221                spec,
3222                seat,
3223                prompt: prompt::implement_in(
3224                    &instruction,
3225                    &worktree.to_string_lossy(),
3226                    &language,
3227                    &github_language,
3228                    brief.as_deref(),
3229                    &attachments,
3230                ),
3231                cwd: worktree,
3232                timeout,
3233                allow_write: true,
3234                sessions,
3235                artifacts: artifacts.clone(),
3236                stem: format!("impl-{label}"),
3237                handover: None,
3238            });
3239        }
3240
3241        self.state.event(
3242            "implement",
3243            format!("{} candidates in parallel", jobs.len()),
3244        );
3245        // Kept so a seat whose CLI hung up can be asked again from the same
3246        // job: `wave` consumes what it is given. Mutable so `resume_seat_handovers`
3247        // can update a seat's own entry once a fallback agent takes it over —
3248        // `resume_unconfirmed_commands`, which reads `sent` afterward, must see
3249        // whichever agent actually answered, not the one that quota'd out.
3250        let mut sent = jobs.clone();
3251        let cache = self.state.config.cache_dir();
3252        let ctx = WaveCtx {
3253            carry_seats: false,
3254            pauses: Some((&self.pause, &self.interrupt)),
3255            run: &run_id,
3256            node: "implement",
3257            prompts: &prompts,
3258            cache: cache.as_deref(),
3259            round: None,
3260        };
3261        let mut results = wave(jobs, Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
3262        if !wave_blocked(&results) {
3263            self.resume_undelivered(&mut results, &sent, &prompts, &run_id)
3264                .await;
3265            self.resume_seat_handovers(&mut results, &mut sent, &prompts, &run_id)
3266                .await?;
3267            self.resume_unconfirmed_commands(&mut results, &sent, &prompts, &run_id)
3268                .await;
3269        }
3270        // Do not finalize failed candidates when the entire wave needs machine
3271        // recovery: leaving them pending resumes this node with its work intact.
3272        if !results.is_empty()
3273            && results
3274                .iter()
3275                .all(|(_, _, out)| matches!(out, AgentOutcome::Quota(_)))
3276        {
3277            let losses: Vec<_> = results
3278                .iter()
3279                .map(|(_, seat, out)| {
3280                    let AgentOutcome::Quota(o) = out else {
3281                        unreachable!()
3282                    };
3283                    QuotaLoss::from_report(seat.key.clone(), "implement", o.quota.as_ref())
3284                })
3285                .collect();
3286            self.state.quota.extend(losses.clone());
3287            for (_, seat, _) in results {
3288                self.state.seats.insert(seat.key.clone(), seat);
3289            }
3290            for &i in &todo {
3291                let label = self.state.candidates[i].label;
3292                self.state.interrupted_implementations.insert(label);
3293                self.state
3294                    .candidate_preservation
3295                    .insert(label, "machine outage awaiting persistence".into());
3296            }
3297            // Preserve partial edits too, while keeping every interrupted seat
3298            // pending even when its tree already contains an inherited patch.
3299            block_machine_outage(&mut self.state, "implement", &losses);
3300            self.state.save()?;
3301            self.persist_candidates().await?;
3302            for &i in &todo {
3303                self.state
3304                    .interrupted_implementations
3305                    .insert(self.state.candidates[i].label);
3306            }
3307            return self.stop_for_resource();
3308        }
3309        let resource_blocked = self.state.resource_block.is_some() || wave_blocked(&results);
3310
3311        let selected_failed = self.state.config.graph.selected_implementer.is_some()
3312            && results
3313                .iter()
3314                .any(|(_, _, out)| FailClass::of(out).is_some());
3315        for (&i, (_wi, seat, out)) in todo.iter().zip(results) {
3316            if matches!(out, AgentOutcome::ResourceBlocked(_)) {
3317                // Executed turns interrupted by disk pressure already carry
3318                // a preservation barrier from wave. Admission-only waits do
3319                // not. Keep the interrupted seat's session for recovery too.
3320                if self
3321                    .state
3322                    .candidate_preservation
3323                    .contains_key(&self.state.candidates[i].label)
3324                {
3325                    self.state.seats.insert(seat.key.clone(), seat);
3326                }
3327                continue;
3328            }
3329            let seat_key = seat.key.clone();
3330            // A quota fallback (`resume_seat_handovers`) may have handed this
3331            // seat to a different agent than the one `prep` recorded on the
3332            // candidate; the stats tables and any later fixer-defaults-to-
3333            // winner's-author lookup must credit whoever actually answered —
3334            // unless every fallback also quota'd out, in which case nobody
3335            // actually answered and crediting the last agent tried would
3336            // erase every earlier agent's own quota loss from the stats
3337            // tables instead of just this one seat's.
3338            let agent = seat.agent.clone();
3339            let exhausted_the_fallback_chain = FailClass::of(&out).is_some();
3340            self.state.seats.insert(seat.key.clone(), seat);
3341            let label = self.state.candidates[i].label;
3342            self.state.interrupted_implementations.remove(&label);
3343
3344            let (summary, duration, failed, verified_claim) = match out {
3345                AgentOutcome::Ok(o) => {
3346                    let text = verdict::section(&o.text, "summary").unwrap_or(o.text.clone());
3347                    let failed = (!o.usable()).then(|| {
3348                        if o.timed_out {
3349                            "agent timed out".to_owned()
3350                        } else {
3351                            format!(
3352                                "agent exited with {}",
3353                                crate::notices::exit_status(o.exit_code)
3354                            )
3355                        }
3356                    });
3357                    let verified_claim = verified_noop_claim(failed.is_none(), &o.commands, &text);
3358                    (text, o.duration_ms, failed, verified_claim)
3359                }
3360                // Left un-resumed by `resume_undelivered` (a dirty tree
3361                // already rescues the work, or there was no session left to
3362                // resume into) — reported like the ordinary failure it is,
3363                // never as if `o.text` (the CLI's raw error JSON) were an
3364                // answer.
3365                AgentOutcome::Dropped(o) => {
3366                    let why = o
3367                        .dropped
3368                        .as_ref()
3369                        .map(|d| d.why.as_str())
3370                        .unwrap_or("the CLI ended the stream without delivering its answer");
3371                    (
3372                        String::new(),
3373                        o.duration_ms,
3374                        Some(format!("the CLI dropped the stream ({why})")),
3375                        None,
3376                    )
3377                }
3378                AgentOutcome::Quota(o) => {
3379                    self.state.quota.push(QuotaLoss::from_report(
3380                        seat_key,
3381                        "implement",
3382                        o.quota.as_ref(),
3383                    ));
3384                    (
3385                        String::new(),
3386                        o.duration_ms,
3387                        Some("rate limited (quota); produced no change".to_owned()),
3388                        None,
3389                    )
3390                }
3391                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
3392                    (String::new(), 0, Some(e), None)
3393                }
3394            };
3395
3396            // Save every completed turn before any fallible Git operation. A failed
3397            // rescue must not erase the reply or prevent collection of other seats.
3398            let c = &mut self.state.candidates[i];
3399            if !exhausted_the_fallback_chain {
3400                c.agent = agent;
3401            }
3402            c.summary = blind::sanitize_prose(&summary, &self.state.config.blind);
3403            c.duration_ms = duration;
3404            c.failed = failed;
3405            c.verified_noop = verified_claim;
3406            self.state
3407                .candidate_preservation
3408                .insert(label, "awaiting persistence".to_owned());
3409        }
3410        self.state.save()?;
3411        self.persist_candidates().await?;
3412
3413        if resource_blocked {
3414            return self.stop_for_resource();
3415        }
3416        if selected_failed {
3417            self.state.status = RunStatus::Blocked;
3418            self.state.event("implement", "selected implementer failed or hit quota; holding without fallback, review or publication");
3419            self.state.save()?;
3420            bail!(
3421                "selected implementer unavailable or quota-limited; restore availability and explicitly release the task"
3422            );
3423        }
3424        self.after_implement()
3425    }
3426
3427    /// Retry only persistence after a completed implementation turn.
3428    async fn persist_candidates(&mut self) -> Result<()> {
3429        let labels: Vec<_> = self.state.candidate_preservation.keys().copied().collect();
3430        for label in labels {
3431            let i = self
3432                .state
3433                .candidates
3434                .iter()
3435                .position(|c| c.label == label)
3436                .context("pending candidate is missing")?;
3437            let c = self.state.candidates[i].clone();
3438            let interrupted = self.state.interrupted_implementations.contains(&label);
3439            let result = async {
3440                let wait = crate::repo_lock::WaitPolicy::new(
3441                    Duration::from_secs(self.state.config.graph.timeout_resource_wait),
3442                    || false,
3443                );
3444                let _coordination =
3445                    coordinate_operation(&mut self.state, &c.worktree, &wait).await?;
3446                // Best effort evidence requires no index writes. A successful snapshot
3447                // never authorizes removal of a tree whose rescue failed.
3448                if let Err(e) = git::snapshot_uncommitted(
3449                    &c.worktree,
3450                    &self
3451                        .state
3452                        .dir()
3453                        .join("artifacts")
3454                        .join(format!("candidate-{label}-recovery")),
3455                )
3456                .await
3457                {
3458                    self.state.event(
3459                        "preserve",
3460                        format!("candidate {label} snapshot incomplete: {e:#}"),
3461                    );
3462                }
3463                let rescued = git::rescue_commit(
3464                    &c.worktree,
3465                    &format!("magi: candidate {label} (uncommitted work)"),
3466                )
3467                .await?;
3468                self.state.note_withheld("implement", &rescued.withheld);
3469                let base = &self.state.base_commit;
3470                let commits = git::commits_ahead(&c.worktree, base, "HEAD").await?;
3471                let patch = git::diff(&c.worktree, base, "HEAD").await?;
3472                let stat = git::diff_stat(&c.worktree, base, "HEAD").await?;
3473                let files = git::changed_files(&c.worktree, base, "HEAD").await?.len();
3474                write_artifact(&self.state, &format!("cand-{label}.patch"), &patch)?;
3475                if c.empty && commits > 0 && !patch.trim().is_empty()
3476                    && (self.state.judge_skipped || !self.state.judgements.is_empty()
3477                        || !self.state.deliberation.is_empty() || !self.state.votes.is_empty()
3478                        || self.state.tally.is_some())
3479                {
3480                    // Keep the old classification and pending marker so every
3481                    // retry stops too. Retain decisions as recovery evidence;
3482                    // only a supported recovery operation may replace them.
3483                    bail!("candidate {label} changes the judged candidate set; supported recovery and fresh judging are required before continuing");
3484                }
3485                let c = &mut self.state.candidates[i];
3486                c.commits = commits;
3487                c.stat = stat;
3488                c.files = files;
3489                let no_changes = commits == 0 || patch.trim().is_empty();
3490                c.empty = no_changes && !interrupted;
3491                if interrupted && no_changes {
3492                    c.failed = None;
3493                    c.verified_noop = None;
3494                }
3495                if !c.empty {
3496                    c.failed = None;
3497                    c.verified_noop = None;
3498                }
3499                self.state.event(
3500                    "preserve",
3501                    format!("candidate {label}: {files} files, {commits} commits"),
3502                );
3503                Ok::<_, anyhow::Error>(())
3504            }
3505            .await;
3506            match result {
3507                Ok(()) => {
3508                    self.state.candidate_preservation.remove(&label);
3509                    if !interrupted || self.state.candidates[i].files > 0 {
3510                        self.state.interrupted_implementations.remove(&label);
3511                    }
3512                }
3513                Err(e) => {
3514                    let reason = format!("candidate {label} preservation failed: {e:#}");
3515                    self.state.event("preserve", &reason);
3516                    self.state.candidate_preservation.insert(label, reason);
3517                }
3518            }
3519            if self.state.candidate_preservation.is_empty()
3520                && self.state.status == RunStatus::Blocked
3521                && self.state.candidates.iter().all(|c| c.failed.is_none())
3522            {
3523                // Persist the recovered phase with the cleared pending marker;
3524                // a crash between saves must not turn this into a selected-seat
3525                // failure hold on the next resume.
3526                self.state.status = RunStatus::Implementing;
3527                self.state.event(
3528                    "preserve",
3529                    "candidate persistence recovered; implementation can continue",
3530                );
3531            }
3532            self.state.save()?;
3533        }
3534        if !self.state.candidate_preservation.is_empty() {
3535            self.state.status = RunStatus::Blocked;
3536            self.state.save()?;
3537            bail!(
3538                "candidate preservation incomplete; retain worktrees and artifacts, repair persistence and resume this run"
3539            );
3540        }
3541        Ok(())
3542    }
3543
3544    /// Ask again, once, for work a CLI did and then failed to hand over.
3545    ///
3546    /// [`agent::dropped_stream`] recognises the one shape observed: an error
3547    /// status with an empty response and a usage report showing output tokens,
3548    /// i.e. **billed work with nothing delivered**. Run 26c7's candidate B was
3549    /// seven minutes and 14,267 output tokens that arrived as an empty
3550    /// candidate, because `agy`'s own subscriber fell behind and hung up.
3551    ///
3552    /// Two conditions, and both matter:
3553    ///
3554    /// - **Only when the tree is untouched.** Often the agent has already
3555    ///   written its files and only the closing message was lost; the rescue
3556    ///   commit below picks that up and there is nothing to ask for. Re-asking
3557    ///   then would pay for a second implementation of work already on disk.
3558    /// - **Once.** A CLI that drops one stream can drop the next, and this
3559    ///   node is the most expensive in the graph.
3560    ///
3561    /// The re-ask is a resume, not a re-run: `has_context` is true because the
3562    /// dropped reply still carried its `conversation_id`, so the seat is asked
3563    /// to finish what it was doing rather than sent the whole task again. It
3564    /// therefore gets a nudge's budget ([`retry_budget`]) - a quarter of the
3565    /// node's - for the same reason a re-ranked judge does: restating finished
3566    /// work is not the work.
3567    ///
3568    /// Unlike a quota this is worth retrying at all: a rate limit fails the
3569    /// same way until it resets, while an abandoned conversation is still
3570    /// there to be picked up.
3571    async fn resume_undelivered(
3572        &mut self,
3573        results: &mut [(usize, SeatState, AgentOutcome)],
3574        sent: &[SeatJob],
3575        prompts: &Prompts,
3576        run_id: &str,
3577    ) {
3578        for (wi, seat, out) in results.iter_mut() {
3579            let Some(dropped) = (match &*out {
3580                AgentOutcome::Dropped(o) => o.dropped.clone(),
3581                _ => None,
3582            }) else {
3583                continue;
3584            };
3585            let Some(job) = sent.get(*wi) else { continue };
3586            // Already on disk? Then only the closing message was lost.
3587            if !git::is_clean(&job.cwd).await.unwrap_or(true) {
3588                self.state.event(
3589                    "implement",
3590                    format!(
3591                        "{}: the CLI dropped the stream after {} output tokens ({}), but the \
3592                         work is in the tree",
3593                        seat.key, dropped.output_tokens, dropped.why
3594                    ),
3595                );
3596                continue;
3597            }
3598            // The re-ask only makes sense as a resume: `resume_after_drop`
3599            // says nothing about the task, trusting the seat to still hold it.
3600            // Without a session to resume — sessions disabled, or this CLI's
3601            // drop shape happened not to carry a session id — that prompt
3602            // would open a brand-new conversation with no context at all,
3603            // which is worse than leaving this as the ordinary failure it
3604            // already is.
3605            if !has_context(&job.spec, seat, job.sessions) {
3606                self.state.event(
3607                    "implement",
3608                    format!(
3609                        "{}: the CLI dropped the stream after {} output tokens ({}), but there \
3610                         is no session left to resume",
3611                        seat.key, dropped.output_tokens, dropped.why
3612                    ),
3613                );
3614                continue;
3615            }
3616            self.state.event(
3617                "implement",
3618                format!(
3619                    "{}: the CLI dropped the stream after {} output tokens ({}); resuming the \
3620                     conversation",
3621                    seat.key, dropped.output_tokens, dropped.why
3622                ),
3623            );
3624            let mut retry = job.clone();
3625            retry.seat = seat.clone();
3626            retry.prompt = prompt::resume_after_drop(&dropped.why);
3627            retry.timeout = retry_budget(job.timeout, true);
3628            retry.stem = format!("{}-resume", job.stem);
3629            let cache = self.state.config.cache_dir();
3630            let ctx = WaveCtx {
3631                carry_seats: false,
3632                pauses: Some((&self.pause, &self.interrupt)),
3633                run: run_id,
3634                node: "implement",
3635                prompts,
3636                cache: cache.as_deref(),
3637                round: None,
3638            };
3639            let (resumed_seat, resumed) =
3640                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
3641            *seat = resumed_seat;
3642            *out = resumed;
3643        }
3644    }
3645
3646    /// Fall an implement seat through to the next untried agent in the
3647    /// implementer roster when it lost to quota — or, since the handover was
3648    /// generalised, to a timeout or an ordinary failure (see [`FailClass`] and
3649    /// [`should_hand_over`] for when a non-quota failure stops the chain), the
3650    /// quota path itself being unchanged — instead of leaving the
3651    /// seat's loss final the moment one agent's account runs dry.
3652    ///
3653    /// Solo runs (`graph.implementers = 1`, `daemon::apply_solo`'s forced shape)
3654    /// are the motivating case: `Config::resolve_roles`'s `implementers`
3655    /// truncates to the single slot rotation picked, so a solo task whose one
3656    /// implementer hits quota mid-run used to have nothing else to try. This
3657    /// walks [`ResolvedRoles::implementer_roster`] instead — the untruncated,
3658    /// unrotated roster — which is the only place the *other* candidates in
3659    /// the machine's roster still exist once `implementers` has been cut down
3660    /// to size.
3661    ///
3662    /// Walks forward from just past the seat's own original position in the
3663    /// roster, never wrapping back to the front: a later candidate slot (say
3664    /// `beta`, the roster's second entry) must fall through to the *next*
3665    /// entry (`gamma`) on its own quota loss, not back to `alpha`, which is
3666    /// almost certainly a different candidate's own agent already — and once
3667    /// the roster's tail is exhausted there is nothing left to fall through
3668    /// to for *this* seat, wrapping or not. Tried by `spec.id`, never the
3669    /// whole [`AgentSpec`]: a roster with the same id named twice must not
3670    /// let this retry that id forever. The loop keeps falling through until
3671    /// an attempt lands something other than `Quota` or the roster's tail
3672    /// runs out of untried ids, at which point the seat is left exactly as
3673    /// `implement`'s own `AgentOutcome::Quota` arm already handles it: one
3674    /// `QuotaLoss` recorded, the candidate failed/empty.
3675    ///
3676    /// `sent` is taken mutably and updated with the fallback agent's spec:
3677    /// `resume_unconfirmed_commands`, which runs after this and also reads
3678    /// `sent`, must see whichever agent actually ended up answering the seat
3679    /// — reading the stale, original spec there would check session
3680    /// eligibility against the wrong CLI and could hand a fallback agent's
3681    /// session id to the agent that just lost the seat to quota.
3682    ///
3683    /// Every fallback gets a fresh [`SeatState`], never the quota'd seat's own
3684    /// — `self.seat` only reuses state when the agent id is unchanged, so
3685    /// handing it a different id already gets this for free. Reusing the old
3686    /// seat would resume a different CLI's session as if it were a
3687    /// continuation of this one.
3688    ///
3689    /// Unlike [`Runner::resume_undelivered`], not gated on a clean worktree:
3690    /// a quota loss cuts an agent off mid-turn, so anything already in the
3691    /// tree is unfinished work, not a completed candidate a re-ask would pay
3692    /// for twice. A dirty tree is rescued into a commit first (the same
3693    /// neutral-identity rescue `implement`'s own outcome loop gives every
3694    /// candidate) so the next agent starts clean.
3695    ///
3696    /// The new agent gets the implementer's full prompt and full
3697    /// `timeout_implement` budget, not `resume_after_drop`'s nudge-sized one:
3698    /// it has no session and no context, and is implementing the task from
3699    /// nothing, unlike a resumed drop which is only restating work already
3700    /// done.
3701    ///
3702    /// Every intermediate `Quota` this loop absorbs is folded into a plain
3703    /// `implement` event, never into `self.state.quota` — that is what
3704    /// `daemon.rs`'s own backoff reads to decide a run's task attempt should
3705    /// go unspent, and a seat that ultimately recovered on its second or
3706    /// third agent is not the stalled panel that check exists to catch. Only
3707    /// the final, unrecovered `Quota` (once the roster runs out) ever reaches
3708    /// `self.state.quota`, via the ordinary `AgentOutcome::Quota` arm the
3709    /// outcome loop already has — this helper never pushes to it itself.
3710    async fn resume_seat_handovers(
3711        &mut self,
3712        results: &mut [(usize, SeatState, AgentOutcome)],
3713        sent: &mut [SeatJob],
3714        prompts: &Prompts,
3715        run_id: &str,
3716    ) -> Result<()> {
3717        let instruction = seeded_instruction(&self.state);
3718        let language = self.state.config.graph.language.clone();
3719        let github_language = self.state.config.graph.github_language.clone();
3720        let brief = self
3721            .state
3722            .advice
3723            .as_ref()
3724            .and_then(|a| a.synthesis.as_deref())
3725            .map(str::to_owned);
3726        let attachments = self.state.attachments.clone();
3727        for (wi, seat, out) in results.iter_mut() {
3728            // Who holds the other candidate seats of this wave right now
3729            // (earlier handovers already written back to `sent`).
3730            let others: BTreeSet<String> = sent
3731                .iter()
3732                .enumerate()
3733                .filter(|(j, _)| j != wi)
3734                .map(|(_, j)| j.spec.id.clone())
3735                .collect();
3736            let Some(job) = sent.get_mut(*wi) else {
3737                continue;
3738            };
3739            // Where the seat's own original agent sits in the roster — the
3740            // fallback walk starts just past here, never at the front, so a
3741            // later candidate slot's quota loss does not fall back onto an
3742            // earlier slot's own agent.
3743            let start = self
3744                .roles
3745                .implementer_roster
3746                .iter()
3747                .position(|s| s.id == job.spec.id)
3748                .unwrap_or(0);
3749            let mut tried: BTreeSet<String> = BTreeSet::from([job.spec.id.clone()]);
3750            let mut fallback_attempt = 0usize;
3751            let mut prev: Option<FailClass> = None;
3752            while let Some(cur) = FailClass::of(&*out) {
3753                if !should_hand_over(prev.as_ref(), &cur) {
3754                    break;
3755                }
3756                let Some(next) =
3757                    pick_successor(&self.roles.implementer_roster, start, &tried, None, &others)
3758                        .cloned()
3759                else {
3760                    break;
3761                };
3762                tried.insert(next.id.clone());
3763                fallback_attempt += 1;
3764
3765                let coordination = self.coordinate(&job.cwd).await?;
3766                if let Ok(r) = git::rescue_commit(
3767                    &job.cwd,
3768                    &format!(
3769                        "magi: candidate {} (uncommitted work before {} fallback)",
3770                        seat.key,
3771                        if cur == FailClass::Quota {
3772                            "quota"
3773                        } else {
3774                            "handover"
3775                        }
3776                    ),
3777                )
3778                .await
3779                {
3780                    self.state.note_withheld("implement", &r.withheld);
3781                }
3782                drop(coordination);
3783
3784                record_handover(
3785                    &mut self.state,
3786                    "implement",
3787                    &seat.key,
3788                    &seat.agent,
3789                    &next.id,
3790                    &cur,
3791                    &fail_reason(&*out),
3792                );
3793                prev = Some(cur.clone());
3794
3795                let new_seat = handover_seat(&seat.key, &next.id, self.state.next_seat_seed());
3796                self.state.seats.insert(seat.key.clone(), new_seat.clone());
3797                // Kept in sync on `sent` itself, not just the local retry: a
3798                // later helper (`resume_unconfirmed_commands`) reads `sent`
3799                // after this one returns and must see whichever agent is now
3800                // occupying the seat, not the one that just quota'd out —
3801                // otherwise it would judge session/continuation eligibility
3802                // by the wrong CLI and could resend a fallback's session id
3803                // to the agent that lost it the seat in the first place.
3804                job.spec = next.clone();
3805                let mut retry = job.clone();
3806                retry.seat = new_seat;
3807                retry.prompt = prompt::implement_in(
3808                    &instruction,
3809                    &job.cwd.to_string_lossy(),
3810                    &language,
3811                    &github_language,
3812                    brief.as_deref(),
3813                    &attachments,
3814                );
3815                retry.stem = format!("{}-{}-{}", job.stem, cur.stem_word(), next.id);
3816                let cache = self.state.config.cache_dir();
3817                let ctx = WaveCtx {
3818                    carry_seats: false,
3819                    pauses: Some((&self.pause, &self.interrupt)),
3820                    run: run_id,
3821                    node: "implement",
3822                    prompts,
3823                    cache: cache.as_deref(),
3824                    round: None,
3825                };
3826                let (fallback_seat, fallback_out) = run_one(
3827                    retry,
3828                    Arc::clone(&self.sem),
3829                    &ctx,
3830                    &mut self.state,
3831                    fallback_attempt,
3832                )
3833                .await;
3834                *seat = fallback_seat;
3835                *out = fallback_out;
3836            }
3837        }
3838        Ok(())
3839    }
3840
3841    /// Ask an implement seat's own CLI to confirm what it started, once, when
3842    /// its reply reported a command whose completion status it never
3843    /// confirmed — see [`has_unconfirmed_command`]'s own doc for exactly what
3844    /// that does and does not mean.
3845    ///
3846    /// The completion contract this task asks for, extended to `implement`
3847    /// with the same signal `continue_fix_report` reads for the fixer,
3848    /// rather than a keyword search over the reply or a hard requirement on
3849    /// `## SUMMARY`'s presence — the shape behind fb35, 9566 and e185, where
3850    /// a candidate's CLI turn ended cleanly while a test run it had started
3851    /// had not. A short, ordinary reply with no `## SUMMARY` and no commands
3852    /// named in it at all is untouched by this: `commands` is empty, so
3853    /// there is nothing to be unconfirmed.
3854    ///
3855    /// Unlike `resume_undelivered`, not gated on the tree being untouched:
3856    /// this is not about recovering edits that might already be on disk, it
3857    /// is about a result the seat itself never vouched for, which resuming
3858    /// asks for regardless of what the tree already holds. Bounded to one
3859    /// attempt for the same reason `resume_undelivered` is — this is the
3860    /// most expensive node in the graph — and a seat that still cannot
3861    /// confirm on that attempt is left as whatever its (possibly still
3862    /// unconfirmed) reply says; this does not invent a new "failed" reason
3863    /// for a candidate that otherwise produced a real, committed change.
3864    async fn resume_unconfirmed_commands(
3865        &mut self,
3866        results: &mut [(usize, SeatState, AgentOutcome)],
3867        sent: &[SeatJob],
3868        prompts: &Prompts,
3869        run_id: &str,
3870    ) {
3871        for (wi, seat, out) in results.iter_mut() {
3872            let AgentOutcome::Ok(o) = &*out else {
3873                continue;
3874            };
3875            if !has_unconfirmed_command(&o.commands) {
3876                continue;
3877            }
3878            let Some(job) = sent.get(*wi) else { continue };
3879            if !has_context(&job.spec, seat, job.sessions) {
3880                self.state.event(
3881                    "implement",
3882                    format!(
3883                        "{}: the reply named a command whose own CLI never confirmed the exit \
3884                         status of, but there is no session left to resume",
3885                        seat.key
3886                    ),
3887                );
3888                continue;
3889            }
3890            self.state.event(
3891                "implement",
3892                format!(
3893                    "{}: the reply named a command whose own CLI never confirmed the exit \
3894                     status of; resuming the conversation",
3895                    seat.key
3896                ),
3897            );
3898            let mut retry = job.clone();
3899            retry.seat = seat.clone();
3900            retry.prompt = prompt::resume_incomplete(
3901                "a command in your last reply had no confirmed exit status",
3902            );
3903            retry.timeout = retry_budget(job.timeout, true);
3904            retry.stem = format!("{}-confirm", job.stem);
3905            let cache = self.state.config.cache_dir();
3906            let ctx = WaveCtx {
3907                carry_seats: false,
3908                pauses: Some((&self.pause, &self.interrupt)),
3909                run: run_id,
3910                node: "implement",
3911                prompts,
3912                cache: cache.as_deref(),
3913                round: None,
3914            };
3915            let (resumed_seat, resumed) =
3916                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
3917            *seat = resumed_seat;
3918            *out = resumed;
3919        }
3920    }
3921
3922    /// Ask the fixer's own seat again, up to [`MAX_FIX_CONTINUATIONS`] times,
3923    /// when its CLI turn ended cleanly (`AgentOutcome::Ok`) but the reply held
3924    /// no [`FixReport`] — see [`MAX_FIX_CONTINUATIONS`]'s own doc for the run
3925    /// that motivated this.
3926    ///
3927    /// Not the same gap as an unparsable *shape*, which [`ask_json_wave`]'s
3928    /// own nudge loop already covers for judge/review/vote seats, and not a
3929    /// dropped stream, which [`Runner::resume_undelivered`] covers for
3930    /// implement seats: here the CLI turn genuinely finished while the node's
3931    /// own work — the fixer's account of what it did — had not. Gated purely
3932    /// on `extract_json::<FixReport>` having failed on an otherwise-usable
3933    /// reply, never on any wording in it, so a fixer whose valid, first-try
3934    /// `FixReport` happens to mention having waited on a background test is
3935    /// never resumed — the `Ok(report)` branch at the call site returns
3936    /// before this is ever invoked.
3937    ///
3938    /// Same discipline as `resume_undelivered`: a nudge-sized timeout per
3939    /// attempt ([`retry_budget`]), nothing attempted once the session is
3940    /// gone, and a quota hit ends the loop immediately rather than retrying a
3941    /// rate limit that fails the same way again.
3942    async fn continue_fix_report(
3943        &mut self,
3944        mut seat: SeatState,
3945        parse_err: String,
3946        job: &SeatJob,
3947        prompts: &Prompts,
3948        run_id: &str,
3949        round: usize,
3950    ) -> (
3951        SeatState,
3952        Option<FixReport>,
3953        Option<String>,
3954        ContinuationRecord,
3955    ) {
3956        let mut last_err = parse_err;
3957        let mut cumulative_wait_ms = 0u64;
3958        let mut attempts = 0usize;
3959        loop {
3960            if !has_context(&job.spec, &seat, job.sessions) {
3961                self.state.event(
3962                    "fix",
3963                    format!(
3964                        "round {round}: fixer's reply had no adoption report ({last_err}); no \
3965                         session left to resume into"
3966                    ),
3967                );
3968                let outcome = if attempts == 0 {
3969                    ContinuationOutcome::NoSession
3970                } else {
3971                    ContinuationOutcome::Exhausted
3972                };
3973                return (
3974                    seat,
3975                    None,
3976                    Some(format!("unparsable fix report: {last_err}")),
3977                    ContinuationRecord {
3978                        attempts,
3979                        cumulative_wait_ms,
3980                        outcome,
3981                    },
3982                );
3983            }
3984            if attempts >= MAX_FIX_CONTINUATIONS {
3985                self.state.event(
3986                    "fix",
3987                    format!(
3988                        "round {round}: fixer's reply still had no adoption report after \
3989                         {attempts} continuation(s) ({last_err}); giving up"
3990                    ),
3991                );
3992                return (
3993                    seat,
3994                    None,
3995                    Some(format!(
3996                        "unparsable fix report after {attempts} continuation(s): {last_err}"
3997                    )),
3998                    ContinuationRecord {
3999                        attempts,
4000                        cumulative_wait_ms,
4001                        outcome: ContinuationOutcome::Exhausted,
4002                    },
4003                );
4004            }
4005            attempts += 1;
4006            self.state.event(
4007                "fix",
4008                format!(
4009                    "round {round}: fixer's reply had no adoption report ({last_err}); resuming \
4010                     the conversation (attempt {attempts}/{MAX_FIX_CONTINUATIONS})"
4011                ),
4012            );
4013            let mut retry = job.clone();
4014            retry.seat = seat.clone();
4015            retry.prompt = prompt::resume_incomplete(&last_err);
4016            retry.timeout = retry_budget(job.timeout, true);
4017            retry.stem = format!("{}-continue{attempts}", job.stem);
4018            let cache = self.state.config.cache_dir();
4019            let ctx = WaveCtx {
4020                carry_seats: false,
4021                pauses: Some((&self.pause, &self.interrupt)),
4022                run: run_id,
4023                node: "fix",
4024                prompts,
4025                cache: cache.as_deref(),
4026                round: Some(round),
4027            };
4028            let (resumed_seat, resumed_out) = run_one(
4029                retry,
4030                Arc::clone(&self.sem),
4031                &ctx,
4032                &mut self.state,
4033                attempts,
4034            )
4035            .await;
4036            seat = resumed_seat;
4037            match resumed_out {
4038                AgentOutcome::Ok(o) => {
4039                    cumulative_wait_ms += o.duration_ms;
4040                    match verdict::extract_json::<FixReport>(&o.text) {
4041                        Ok(report) if !has_unconfirmed_command(&o.commands) => {
4042                            self.state.event(
4043                                "fix",
4044                                format!(
4045                                    "round {round}: fixer's adoption report recovered after \
4046                                     {attempts} continuation(s)"
4047                                ),
4048                            );
4049                            return (
4050                                seat,
4051                                Some(report),
4052                                None,
4053                                ContinuationRecord {
4054                                    attempts,
4055                                    cumulative_wait_ms,
4056                                    outcome: ContinuationOutcome::Resumed,
4057                                },
4058                            );
4059                        }
4060                        // The report parsed, but this same reply's own
4061                        // CommandEvidence — the identical record `state.jobs`
4062                        // renders — names a command whose CLI never
4063                        // confirmed an exit status. Read together, that is
4064                        // not a resolved answer: keep nudging rather than
4065                        // accept a report standing next to a command the
4066                        // seat's own CLI cannot vouch for.
4067                        Ok(_) => {
4068                            last_err = "the reply parsed, but it reported a command whose own CLI \
4069                                 never confirmed an exit status"
4070                                .to_owned();
4071                        }
4072                        Err(e) => last_err = e.to_string(),
4073                    }
4074                }
4075                AgentOutcome::Quota(o) => {
4076                    cumulative_wait_ms += o.duration_ms;
4077                    let loss = QuotaLoss::from_report(seat.key.clone(), "fix", o.quota.as_ref());
4078                    block_machine_outage(&mut self.state, "fix", std::slice::from_ref(&loss));
4079                    self.state.quota.push(loss);
4080                    self.state.event(
4081                        "fix",
4082                        format!(
4083                            "round {round}: continuation rate limited (quota); not retrying now"
4084                        ),
4085                    );
4086                    return (
4087                        seat,
4088                        None,
4089                        Some("rate limited (quota) while recovering the fix report".to_owned()),
4090                        ContinuationRecord {
4091                            attempts,
4092                            cumulative_wait_ms,
4093                            outcome: ContinuationOutcome::QuotaLost,
4094                        },
4095                    );
4096                }
4097                AgentOutcome::Dropped(o) => {
4098                    cumulative_wait_ms += o.duration_ms;
4099                    let why = o
4100                        .dropped
4101                        .as_ref()
4102                        .map(|d| d.why.as_str())
4103                        .unwrap_or("the CLI ended the stream without delivering its answer");
4104                    last_err = format!("the CLI dropped the stream ({why})");
4105                }
4106                AgentOutcome::Failed(e) => last_err = e,
4107                // The continuation was never started; the report stays lost
4108                // and the caller records that, without any handover.
4109                AgentOutcome::ResourceBlocked(e) => {
4110                    return (
4111                        seat,
4112                        None,
4113                        Some(format!("the continuation was not started: {e}")),
4114                        ContinuationRecord {
4115                            attempts: attempts.saturating_sub(1),
4116                            cumulative_wait_ms,
4117                            outcome: ContinuationOutcome::NoSession,
4118                        },
4119                    );
4120                }
4121            }
4122        }
4123    }
4124
4125    fn after_implement(&mut self) -> Result<()> {
4126        if !self.state.candidate_preservation.is_empty() {
4127            bail!("candidate preservation incomplete; judging is unsafe");
4128        }
4129        // Scan every candidate patch once the set is complete.
4130        if self.state.leaks.is_empty() {
4131            let cfg = self.state.config.blind.clone();
4132            let mut leaks = Vec::new();
4133            for c in &self.state.candidates {
4134                let Some(patch) =
4135                    crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
4136                else {
4137                    continue;
4138                };
4139                leaks.extend(blind::scan(
4140                    &format!("candidate {} patch", c.label),
4141                    &patch,
4142                    &cfg.vendor_tokens,
4143                ));
4144            }
4145            if !leaks.is_empty() {
4146                let summary = leaks
4147                    .iter()
4148                    .map(|l| format!("{}×{} in {}", l.token, l.count, l.site))
4149                    .collect::<Vec<_>>()
4150                    .join(", ");
4151                match cfg.on_leak {
4152                    LeakPolicy::Fail => {
4153                        self.state.status = RunStatus::Failed;
4154                        self.state
4155                            .event("blind", format!("vendor text in a patch: {summary}"));
4156                        self.state.leaks = leaks;
4157                        self.state.save()?;
4158                        self.settle_questions();
4159                        bail!(
4160                            "blind.on_leak = \"fail\" and vendor text reached a \
4161                             judged patch: {summary}"
4162                        );
4163                    }
4164                    LeakPolicy::Redact => self.state.event(
4165                        "blind",
4166                        format!("redacting vendor text for judging: {summary}"),
4167                    ),
4168                    LeakPolicy::Warn => self.state.event(
4169                        "blind",
4170                        format!("vendor text present in a judged patch (shown as-is): {summary}"),
4171                    ),
4172                }
4173                self.state.leaks = leaks;
4174            }
4175        }
4176
4177        if self.state.viable().is_empty() {
4178            if self.state.all_candidates_verified_noop() {
4179                // Every candidate agreed, with evidence the adoption guard
4180                // accepted, that nothing belongs in this worktree. That is
4181                // not the same fact as a candidate that simply failed to
4182                // write anything, and settling it as an ordinary `Failed`
4183                // (see `SCHEMA`'s doc for schema 10) is what let two of
4184                // task 391f's attempts burn a retry each re-discovering the
4185                // same already-landed fix. Terminal either way, so `judge`
4186                // must never run over an empty candidate set — unlike the
4187                // `Failed` branch below this returns `Ok`, not an error:
4188                // nothing here failed.
4189                self.state.status = RunStatus::VerifiedNoop;
4190                self.state.save()?;
4191                self.settle_questions();
4192                return Ok(());
4193            }
4194            self.state.status = RunStatus::Failed;
4195            self.state.save()?;
4196            self.settle_questions();
4197            bail!("no candidate produced a change; nothing to judge");
4198        }
4199        self.state.status = RunStatus::Judging;
4200        self.state.save()?;
4201        Ok(())
4202    }
4203
4204    // --------------------------------------------------------------- judge
4205
4206    async fn judge(&mut self) -> Result<()> {
4207        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4208        // agent files with `magi task add` name the run that paid for it. The
4209        // prompt overlay is cloned alongside it because the waves borrow it
4210        // while `self` is mutably borrowed by the node's own bookkeeping.
4211        let run_id = self.state.id.clone();
4212        let prompts = self.state.config.prompts.clone();
4213        if !self.state.judgements.is_empty() || self.state.judge_skipped {
4214            return Ok(());
4215        }
4216        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4217        if viable.len() == 1 {
4218            // Recorded so this is a one-time event: `judgements` stays empty
4219            // either way, which without this flag is indistinguishable from
4220            // "not yet judged" on the next reentry — and status is left
4221            // untouched, so a later node's conclusion (e.g. `Blocked` after
4222            // the review budget ran out) survives a resume instead of being
4223            // clobbered back to `Judging` by this node running again.
4224            self.state.judge_skipped = true;
4225            self.state.event(
4226                "judge",
4227                format!(
4228                    "only candidate {} produced a change; judging skipped",
4229                    viable[0].label
4230                ),
4231            );
4232            self.state.save()?;
4233            return Ok(());
4234        }
4235        self.state.status = RunStatus::Judging;
4236
4237        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
4238        let language = self.state.config.graph.language.clone();
4239        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4240        let sessions = self.state.config.graph.sessions;
4241        let artifacts = agent::artifacts_dir(&self.state.dir());
4242        let root = self.state.worktree_root();
4243        let base_short = short(&self.state.base_commit);
4244
4245        let mut jobs = Vec::new();
4246        let mut orders = Vec::new();
4247        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4248            let order = blind::presentation_order(viable.len(), j, self.state.seed);
4249            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
4250            orders.push(order.iter().map(|&k| viable[k].index).collect::<Vec<_>>());
4251            let seat_key = format!("judge-{}", j + 1);
4252            let seat = self.seat(&seat_key, &spec.id);
4253            jobs.push(SeatJob {
4254                prompt: prompt::judge(
4255                    &self.state.instruction,
4256                    &views,
4257                    self.roles.judges.len(),
4258                    &base_short,
4259                    &language,
4260                ),
4261                spec,
4262                seat,
4263                cwd: root.join(format!("judge-{}", j + 1)),
4264                timeout,
4265                allow_write: false,
4266                sessions,
4267                artifacts: artifacts.clone(),
4268                stem: format!("judge-{}", j + 1),
4269                handover: None,
4270            });
4271        }
4272
4273        self.state.event(
4274            "judge",
4275            format!(
4276                "{} judges ranking {} candidates blind",
4277                jobs.len(),
4278                viable.len()
4279            ),
4280        );
4281        let labels_for_check = labels.clone();
4282        let mut quota_losses = Vec::new();
4283        let cache = self.state.config.cache_dir();
4284        let ctx = WaveCtx {
4285            carry_seats: false,
4286            pauses: Some((&self.pause, &self.interrupt)),
4287            run: &run_id,
4288            node: "judge",
4289            prompts: &prompts,
4290            cache: cache.as_deref(),
4291            round: None,
4292        };
4293        let results = ask_json_wave::<Ranking>(
4294            jobs,
4295            Arc::clone(&self.sem),
4296            self.state.config.graph.retries,
4297            &self.roles.judge_roster,
4298            &ctx,
4299            &mut quota_losses,
4300            &mut self.state,
4301            &move |r: &Ranking| r.validate(&labels_for_check),
4302        )
4303        .await;
4304        if self.state.resource_block.is_some() {
4305            return self.stop_for_resource();
4306        }
4307        self.state.quota.extend(quota_losses);
4308
4309        for (j, (seat, res, _attempts)) in results.into_iter().enumerate() {
4310            let agent_id = seat.agent.clone();
4311            self.state.seats.insert(seat.key.clone(), seat);
4312            let mut record = Judgement {
4313                judge: j + 1,
4314                seat: format!("judge-{}", j + 1),
4315                agent: agent_id,
4316                ranking: Vec::new(),
4317                reasons: BTreeMap::new(),
4318                confidence: None,
4319                strengths: BTreeMap::new(),
4320                order: orders[j].clone(),
4321                failed: None,
4322                duration_ms: 0,
4323            };
4324            match res {
4325                Ok((ranking, out)) => {
4326                    record.ranking = ranking.normalized();
4327                    record.reasons = ranking.reasons;
4328                    record.strengths = ranking.strengths;
4329                    record.confidence = ranking.confidence;
4330                    record.duration_ms = out.duration_ms;
4331                    self.state.event(
4332                        "judge",
4333                        format!(
4334                            "judge {} ranked {}",
4335                            j + 1,
4336                            record.ranking.iter().collect::<String>()
4337                        ),
4338                    );
4339                }
4340                Err(e) => {
4341                    record.failed = Some(e.to_string());
4342                    self.state
4343                        .event("judge", format!("judge {} produced no ranking: {e}", j + 1));
4344                }
4345            }
4346            self.state.judgements.push(record);
4347            self.state.save()?;
4348        }
4349        Ok(())
4350    }
4351
4352    // ---------------------------------------------------------- deliberate
4353
4354    async fn deliberate(&mut self) -> Result<()> {
4355        if self.hold_base_sync().await? {
4356            return Ok(());
4357        }
4358        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4359        // agent files with `magi task add` name the run that paid for it. The
4360        // prompt overlay is cloned alongside it because the waves borrow it
4361        // while `self` is mutably borrowed by the node's own bookkeeping.
4362        let run_id = self.state.id.clone();
4363        let prompts = self.state.config.prompts.clone();
4364        let rounds = self.state.config.graph.deliberate_rounds;
4365        // Resume unfinished rounds after an outage, but never reopen a tally.
4366        if self.state.deliberation.len() >= rounds || self.state.tally.is_some() {
4367            return Ok(());
4368        }
4369        let tops: Vec<char> = self
4370            .state
4371            .judgements
4372            .iter()
4373            .filter_map(|j| j.ranking.first().copied())
4374            .collect();
4375        if tops.len() < 2 || tops.iter().all(|t| *t == tops[0]) || rounds == 0 {
4376            if tops.len() >= 2 && tops.iter().all(|t| *t == tops[0]) {
4377                self.state.event(
4378                    "deliberate",
4379                    format!("judges agreed on {} outright; no deliberation", tops[0]),
4380                );
4381            }
4382            self.state.status = RunStatus::Voting;
4383            self.state.save()?;
4384            return Ok(());
4385        }
4386
4387        self.state.status = RunStatus::Deliberating;
4388        self.state.event(
4389            "deliberate",
4390            format!(
4391                "split: first choices were {} — opening {rounds} round(s)",
4392                tops.iter().collect::<String>()
4393            ),
4394        );
4395
4396        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4397        let language = self.state.config.graph.language.clone();
4398        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4399        let sessions = self.state.config.graph.sessions;
4400        let artifacts = agent::artifacts_dir(&self.state.dir());
4401        let root = self.state.worktree_root();
4402        let base_short = short(&self.state.base_commit);
4403
4404        // Judges argue in sequence so that a turn can answer the one before it;
4405        // that is the difference between deliberation and three parallel
4406        // monologues.
4407        for round in self.state.deliberation.len() + 1..=rounds {
4408            let mut turns: Vec<DeliberationTurn> = Vec::new();
4409            let mut round_losses = Vec::new();
4410            let mut asked = 0;
4411            for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4412                if self.state.judgements[j].failed.is_some() {
4413                    continue;
4414                }
4415                let seat_key = format!("judge-{}", j + 1);
4416                let spec = self.occupant(&seat_key, spec);
4417                let mut seat = self.seat(&seat_key, &spec.id);
4418                let transcript = self.transcript(&turns, j);
4419                let build = |context: Option<&str>| {
4420                    prompt::deliberate(
4421                        &self.state.instruction,
4422                        context,
4423                        &transcript,
4424                        round,
4425                        rounds,
4426                        &language,
4427                    )
4428                };
4429                let block = self.candidate_block(&viable, &base_short);
4430                let full = build(Some(&block));
4431                let text = if has_context(&spec, &seat, sessions) {
4432                    build(None)
4433                } else {
4434                    full.clone()
4435                };
4436                let job = SeatJob {
4437                    spec,
4438                    seat: seat.clone(),
4439                    prompt: text,
4440                    cwd: root.join(format!("judge-{}", j + 1)),
4441                    timeout,
4442                    allow_write: false,
4443                    sessions,
4444                    artifacts: artifacts.clone(),
4445                    stem: format!("delib-{round}-judge-{}", j + 1),
4446                    handover: Some(full),
4447                };
4448                let cache = self.state.config.cache_dir();
4449                let ctx = WaveCtx {
4450                    carry_seats: false,
4451                    pauses: Some((&self.pause, &self.interrupt)),
4452                    run: &run_id,
4453                    node: "deliberate",
4454                    prompts: &prompts,
4455                    cache: cache.as_deref(),
4456                    round: None,
4457                };
4458                // A turn is never nudged (`retries` 0): a failed seat is
4459                // handed to the next roster agent, which gets the full
4460                // context. An empty answer is a turn, not a failure.
4461                let mut losses = Vec::new();
4462                asked += 1;
4463                let mut results = ask_wave_with::<String>(
4464                    vec![job],
4465                    Arc::clone(&self.sem),
4466                    0,
4467                    &self.roles.judge_roster,
4468                    &ctx,
4469                    &mut losses,
4470                    &mut self.state,
4471                    &|text: &str| {
4472                        Ok(verdict::section(text, "position").unwrap_or_else(|| text.to_owned()))
4473                    },
4474                )
4475                .await;
4476                if self.state.resource_block.is_some() {
4477                    return self.stop_for_resource();
4478                }
4479                round_losses.extend(losses.iter().cloned());
4480                self.state.quota.extend(losses);
4481                let (updated, res, _) = results.pop().expect("one job in, one result out");
4482                seat = updated;
4483                let agent_id = seat.agent.clone();
4484                self.state.seats.insert(seat.key.clone(), seat);
4485                let body = match res {
4486                    Ok((body, _)) => body,
4487                    // Skip the seat; a CLI's raw error JSON is never read as
4488                    // this judge's position.
4489                    Err(e) => {
4490                        self.state
4491                            .event("deliberate", format!("judge {} skipped: {e}", j + 1));
4492                        continue;
4493                    }
4494                };
4495                let tentative = verdict::extract_json::<Position>(&body)
4496                    .ok()
4497                    .and_then(|p| p.tentative)
4498                    .and_then(|s| s.trim().chars().next())
4499                    .map(|c| c.to_ascii_uppercase());
4500                self.state.event(
4501                    "deliberate",
4502                    format!(
4503                        "round {round}: judge {} now favours {}",
4504                        j + 1,
4505                        tentative.map_or("—".to_owned(), |c| c.to_string())
4506                    ),
4507                );
4508                turns.push(DeliberationTurn {
4509                    judge: j + 1,
4510                    agent: agent_id,
4511                    body: blind::sanitize_prose(&body, &self.state.config.blind),
4512                    tentative,
4513                });
4514            }
4515            if asked > 0 && turns.is_empty() && round_losses.len() == asked {
4516                block_machine_outage(&mut self.state, "deliberate", &round_losses);
4517                return self.stop_for_resource();
4518            }
4519            self.state
4520                .deliberation
4521                .push(DeliberationRound { round, turns });
4522            self.state.save()?;
4523        }
4524
4525        self.state.status = RunStatus::Voting;
4526        self.state.save()?;
4527        Ok(())
4528    }
4529
4530    // ---------------------------------------------------------------- vote
4531
4532    async fn vote(&mut self) -> Result<()> {
4533        if self.hold_base_sync().await? {
4534            return Ok(());
4535        }
4536        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4537        // agent files with `magi task add` name the run that paid for it. The
4538        // prompt overlay is cloned alongside it because the waves borrow it
4539        // while `self` is mutably borrowed by the node's own bookkeeping.
4540        let run_id = self.state.id.clone();
4541        let prompts = self.state.config.prompts.clone();
4542        if !self.state.votes.is_empty() || self.state.tally.is_some() {
4543            return Ok(());
4544        }
4545        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
4546        if viable.len() == 1 {
4547            return Ok(());
4548        }
4549        self.state.status = RunStatus::Voting;
4550
4551        let language = self.state.config.graph.language.clone();
4552        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4553        let sessions = self.state.config.graph.sessions;
4554        let artifacts = agent::artifacts_dir(&self.state.dir());
4555        let root = self.state.worktree_root();
4556        let base_short = short(&self.state.base_commit);
4557        let candidates: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4558
4559        let mut jobs = Vec::new();
4560        let mut seats_at = Vec::new();
4561        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4562            if self
4563                .state
4564                .judgements
4565                .get(j)
4566                .is_some_and(|r| r.failed.is_some())
4567            {
4568                continue;
4569            }
4570            let seat_key = format!("judge-{}", j + 1);
4571            let spec = self.occupant(&seat_key, spec);
4572            let seat = self.seat(&seat_key, &spec.id);
4573            let full = self.vote_prompt_full(j, &viable, &language, &candidates, &base_short);
4574            let text = if has_context(&spec, &seat, sessions) {
4575                prompt::final_vote(&viable, &language)
4576            } else {
4577                full.clone()
4578            };
4579            jobs.push(SeatJob {
4580                spec,
4581                seat,
4582                prompt: text,
4583                cwd: root.join(format!("judge-{}", j + 1)),
4584                timeout,
4585                allow_write: false,
4586                sessions,
4587                artifacts: artifacts.clone(),
4588                stem: format!("vote-judge-{}", j + 1),
4589                handover: Some(full),
4590            });
4591            seats_at.push(j);
4592        }
4593
4594        self.state.event(
4595            "vote",
4596            format!(
4597                "collecting {} final votes one by one, privately",
4598                jobs.len()
4599            ),
4600        );
4601        let allowed = viable.clone();
4602        let mut quota_losses = Vec::new();
4603        let cache = self.state.config.cache_dir();
4604        let ctx = WaveCtx {
4605            carry_seats: false,
4606            pauses: Some((&self.pause, &self.interrupt)),
4607            run: &run_id,
4608            node: "vote",
4609            prompts: &prompts,
4610            cache: cache.as_deref(),
4611            round: None,
4612        };
4613        let results = ask_json_wave::<FinalVote>(
4614            jobs,
4615            Arc::clone(&self.sem),
4616            self.state.config.graph.retries,
4617            &self.roles.judge_roster,
4618            &ctx,
4619            &mut quota_losses,
4620            &mut self.state,
4621            &move |v: &FinalVote| match v.label() {
4622                Some(c) if allowed.contains(&c) => Ok(()),
4623                other => bail!("vote {other:?} is not one of {allowed:?}"),
4624            },
4625        )
4626        .await;
4627        if self.state.resource_block.is_some() {
4628            return self.stop_for_resource();
4629        }
4630        self.state.quota.extend(quota_losses);
4631
4632        for (&j, (seat, res, _attempts)) in seats_at.iter().zip(results) {
4633            let agent_id = seat.agent.clone();
4634            self.state.seats.insert(seat.key.clone(), seat);
4635            let initial = self
4636                .state
4637                .judgements
4638                .get(j)
4639                .and_then(|r| r.ranking.first().copied());
4640            let mut record = VoteRecord {
4641                judge: j + 1,
4642                agent: agent_id,
4643                vote: None,
4644                reason: String::new(),
4645                changed: false,
4646            };
4647            match res {
4648                Ok((v, _)) => {
4649                    record.vote = v.label();
4650                    record.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
4651                    record.changed = matches!((record.vote, initial), (Some(a), Some(b)) if a != b);
4652                    self.state.event(
4653                        "vote",
4654                        format!(
4655                            "judge {} voted {}{}",
4656                            j + 1,
4657                            record.vote.unwrap_or('?'),
4658                            if record.changed { " (changed)" } else { "" }
4659                        ),
4660                    );
4661                }
4662                Err(e) => {
4663                    self.state
4664                        .event("vote", format!("judge {} cast no vote: {e}", j + 1));
4665                }
4666            }
4667            self.state.votes.push(record);
4668            self.state.save()?;
4669        }
4670        Ok(())
4671    }
4672
4673    // --------------------------------------------------------------- tally
4674
4675    fn tally(&mut self) -> Result<()> {
4676        if self.state.tally.is_some() {
4677            return Ok(());
4678        }
4679        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
4680        let tops: Vec<char> = self
4681            .state
4682            .judgements
4683            .iter()
4684            .filter_map(|j| j.ranking.first().copied())
4685            .collect();
4686        let unanimous_initial = tops.len() > 1 && tops.iter().all(|t| *t == tops[0]);
4687
4688        // A judge whose private vote failed still counted once, in the initial
4689        // ranking; using it beats discarding a whole seat.
4690        let mut first_choice: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
4691        let mut cast: Vec<char> = Vec::new();
4692        for (i, j) in self.state.judgements.iter().enumerate() {
4693            let vote = self
4694                .state
4695                .votes
4696                .iter()
4697                .find(|v| v.judge == i + 1)
4698                .and_then(|v| v.vote)
4699                .or_else(|| j.ranking.first().copied());
4700            if let Some(v) = vote {
4701                *first_choice.entry(v).or_insert(0) += 1;
4702                cast.push(v);
4703            }
4704        }
4705
4706        let mut borda: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
4707        for j in &self.state.judgements {
4708            let n = j.ranking.len();
4709            for (pos, label) in j.ranking.iter().enumerate() {
4710                *borda.entry(*label).or_insert(0) += n.saturating_sub(pos + 1);
4711            }
4712        }
4713
4714        let best = first_choice.values().copied().max().unwrap_or(0);
4715        let mut leaders: Vec<char> = first_choice
4716            .iter()
4717            .filter(|(_, v)| **v == best)
4718            .map(|(k, _)| *k)
4719            .collect();
4720        let mut tie_break = None;
4721        if leaders.len() > 1 {
4722            let top_borda = leaders.iter().map(|l| borda[l]).max().unwrap_or(0);
4723            let borda_leaders: Vec<char> = leaders
4724                .iter()
4725                .copied()
4726                .filter(|l| borda[l] == top_borda)
4727                .collect();
4728            tie_break = Some(if borda_leaders.len() == 1 {
4729                format!(
4730                    "{} way tie on first-choice votes, broken by Borda points from the initial rankings",
4731                    leaders.len()
4732                )
4733            } else {
4734                format!(
4735                    "{} way tie on both first-choice votes and Borda points, broken by label order",
4736                    leaders.len()
4737                )
4738            });
4739            leaders = borda_leaders;
4740            leaders.sort_unstable();
4741        }
4742        let winner = *leaders
4743            .first()
4744            .or(viable.first())
4745            .context("no candidate to declare a winner from")?;
4746
4747        let changed_votes = self.state.votes.iter().filter(|v| v.changed).count();
4748        let unanimous_final = !cast.is_empty() && cast.iter().all(|c| *c == cast[0]);
4749        let deliberated = !self.state.deliberation.is_empty();
4750
4751        // Whose verdict is this? A rate-limited seat is absent even if it
4752        // ranked before the limit hit, so presence is measured against the
4753        // recorded losses, not just "did a ranking ever appear".
4754        let quota_seats: std::collections::BTreeSet<&str> =
4755            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
4756        let mut present = 0usize;
4757        for (i, j) in self.state.judgements.iter().enumerate() {
4758            if quota_seats.contains(j.seat.as_str()) {
4759                continue;
4760            }
4761            let ranked = !j.ranking.is_empty() && j.failed.is_none();
4762            let voted = self
4763                .state
4764                .votes
4765                .iter()
4766                .any(|v| v.judge == i + 1 && v.vote.is_some());
4767            if ranked || voted {
4768                present += 1;
4769            }
4770        }
4771        // Strict majority of the configured panel. A bare majority is real
4772        // signal we can act on, while a minority verdict must never stand in
4773        // for a healthy one. A one-candidate run needs no panel at all, and
4774        // `judges` stays `0` rather than the roster size a panel that never
4775        // sat would otherwise be credited with.
4776        let needs_quorum = viable.len() > 1;
4777        let judges_total = if needs_quorum {
4778            self.roles.judges.len()
4779        } else {
4780            0
4781        };
4782        let quorum = if needs_quorum {
4783            judges_total / 2 + 1
4784        } else {
4785            0
4786        };
4787        let met_quorum = !needs_quorum || present >= quorum;
4788        let uncontested = (!needs_quorum).then(|| {
4789            format!("only one candidate ({winner}) produced a usable change; no panel was asked")
4790        });
4791
4792        self.state.event(
4793            "tally",
4794            match &uncontested {
4795                Some(reason) => format!("winner {winner} — {reason}"),
4796                None => format!(
4797                    "winner {winner} — votes {} | initial {} | {} changed | \
4798                     {present}/{judges_total} judges{}",
4799                    first_choice
4800                        .iter()
4801                        .map(|(k, v)| format!("{k}:{v}"))
4802                        .collect::<Vec<_>>()
4803                        .join(" "),
4804                    if unanimous_initial {
4805                        "unanimous"
4806                    } else {
4807                        "split"
4808                    },
4809                    changed_votes,
4810                    if met_quorum {
4811                        String::new()
4812                    } else {
4813                        format!(" — below quorum ({quorum} required)")
4814                    },
4815                ),
4816            },
4817        );
4818        if !met_quorum {
4819            self.state.event(
4820                "stall",
4821                format!(
4822                    "verdict rests on {present} of {judges_total} judges (quorum {quorum}); \
4823                     the run stops here, resumable"
4824                ),
4825            );
4826        }
4827        self.state.tally = Some(Tally {
4828            first_choice,
4829            borda,
4830            winner,
4831            rankings: tops.len(),
4832            unanimous_initial,
4833            deliberated,
4834            changed_votes,
4835            unanimous_final,
4836            tie_break,
4837            judges: judges_total,
4838            present,
4839            quorum,
4840            met_quorum,
4841            uncontested,
4842        });
4843        self.state.status = if met_quorum {
4844            RunStatus::Reviewing
4845        } else {
4846            RunStatus::Stalled
4847        };
4848        self.state.save()?;
4849        Ok(())
4850    }
4851
4852    // ------------------------------------------------------------- recover
4853
4854    /// Re-ask the judge seats `tally` counts as absent, so a `Stalled` run can be
4855    /// resumed toward completion once the transient cause clears.
4856    ///
4857    /// A seat is absent — and therefore re-asked — when `tally` refuses to count
4858    /// it toward the quorum, which is exactly the set of seats whose absence
4859    /// collapsed the panel: struck by a rate limit at *any* node (the quorum must
4860    /// not depend on which node happened to hit the limit), or an ordinary
4861    /// failure (`failed = Some`) that never produced a usable ranking. A healthy
4862    /// seat is never disturbed.
4863    ///
4864    /// A seat that now answers with a usable ranking is "recovered": its
4865    /// `Judgement` is refreshed, its `QuotaLoss`/`failed` state cleared (so
4866    /// `tally` counts it present again), and its vote re-collected. A seat that
4867    /// still fails keeps its loss and stays absent.
4868    ///
4869    /// Returns `true` when the re-tally restores the quorum (the run may proceed
4870    /// to review/gate/merge), `false` when it is still below quorum (the run
4871    /// stays `Stalled`, still resumable for a later retry).
4872    #[allow(clippy::too_many_lines)]
4873    async fn recover_stall(&mut self) -> Result<bool> {
4874        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4875        // agent files with `magi task add` name the run that paid for it. The
4876        // prompt overlay is cloned alongside it because the waves borrow it
4877        // while `self` is mutably borrowed by the node's own bookkeeping.
4878        let run_id = self.state.id.clone();
4879        let prompts = self.state.config.prompts.clone();
4880        // Absent seats = quota-lost at any node, or failed outright. Mirroring
4881        // `tally`'s presence test (rather than the old quota-judge/vote filter)
4882        // is what keeps a non-quota collapse — or a quota loss recorded at the
4883        // deliberate node — from being a permanent dead-end on `--resume`.
4884        let quota_seats: BTreeSet<&str> =
4885            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
4886        let absent: Vec<String> = self
4887            .state
4888            .judgements
4889            .iter()
4890            .filter(|j| quota_seats.contains(j.seat.as_str()) || j.failed.is_some())
4891            .map(|j| j.seat.clone())
4892            .collect();
4893        if absent.is_empty() {
4894            return Ok(false);
4895        }
4896        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4897        if viable.len() <= 1 {
4898            return Ok(false);
4899        }
4900        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
4901        let language = self.state.config.graph.language.clone();
4902        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4903        let sessions = self.state.config.graph.sessions;
4904        let artifacts = agent::artifacts_dir(&self.state.dir());
4905        let root = self.state.worktree_root();
4906        let base_short = short(&self.state.base_commit);
4907        let candidates: Vec<Candidate> = viable.clone();
4908
4909        // Map each absent seat key to its 0-based position in `roles.judges`.
4910        let mut positions: Vec<usize> = absent
4911            .iter()
4912            .filter_map(|k| self.state.judgements.iter().position(|r| &r.seat == k))
4913            .collect();
4914        if positions.is_empty() {
4915            return Ok(false);
4916        }
4917        positions.sort_unstable();
4918        positions.dedup();
4919
4920        // Re-rank the lost seats, one blind prompt each.
4921        let mut judge_jobs = Vec::new();
4922        for &j in &positions {
4923            let order = blind::presentation_order(viable.len(), j, self.state.seed);
4924            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
4925            let seat_key = format!("judge-{}", j + 1);
4926            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
4927            let seat = self.seat(&seat_key, &spec.id);
4928            judge_jobs.push(SeatJob {
4929                spec,
4930                seat,
4931                prompt: prompt::judge(
4932                    &self.state.instruction,
4933                    &views,
4934                    self.roles.judges.len(),
4935                    &base_short,
4936                    &language,
4937                ),
4938                cwd: root.join(seat_key),
4939                timeout,
4940                allow_write: false,
4941                sessions,
4942                artifacts: artifacts.clone(),
4943                stem: format!("judge-{}-recover", j + 1),
4944                handover: None,
4945            });
4946        }
4947
4948        let labels_for_check = labels.clone();
4949        let mut judge_losses = Vec::new();
4950        let retries = self.state.config.graph.retries;
4951        let cache = self.state.config.cache_dir();
4952        let ctx = WaveCtx {
4953            carry_seats: false,
4954            pauses: Some((&self.pause, &self.interrupt)),
4955            run: &run_id,
4956            node: "judge",
4957            prompts: &prompts,
4958            cache: cache.as_deref(),
4959            round: None,
4960        };
4961        let results = ask_json_wave::<Ranking>(
4962            judge_jobs,
4963            Arc::clone(&self.sem),
4964            retries,
4965            &self.roles.judge_roster,
4966            &ctx,
4967            &mut judge_losses,
4968            &mut self.state,
4969            &move |r: &Ranking| r.validate(&labels_for_check),
4970        )
4971        .await;
4972        if self.state.resource_block.is_some() {
4973            self.stop_for_resource()?;
4974            return Ok(false);
4975        }
4976
4977        // Refresh the judgement of every seat that ranked again.
4978        let mut recovered: BTreeSet<usize> = BTreeSet::new();
4979        for (&j, (seat, res, _attempts)) in positions.iter().zip(results) {
4980            let agent_id = seat.agent.clone();
4981            self.state.seats.insert(seat.key.clone(), seat);
4982            let record = &mut self.state.judgements[j];
4983            match res {
4984                Ok((ranking, out)) => {
4985                    record.agent = agent_id;
4986                    record.ranking = ranking.normalized();
4987                    record.reasons = ranking.reasons;
4988                    record.strengths = ranking.strengths;
4989                    record.confidence = ranking.confidence;
4990                    record.failed = None;
4991                    record.duration_ms = out.duration_ms;
4992                    recovered.insert(j);
4993                    self.state.event(
4994                        "recover",
4995                        format!("judge {} ranked again after the limit", j + 1),
4996                    );
4997                }
4998                Err(e) => {
4999                    self.state
5000                        .event("recover", format!("judge {} still cannot rank: {e}", j + 1));
5001                }
5002            }
5003        }
5004
5005        // Re-ask the votes of the seats that recovered a ranking.
5006        let mut vote_jobs = Vec::new();
5007        let mut vote_pos: Vec<usize> = Vec::new();
5008        for &j in &recovered {
5009            let seat_key = format!("judge-{}", j + 1);
5010            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
5011            let seat = self.seat(&seat_key, &spec.id);
5012            let full = self.vote_prompt_full(j, &labels, &language, &candidates, &base_short);
5013            let text = if has_context(&spec, &seat, sessions) {
5014                prompt::final_vote(&labels, &language)
5015            } else {
5016                full.clone()
5017            };
5018            vote_jobs.push(SeatJob {
5019                spec,
5020                seat,
5021                prompt: text,
5022                cwd: root.join(seat_key),
5023                timeout,
5024                allow_write: false,
5025                sessions,
5026                artifacts: artifacts.clone(),
5027                stem: format!("vote-judge-{}-recover", j + 1),
5028                handover: Some(full),
5029            });
5030            vote_pos.push(j);
5031        }
5032        let allowed = labels.clone();
5033        let mut vote_losses = Vec::new();
5034        let vote_retries = self.state.config.graph.retries;
5035        let vote_cache = self.state.config.cache_dir();
5036        let ctx = WaveCtx {
5037            carry_seats: false,
5038            pauses: Some((&self.pause, &self.interrupt)),
5039            run: &run_id,
5040            node: "vote",
5041            prompts: &prompts,
5042            cache: vote_cache.as_deref(),
5043            round: None,
5044        };
5045        let votes = ask_json_wave::<FinalVote>(
5046            vote_jobs,
5047            Arc::clone(&self.sem),
5048            vote_retries,
5049            &self.roles.judge_roster,
5050            &ctx,
5051            &mut vote_losses,
5052            &mut self.state,
5053            &move |v: &FinalVote| match v.label() {
5054                Some(c) if allowed.contains(&c) => Ok(()),
5055                other => bail!("vote {other:?} is not one of {allowed:?}"),
5056            },
5057        )
5058        .await;
5059        if self.state.resource_block.is_some() {
5060            self.stop_for_resource()?;
5061            return Ok(false);
5062        }
5063        for (&j, (seat, res, _attempts)) in vote_pos.iter().zip(votes) {
5064            let agent_id = seat.agent.clone();
5065            self.state.seats.insert(seat.key.clone(), seat);
5066            match res {
5067                Ok((v, _)) => {
5068                    if let Some(rec) = self.state.votes.iter_mut().find(|r| r.judge == j + 1) {
5069                        rec.vote = v.label();
5070                        rec.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
5071                    } else {
5072                        self.state.votes.push(VoteRecord {
5073                            judge: j + 1,
5074                            agent: agent_id,
5075                            vote: v.label(),
5076                            reason: blind::sanitize_prose(&v.reason, &self.state.config.blind),
5077                            changed: false,
5078                        });
5079                    }
5080                    self.state.event(
5081                        "recover",
5082                        format!("judge {} voted again after the limit", j + 1),
5083                    );
5084                }
5085                Err(e) => {
5086                    self.state
5087                        .event("recover", format!("judge {} still cannot vote: {e}", j + 1));
5088                }
5089            }
5090        }
5091
5092        // A seat that ranked again is present even if its re-vote failed —
5093        // `tally` falls back to the initial ranking's first choice — so clear
5094        // its quota loss. Seats that still fail keep theirs and stay absent.
5095        let recovered_keys: BTreeSet<String> = recovered
5096            .iter()
5097            .map(|&j| format!("judge-{}", j + 1))
5098            .collect();
5099        self.state
5100            .quota
5101            .retain(|q| !recovered_keys.contains(&q.seat));
5102        // A seat that hit the limit again is a fresh loss, not the old one:
5103        // replace the stale entry so the history stays one-per-seat and the
5104        // daemon can tell this attempt's loss from a previous session's.
5105        for loss in judge_losses.into_iter().chain(vote_losses) {
5106            if recovered_keys.contains(&loss.seat) {
5107                continue;
5108            }
5109            self.state.quota.retain(|q| q.seat != loss.seat);
5110            self.state.quota.push(loss);
5111        }
5112
5113        // Recompute the verdict from the refreshed panel.
5114        self.state.tally = None;
5115        self.tally()?;
5116        Ok(self
5117            .state
5118            .tally
5119            .as_ref()
5120            .map(|t| t.met_quorum)
5121            .unwrap_or(false))
5122    }
5123
5124    // ---------------------------------------------------------------- graft
5125
5126    /// Port the strengths the judges attributed to the losing candidates onto
5127    /// the winner, once, between the tally and the review loop.
5128    ///
5129    /// Best-effort by construction: it returns nothing and fails nothing. A
5130    /// skip, a fixer that failed or hit quota, or a round that changed nothing
5131    /// all leave the winner at its previous commit (`GraftRecord::pre`), and
5132    /// the run carries on as if the phase were off. See [`graft`] for the
5133    /// decisions and `AGENTS.md` for the invariants.
5134    ///
5135    /// The one exception is a rollback that could not be confirmed: the
5136    /// rejected commit may still be the winner's tip, so the run is blocked
5137    /// (resumable; the record stays `Running`, which makes a resume retry the
5138    /// restore) instead of reviewing, gating and merging it.
5139    async fn graft(&mut self) -> Result<()> {
5140        let Err(e) = self.graft_inner().await else {
5141            return Ok(());
5142        };
5143        if e.is::<crate::repo_lock::ResourceBlocked>() {
5144            return Err(e);
5145        }
5146        if e.downcast_ref::<GraftRestoreFailed>().is_some() {
5147            self.state.status = RunStatus::Blocked;
5148            self.state.event("graft", format!("blocked: {e:#}"));
5149            self.state.save()?;
5150            return Err(e);
5151        }
5152        // An error after the `Running` record was saved may have left the
5153        // fixer's work in the tree: the record must not stay unsettled
5154        // (a later resume would reset past the review fixes), so confirm the
5155        // restore now, or block.
5156        if let Some(rec) = self.state.graft.clone()
5157            && !rec.outcome.settled()
5158        {
5159            if let Some(winner) = self.state.winner().cloned() {
5160                if let Err(re) = self.graft_restore(&winner.worktree, &rec.pre).await {
5161                    if re.is::<crate::repo_lock::ResourceBlocked>() {
5162                        return Err(re);
5163                    }
5164                    self.state.status = RunStatus::Blocked;
5165                    self.state.event("graft", format!("blocked: {re:#}"));
5166                    self.state.save()?;
5167                    return Err(re);
5168                }
5169            }
5170            if let Some(g) = self.state.graft.as_mut() {
5171                g.outcome = GraftOutcome::RolledBack(format!("{e:#}"));
5172            }
5173        }
5174        self.state.event("graft", format!("skipped: {e:#}"));
5175        if let Err(e) = self.state.save() {
5176            tracing::warn!("save after graft: {e:#}");
5177        }
5178        Ok(())
5179    }
5180
5181    /// Put the winner back on `pre` and confirm it: a failed `reset` (a stale
5182    /// `index.lock`, say) or a tip that is not `pre` afterwards is an error.
5183    async fn graft_restore(&mut self, wt: &Path, pre: &str) -> Result<()> {
5184        let _coordination = self.coordinate(wt).await?;
5185        crate::recovery::restore_repair(wt, pre)
5186            .await
5187            .map_err(|e| GraftRestoreFailed(format!("{e:#}")).into())
5188    }
5189
5190    /// A skip is a run event, recorded once however often the node is re-entered.
5191    fn graft_skipped(&mut self, why: &str) {
5192        let message = format!("skipped: {why}");
5193        if !self
5194            .state
5195            .events
5196            .iter()
5197            .any(|e| e.node == "graft" && e.message == message)
5198        {
5199            self.state.event("graft", message);
5200        }
5201    }
5202
5203    async fn graft_inner(&mut self) -> Result<()> {
5204        // A round that was started and never finished (crash, kill): the
5205        // fixer may have left anything in the tree, so put the winner back.
5206        if let Some(rec) = self.state.graft.clone()
5207            && !rec.outcome.settled()
5208        {
5209            // Reviews exist only if the graft ended without its record being
5210            // settled (a swallowed error): the tree has moved on since, and
5211            // a reset to `pre` would discard the review fixes.
5212            if self.state.reviews.is_empty()
5213                && let Some(winner) = self.state.winner().cloned()
5214            {
5215                self.graft_restore(&winner.worktree, &rec.pre).await?;
5216            }
5217            if rec.outcome == GraftOutcome::WaitingForRestore {
5218                self.state.graft = None;
5219                self.state.save()?;
5220            } else {
5221                if let Some(g) = self.state.graft.as_mut() {
5222                    g.outcome = GraftOutcome::RolledBack(graft::INTERRUPTED.to_owned());
5223                }
5224                self.state.event(
5225                    "graft",
5226                    "rolled back: the previous round was interrupted; the winner is untouched",
5227                );
5228                self.state.save()?;
5229                return Ok(());
5230            }
5231        }
5232        let plan = match graft::plan(&self.state) {
5233            Ok(plan) => plan,
5234            Err(skip) => {
5235                if skip != graft::Skip::AlreadyDone {
5236                    self.graft_skipped(skip.reason());
5237                    self.state.save()?;
5238                }
5239                return Ok(());
5240            }
5241        };
5242        let Some(winner) = self.state.winner().cloned() else {
5243            return Ok(());
5244        };
5245        let wt = winner.worktree.clone();
5246        if !git::is_clean(&wt).await? {
5247            self.graft_skipped("the winner's worktree has uncommitted changes");
5248            self.state.save()?;
5249            return Ok(());
5250        }
5251        let pre = git::rev_parse(&wt, "HEAD").await?;
5252        // Saved before the fixer is called: a stop from here on is repaired
5253        // by the branch above on the next entry.
5254        self.state.graft = Some(GraftRecord {
5255            pre: pre.clone(),
5256            post: None,
5257            lines: None,
5258            limit: None,
5259            agent: None,
5260            outcome: GraftOutcome::Running,
5261            requested: graft::requested(&plan),
5262            adoption: None,
5263            adoption_error: None,
5264        });
5265        self.state.event(
5266            "graft",
5267            format!(
5268                "porting strengths of candidate(s) {} onto {}",
5269                plan.strengths
5270                    .iter()
5271                    .map(|(l, _, _)| l.to_string())
5272                    .collect::<Vec<_>>()
5273                    .join(", "),
5274                plan.winner
5275            ),
5276        );
5277        self.state.save()?;
5278
5279        let fix_prompt = prompt::graft(
5280            &self.state.instruction,
5281            plan.winner,
5282            &plan.strengths,
5283            &self.state.config.graph.language,
5284        );
5285        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
5286        let sessions = self.state.config.graph.sessions;
5287        let artifacts = agent::artifacts_dir(&self.state.dir());
5288        let attempts = fixer::graft_attempts(&self.state, &self.roles, &winner);
5289        let (_, seat, out) = self
5290            .ask_fixer_among(attempts, "graft", None, Some((&wt, &pre)), |spec, seat| {
5291                SeatJob {
5292                    prompt: fix_prompt.clone(),
5293                    spec,
5294                    seat,
5295                    cwd: wt.clone(),
5296                    timeout,
5297                    allow_write: true,
5298                    sessions,
5299                    artifacts: artifacts.clone(),
5300                    stem: "graft".to_owned(),
5301                    handover: None,
5302                }
5303            })
5304            .await;
5305        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
5306            // Preserve the need to restore earlier fallback edits without
5307            // confusing an unstarted seat with an interrupted invocation.
5308            self.state.graft.as_mut().expect("graft record").outcome =
5309                GraftOutcome::WaitingForRestore;
5310            return self.stop_for_resource();
5311        }
5312        let mut why: Option<String> = None;
5313        match &out {
5314            AgentOutcome::Ok(o) if agent::output_advances(o) => {
5315                why = Some("the fixer produced nothing usable".to_owned());
5316            }
5317            AgentOutcome::Ok(_) => {}
5318            AgentOutcome::Dropped(_) => why = Some("the CLI dropped the stream".to_owned()),
5319            AgentOutcome::Quota(o) => {
5320                self.state.quota.push(QuotaLoss::from_report(
5321                    seat.key.clone(),
5322                    "graft",
5323                    o.quota.as_ref(),
5324                ));
5325                why = Some("rate limited (quota)".to_owned());
5326            }
5327            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
5328                why = Some(format!(
5329                    "the fixer failed: {}",
5330                    e.lines()
5331                        .next()
5332                        .unwrap_or("")
5333                        .chars()
5334                        .take(160)
5335                        .collect::<String>()
5336                ));
5337            }
5338        }
5339        let agent_id = seat.agent.clone();
5340        self.state.seats.insert(seat.key.clone(), seat);
5341
5342        let mut post = None;
5343        let mut lines = None;
5344        let _coordination = self.coordinate(&wt).await?;
5345        if why.is_none() {
5346            let rescued = git::rescue_commit(&wt, "magi: graft (uncommitted work)").await;
5347            if let Ok(r) = &rescued {
5348                self.state.note_withheld("graft", &r.withheld);
5349            }
5350            let head = git::rev_parse(&wt, "HEAD").await?;
5351            // What is measured must be what gets reviewed and gated: a failed
5352            // rescue, or anything still uncommitted (withheld lockfiles
5353            // aside, which are never part of the tree), rejects the graft.
5354            let dirty = match &rescued {
5355                Ok(r) => git::status_porcelain(&wt)
5356                    .await
5357                    .map(|st| {
5358                        st.lines().any(|l| {
5359                            !r.withheld
5360                                .iter()
5361                                .any(|w| l.trim_end().ends_with(w.path.as_str()))
5362                        })
5363                    })
5364                    .unwrap_or(true),
5365                Err(_) => true,
5366            };
5367            if dirty {
5368                why = Some("the fixer left changes that could not be committed".to_owned());
5369            } else if head == pre {
5370                why = Some("the fixer changed nothing".to_owned());
5371            } else {
5372                lines = git::changed_lines(&wt, &pre, &head).await;
5373                post = Some(head);
5374            }
5375        }
5376        let (adoption, adoption_error) = match &out {
5377            AgentOutcome::Ok(o) => crate::graft_report::adoption_of(&o.text),
5378            _ => (None, None),
5379        };
5380        let requested = graft::requested(&plan);
5381        let outcome = match why {
5382            None => {
5383                self.state.event(
5384                    "graft",
5385                    format!(
5386                        "applied: {}",
5387                        lines.map_or_else(
5388                            || "changed lines unavailable".to_owned(),
5389                            |n| format!("{n} changed lines")
5390                        )
5391                    ),
5392                );
5393                GraftOutcome::Applied
5394            }
5395            Some(why) => {
5396                // Not settled until the restore is confirmed: the record
5397                // stays `Running`, so a resume retries it.
5398                crate::recovery::restore_repair(&wt, &pre)
5399                    .await
5400                    .map_err(|e| GraftRestoreFailed(format!("{e:#}")))?;
5401                self.state.event(
5402                    "graft",
5403                    format!("rolled back: {why}; the winner is untouched"),
5404                );
5405                GraftOutcome::RolledBack(why)
5406            }
5407        };
5408        self.state.graft = Some(GraftRecord {
5409            pre,
5410            post,
5411            lines,
5412            limit: None,
5413            agent: Some(agent_id),
5414            outcome,
5415            requested,
5416            adoption,
5417            adoption_error,
5418        });
5419        self.state.save()?;
5420        Ok(())
5421    }
5422
5423    // ----------------------------------------------------------------- fold
5424
5425    async fn fold_losers(&mut self) -> Result<()> {
5426        let Some(winner) = self.state.tally.as_ref().map(|t| t.winner) else {
5427            return Ok(());
5428        };
5429        if !self.state.candidate_preservation.is_empty() {
5430            bail!("candidate preservation incomplete; refusing cleanup");
5431        }
5432        let repo = self.state.repo.clone();
5433        let _coordination = self.coordinate(&repo).await?;
5434        let home = crate::run::home();
5435        let root = self.state.worktree_root();
5436        let isolated = crate::build_target::isolated(&self.state.config);
5437        let mut folded = Vec::new();
5438        for i in 0..self.state.candidates.len() {
5439            let c = &self.state.candidates[i];
5440            if c.label == winner || c.folded {
5441                continue;
5442            }
5443            let (wt, branch, label) = (c.worktree.clone(), c.branch.clone(), c.label);
5444            let target = fold_target(&home, &root, &wt, isolated);
5445            remove_preserved_worktree(&repo, &wt).await?;
5446            reclaim_fold_target(&home, target);
5447            if git::branch_exists(&repo, &branch).await?
5448                && !git::branch_delete(&repo, &branch).await?
5449            {
5450                bail!("candidate branch removal refused");
5451            }
5452            self.state.candidates[i].folded = true;
5453            self.state.save()?;
5454            folded.push(label.to_string());
5455        }
5456        // The judges are finished; their checkouts are pure cost from here.
5457        for j in 1..=self.roles.judges.len() {
5458            let wt = root.join(format!("judge-{j}"));
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        // The design-deliberation stage is finished by the time a tally
5467        // exists — same reasoning as the judges above.
5468        if self.state.config.graph.advise {
5469            for k in 1..=self.state.config.graph.advisors {
5470                let wt = root.join(format!("advisor-{k}"));
5471                if wt.exists() {
5472                    let target = fold_target(&home, &root, &wt, isolated);
5473                    remove_read_seat_worktree(&mut self.state, &wt).await?;
5474                    reclaim_fold_target(&home, target);
5475                    self.state.save()?;
5476                }
5477            }
5478        }
5479        if !folded.is_empty() {
5480            self.state
5481                .event("fold", format!("folded candidates {}", folded.join(", ")));
5482            self.state.save()?;
5483        }
5484        Ok(())
5485    }
5486
5487    // ------------------------------------------------------------ base sync
5488
5489    async fn hold_base_sync(&mut self) -> Result<bool> {
5490        self.hold_base_sync_as(None).await
5491    }
5492
5493    async fn hold_base_sync_kind(
5494        &mut self,
5495        kind: crate::base_sync_recovery::StopKind,
5496    ) -> Result<()> {
5497        self.hold_base_sync_as(Some(kind)).await?;
5498        Ok(())
5499    }
5500
5501    async fn hold_base_sync_as(
5502        &mut self,
5503        kind: Option<crate::base_sync_recovery::StopKind>,
5504    ) -> Result<bool> {
5505        if !self.state.base_sync_blocked() {
5506            self.state.base_sync_recovery.stop = None;
5507            return Ok(false);
5508        }
5509        let head = match self.state.winner() {
5510            Some(w) => git::rev_parse(&w.worktree, "HEAD")
5511                .await
5512                .unwrap_or_default(),
5513            None => String::new(),
5514        };
5515        if let Some(authorization) = self.state.base_sync_recovery.authorizations.last_mut()
5516            && !authorization.consumed
5517            && authorization.stop.head != head
5518        {
5519            authorization.refuse(format!(
5520                "retained HEAD changed from {} to {head}; inspect it and authorize again with --recover-base",
5521                authorization.stop.head
5522            ));
5523        }
5524        self.state.record_base_sync_stop(&head);
5525        if let Some(kind) = kind {
5526            self.state.base_sync_recovery.stop.as_mut().unwrap().kind = kind.clone();
5527            if let Some(stop) = self.state.base_sync_recovery.stops.last_mut() {
5528                stop.kind = kind;
5529            }
5530        }
5531        self.state.save()?;
5532        Ok(true)
5533    }
5534
5535    /// Land the winner's tree on the current tip of `<remote>/<base>` before
5536    /// anything verifies it.
5537    ///
5538    /// `verify.e2e`, `verify.gate` and every reviewer in [`Self::review_loop`]
5539    /// read whatever is checked out in the winner's worktree. Left alone that
5540    /// tree stays rooted at `base_commit` - the base as [`resolve_base`] saw
5541    /// it when the run *branched* - and a run takes long enough that the base
5542    /// has usually moved by the time it gets here. A gate that ran there
5543    /// answers "green on the commit this run started from", not "green on
5544    /// what is about to land", and the difference showed up three times in
5545    /// one day as a green run whose merge would have reverted a file another
5546    /// pull request had already landed.
5547    ///
5548    /// Reuses [`crate::rebase::rebase_with_fixer`], the same routine
5549    /// `land::Step::Rebase` calls, rather than a second implementation of the
5550    /// same idea: a throwaway worktree, nothing runs in the primary tree, and
5551    /// a second rebase path is exactly the kind of drift `resolve_base`'s own
5552    /// doc warns about ("two answers to a question nobody notices until a
5553    /// diff is wrong").
5554    ///
5555    /// Foreign-checkout reviews instead merge the base into the owned shadow
5556    /// worktree, preserving the ancestry required for fast-forward delivery.
5557    /// A conflicting merge is aborted and held for operator resolution.
5558    ///
5559    /// A conflict is not the end of the road: the standing rebase is handed
5560    /// to the fixer seat, at most `graph.review_rounds` times, counted in
5561    /// `state.rebase_fixes` (so it survives a park/resume and is shared with
5562    /// land). Once it finishes, review and the gate run as usual on the
5563    /// rebased tree, which is where a breakage the new base caused is caught
5564    /// by the ordinary gate-fix round. magi resolves nothing itself.
5565    ///
5566    /// Two different bounds, easy to confuse: [`BASE_SYNC_ROUNDS`], counted in
5567    /// the current durable recovery interval, bounds how often the base is
5568    /// synchronized during active recovery (lifetime attempts remain evidence).
5569    /// `rebase_fixes` is how many times a *conflict* was given to a fixer. When the fixer cannot finish the
5570    /// rebase the branch is restored, `state.base_sync.conflict` is set with
5571    /// what was tried (rounds spent, paths still conflicted) and the branch
5572    /// and worktree stay exactly as they were - untouched, for a person to
5573    /// look at - which is also what makes re-entering this function
5574    /// afterwards a no-op instead of a second attempt at the same wall. A
5575    /// push failure ends the same way.
5576    async fn sync_to_base(&mut self) -> Result<()> {
5577        if self.state.status == RunStatus::AlreadyInBase {
5578            return Ok(());
5579        }
5580        self.hold_base_sync().await?;
5581        let conflicted = self
5582            .state
5583            .base_sync
5584            .as_ref()
5585            .is_some_and(|s| s.conflict.is_some());
5586        let Some(winner) = self.state.winner().cloned() else {
5587            return Ok(());
5588        };
5589
5590        crate::worktree_clean::resume_pending(&mut self.state, &winner.worktree).await?;
5591
5592        let repo = self.state.repo.clone();
5593        let remote = self.state.config.merge.remote.clone();
5594        let base_branch = self.state.base_branch.clone();
5595        let tracking = format!("{remote}/{base_branch}");
5596
5597        let fetched_base =
5598            matches!(git::fetch(&repo, &remote, &base_branch).await, Ok(o) if o.ok());
5599        // No network, or the remote never had this branch: the run already
5600        // started from a fetched `<remote>/<base>` (`resolve_base` refuses
5601        // otherwise), and one that got this far is not blocked by a fetch
5602        // that fails now. It just has no newer tip to compare against.
5603        let Ok(mut tip) = git::rev_parse(&repo, &tracking).await else {
5604            return Ok(());
5605        };
5606
5607        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
5608        self.state.ensure_base_episode();
5609        let mut pending = self
5610            .state
5611            .base_sync_recovery
5612            .operations
5613            .last()
5614            .filter(|o| !o.finished)
5615            .cloned();
5616        let scratch = self.state.dir().join("base-sync");
5617        if git::rebase_in_progress(&scratch).await {
5618            // Older resource stops predate operation reservations. Import the
5619            // standing Git operation, never retarget it to today's main.
5620            if pending.is_none()
5621                && self.state.base_sync_recovery.operations.is_empty()
5622                && !conflicted
5623                && crate::rebase::saved_base_identity(&scratch, &winner.branch)
5624                    .await
5625                    .ok()
5626                    .as_deref()
5627                    == Some(head.as_str())
5628                && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
5629                && git::is_clean(&winner.worktree).await?
5630            {
5631                let saved_tip = crate::rebase::rebase_target(&scratch).await?;
5632                if self.state.base_sync.is_none() {
5633                    self.state.base_sync = Some(BaseSync {
5634                        tip: saved_tip.clone(),
5635                        behind: 0,
5636                        attempts: 0,
5637                        conflict: None,
5638                        already_in: None,
5639                    });
5640                }
5641                self.state.reserve_base_operation(&head, &saved_tip);
5642                self.state.event(
5643                    "base-recovery",
5644                    "imported standing legacy rebase as a spent synchronization reservation",
5645                );
5646                self.state.save()?;
5647                pending = self.state.base_sync_recovery.operations.last().cloned();
5648            }
5649            let expected = pending.as_ref().map(|op| op.tip.as_str());
5650            if expected.is_none()
5651                || crate::rebase::rebase_target(&scratch).await.as_deref().ok() != expected
5652            {
5653                let why = "saved scratch rebase targets a different base; inspect the retained rebase before resuming";
5654                if self.state.base_sync.is_none() {
5655                    self.state.base_sync = Some(BaseSync {
5656                        tip: tip.clone(),
5657                        behind: 0,
5658                        attempts: 0,
5659                        conflict: None,
5660                        already_in: None,
5661                    });
5662                }
5663                self.state.base_sync.as_mut().unwrap().conflict = Some(why.into());
5664                self.state.event("land", why);
5665                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Unknown)
5666                    .await?;
5667                return Ok(());
5668            }
5669        }
5670        if let Some(op) = &pending {
5671            // A replay may add the pinned base's commits, never foreign work.
5672            let mut replay_proven =
5673                head == op.head || op.validated_head.as_deref() == Some(head.as_str());
5674            if !replay_proven && scratch.exists() && !git::rebase_in_progress(&scratch).await {
5675                let wait = repository_wait(&self.state, None);
5676                let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
5677                match crate::rebase::recover_completed_base(&self.state, &scratch, &winner.branch, op, &head).await {
5678                    Ok(true) => {
5679                        self.state.base_sync_recovery.operations.last_mut().unwrap().validated_head = Some(head.clone());
5680                        self.state.save()?;
5681                        git::worktree_remove(&repo, &scratch).await.ok();
5682                        replay_proven = true;
5683                    }
5684                    Ok(false) => self.state.event("base-recovery", "completed scratch failed result validation; retained for inspection"),
5685                    Err(error) => self.state.event("base-recovery", format!("completed scratch could not be validated; retained for inspection: {error:#}")),
5686                }
5687            }
5688            if !replay_proven && git::is_ancestor(&repo, &op.tip, &head).await {
5689                if self.state.foreign_checkout.is_some() {
5690                    replay_proven = git::rev_parse(&repo, &format!("{head}^1"))
5691                        .await
5692                        .ok()
5693                        .as_deref()
5694                        == Some(op.head.as_str())
5695                        && git::rev_parse(&repo, &format!("{head}^2"))
5696                            .await
5697                            .ok()
5698                            .as_deref()
5699                            == Some(op.tip.as_str());
5700                } else if crate::reconcile::origin_missing(&repo, &head, &op.head)
5701                    .await
5702                    .is_ok_and(|m| m.is_empty())
5703                    && let Ok(added) =
5704                        crate::reconcile::origin_missing(&repo, &op.head, &head).await
5705                {
5706                    replay_proven = true;
5707                    for commit in added {
5708                        if !git::is_ancestor(&repo, &commit, &op.tip).await {
5709                            replay_proven = false;
5710                            break;
5711                        }
5712                    }
5713                    replay_proven &= git::commits_ahead(&repo, &op.tip, &head).await?
5714                        <= git::commits_ahead(&repo, &op.tip, &op.head).await?;
5715                }
5716            }
5717            // Never retarget an operation across a crash, even if main moved.
5718            // sync_to_head resets and cleans with -x, so even ignored untracked
5719            // files must stop recovery independently of the old tracked tree.
5720            if git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
5721                || (head != op.head
5722                    && !git::git(&winner.worktree, &["ls-files", "--others", "-z"])
5723                        .await?
5724                        .is_empty())
5725                || (!git::is_clean(&winner.worktree).await?
5726                    && !git::git_raw(&winner.worktree, &["diff", "--quiet", &op.head])
5727                        .await
5728                        .is_ok_and(|o| o.ok()))
5729                || !replay_proven
5730            {
5731                let why = format!(
5732                    "unfinished base synchronization {} has unrecognized branch/worktree state; inspect the retained branch and scratch rebase before resuming",
5733                    op.id
5734                );
5735                let sync = self
5736                    .state
5737                    .base_sync
5738                    .as_mut()
5739                    .context("reserved synchronization has no lifetime accounting")?;
5740                sync.conflict = Some(why.clone());
5741                self.state.event("land", why);
5742                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Unknown)
5743                    .await?;
5744                return Ok(());
5745            }
5746            if head != op.head {
5747                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
5748            }
5749            tip = op.tip.clone();
5750        }
5751        let behind = git::commits_ahead(&repo, &head, &tip).await.unwrap_or(0);
5752        let attempts = self.state.base_sync.as_ref().map_or(0, |s| s.attempts);
5753        if pending.is_none()
5754            && !conflicted
5755            && fetched_base
5756            && self
5757                .state
5758                .base_sync_recovery
5759                .episodes
5760                .last()
5761                .is_some_and(|e| e.boundary.is_some())
5762            && let Some(task) = self.state.origin.as_ref().and_then(|o| o.task.clone())
5763            && let Ok(owner) = crate::queue::Queue::open().get(&task)
5764            && owner.execution_runs().last() == Some(&self.state.id)
5765            && owner.status != crate::queue::TaskStatus::Done
5766            && !owner.fresh_start
5767            && owner.review_branch.is_none()
5768            && crate::daemon::compatible_run_instruction(&self.state, &owner)
5769            && let Some(approval) = owner.resumption.as_ref()
5770            && approval.instruction == owner.instruction
5771            && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
5772            && git::is_clean(&winner.worktree).await?
5773            && self.state.renew_base_episode(&task, approval, &head, &tip)
5774        {
5775            self.state.event("base-recovery", "opened bounded synchronization interval after owner-approved infrastructure recovery");
5776            self.state.save()?;
5777        }
5778
5779        // Before any rebase, and before a recorded conflict is honoured: a
5780        // branch whose change reached the base under other commit ids has
5781        // nothing to rebase and nothing to conflict with, and a run that
5782        // already stopped on that phantom conflict recovers here on resume.
5783        // `behind == 0` with head == tip is a branch the base has since taken
5784        // in whole, whether or not a conflict was ever recorded: the ancestry
5785        // proof must still run (`classify` ignores a head still on the start
5786        // commit).
5787        if (behind > 0 || conflicted || head == tip)
5788            && self
5789                .settle_already_in(&winner.branch, &tip, &head, attempts, behind)
5790                .await?
5791        {
5792            return Ok(());
5793        }
5794        if conflicted && self.state.base_recovery_pending() {
5795            let authorization = self.state.base_sync_recovery.authorizations.last().unwrap();
5796            let owner =
5797                crate::queue::Queue::at(crate::run::home().join("queue")).get(&authorization.task);
5798            let owner_valid = owner.as_ref().is_ok_and(|t| {
5799                t.execution_runs().last() == Some(&self.state.id)
5800                    && t.status != crate::queue::TaskStatus::Done
5801                    && !t.fresh_start
5802                    && t.review_branch.is_none()
5803            });
5804            let invalidation = if !owner_valid {
5805                Some("latest task ownership changed")
5806            } else if !owner.as_ref().is_ok_and(|t| {
5807                authorization
5808                    .generation
5809                    .is_none_or(|g| t.resumption.as_ref().is_some_and(|r| r.generation == g))
5810            }) {
5811                Some("owner approval generation changed")
5812            } else if authorization.question.as_ref().is_some_and(|question| {
5813                !crate::base_recovery_control::decision_current(
5814                    &crate::queue::Queue::at(crate::run::home().join("queue")),
5815                    &self.state,
5816                    &authorization.task,
5817                    question,
5818                )
5819            }) {
5820                Some("recovery decision ownership, routing or stop evidence changed")
5821            } else if authorization.request.is_some()
5822                && !owner
5823                    .as_ref()
5824                    .is_ok_and(|t| t.operator_decided_at == authorization.decision)
5825            {
5826                Some("owner decision changed")
5827            } else if let Some(scope) = &authorization.scope {
5828                if scope.tip != tip {
5829                    Some("fetched base changed")
5830                } else if !self
5831                    .state
5832                    .base_sync_recovery
5833                    .episodes
5834                    .last()
5835                    .is_some_and(|e| e.id == scope.episode)
5836                {
5837                    Some("active synchronization interval changed")
5838                } else if !owner
5839                    .as_ref()
5840                    .is_ok_and(|t| t.instruction == scope.instruction)
5841                {
5842                    Some("task instruction changed")
5843                } else {
5844                    None
5845                }
5846            } else {
5847                None
5848            };
5849            if let Some(reason) = invalidation {
5850                let authorization = self
5851                    .state
5852                    .base_sync_recovery
5853                    .authorizations
5854                    .last_mut()
5855                    .unwrap();
5856                authorization.refuse(format!("{reason}; authorize again with --recover-base"));
5857                self.state.save()?;
5858                return Ok(());
5859            }
5860            if !fetched_base
5861                || git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
5862                || !git::is_clean(&winner.worktree).await?
5863                || !owner.is_ok_and(|t| t.execution_runs().last() == Some(&self.state.id))
5864            {
5865                return Ok(());
5866            }
5867        }
5868        let recovery = conflicted && self.state.consume_base_recovery(&head);
5869        if conflicted {
5870            // Consumption (including a refused changed HEAD) is durable before Git.
5871            self.state.save()?;
5872            if !recovery {
5873                return Ok(());
5874            }
5875        }
5876
5877        if behind == 0 {
5878            // A fixer-finished rebase moves the branch ref before the
5879            // winner's worktree is told (`sync_to_head` below). A run that
5880            // died in between resumes here with `behind == 0` and a tree still
5881            // holding the pre-rebase files, which review and the gate would
5882            // then read. That state is exactly: HEAD moved off the tip the
5883            // rebase started from, yet the tree is still identical to that
5884            // tip. A tree with edits of its own differs from it, so nothing
5885            // is thrown away.
5886            if let Some(from) = self
5887                .state
5888                .rebase_fixes
5889                .iter()
5890                .rev()
5891                .find_map(|r| r.from.clone())
5892                && from != head
5893                && git::git_raw(&winner.worktree, &["diff", "--quiet", &from])
5894                    .await
5895                    .is_ok_and(|o| o.ok())
5896            {
5897                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
5898            }
5899            // An earlier attempt may have rebased the branch locally and died
5900            // before pushing it (only the fresh-rebase arm below pushes).
5901            // Publish it now, so the plain push at PR time is not refused as
5902            // a non-fast-forward. A run already holding a recorded conflict
5903            // never reaches here; that case is out of scope.
5904            let conflict = self.publish_resumed_rebase(&winner.branch, &head).await;
5905            if let Some(why) = &conflict {
5906                self.state.status = RunStatus::Blocked;
5907                self.state.event("land", why.clone());
5908            }
5909            self.state.base_sync = Some(BaseSync {
5910                tip,
5911                behind: 0,
5912                attempts,
5913                conflict,
5914                already_in: None,
5915            });
5916            if pending.is_some() {
5917                self.state.finish_base_operation(Some(&head));
5918            }
5919            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Publication)
5920                .await?;
5921            self.state.save()?;
5922            return Ok(());
5923        }
5924
5925        if self.state.base_episode_used() >= BASE_SYNC_ROUNDS && pending.is_none() && !recovery {
5926            let why = format!(
5927                "{base_branch} moved {behind} commit(s) ahead of {} after {BASE_SYNC_ROUNDS} \
5928                 synchronization(s); synchronizing again would only race it",
5929                winner.branch
5930            );
5931            self.state.status = RunStatus::Blocked;
5932            self.state.base_sync = Some(BaseSync {
5933                tip,
5934                behind,
5935                attempts,
5936                conflict: Some(why.clone()),
5937                already_in: None,
5938            });
5939            self.state.event("land", why);
5940            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Exhausted)
5941                .await?;
5942            self.state.save()?;
5943            return Ok(());
5944        }
5945
5946        if self.state.foreign_checkout.is_some() {
5947            // Delivery to the operator's checkout is fast-forward only. A
5948            // rebase here would discard its saved head from our ancestry.
5949            let wait = repository_wait(&self.state, None);
5950            let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
5951            if self.state.base_sync.is_none() {
5952                self.state.base_sync = Some(BaseSync {
5953                    tip: tip.clone(),
5954                    behind,
5955                    attempts: 0,
5956                    conflict: None,
5957                    already_in: None,
5958                });
5959            }
5960            self.state.reserve_base_operation(&head, &tip);
5961            self.state.save()?;
5962            let merged = git::git_raw(
5963                &winner.worktree,
5964                &[
5965                    "-c",
5966                    "core.hooksPath=/dev/null",
5967                    "merge",
5968                    "--no-ff",
5969                    "--no-autostash",
5970                    "--no-edit",
5971                    "-m",
5972                    &format!("Merge {tracking} before verifying"),
5973                    &tip,
5974                ],
5975            )
5976            .await?;
5977            let conflict = if merged.ok() {
5978                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
5979                self.state.event(
5980                    "land",
5981                    format!("merged {tracking} into {} before verifying", winner.branch),
5982                );
5983                None
5984            } else {
5985                if git::rev_exists(&winner.worktree, "MERGE_HEAD").await {
5986                    git::git(&winner.worktree, &["merge", "--abort"]).await?;
5987                }
5988                let why = format!(
5989                    "could not merge {tracking} into {} without rewriting foreign checkout history: {}",
5990                    winner.branch,
5991                    merged.stderr.chars().take(600).collect::<String>()
5992                );
5993                self.state.status = RunStatus::Blocked;
5994                self.state.event("land", &why);
5995                Some(why)
5996            };
5997            let synced = conflict.is_none();
5998            let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
5999            self.state
6000                .finish_base_operation(synced.then_some(fresh.as_str()));
6001            let attempts = self.state.base_sync.as_ref().unwrap().attempts;
6002            self.state.base_sync = Some(BaseSync {
6003                tip,
6004                behind: if synced { 0 } else { behind },
6005                attempts,
6006                conflict,
6007                already_in: None,
6008            });
6009            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Conflict)
6010                .await?;
6011            self.state.save()?;
6012            return Ok(());
6013        }
6014
6015        self.state.event(
6016            "land",
6017            format!(
6018                "{base_branch} moved {behind} commit(s) ahead of {}; rebasing before verifying",
6019                winner.branch
6020            ),
6021        );
6022        self.state.save()?;
6023
6024        // The remote's copy of the branch, read now and only if the fetch
6025        // really succeeded (a stale tracking ref must never pin a lease). It is
6026        // pushed over after a rebase only when it is a commit this branch
6027        // already contains, by ancestry or by patch (an earlier rebase of ours
6028        // that never reached the remote): anything else is somebody else's work.
6029        let branch_tracking = format!("{remote}/{}", winner.branch);
6030        let fetched_branch = git::fetch(&repo, &remote, &winner.branch).await;
6031        let remote_tip = if self.state.task_pr_branch().is_none()
6032            && matches!(&fetched_branch, Ok(o) if o.ok())
6033        {
6034            git::rev_parse(&repo, &branch_tracking).await.ok()
6035        } else {
6036            None
6037        };
6038        // A remote tip this branch does not contain is somebody else's work:
6039        // rebasing would leave a local tip that can never be pushed. Stop
6040        // before touching anything and say so.
6041        if let Some(theirs) = &remote_tip
6042            && !git::is_ancestor(&repo, theirs, &head).await
6043            && !crate::reconcile::origin_missing(&repo, &head, theirs)
6044                .await
6045                .is_ok_and(|missing| missing.is_empty())
6046        {
6047            let why = format!(
6048                "{branch_tracking} ({}) has commits {} does not contain; not rebasing over \
6049                 them",
6050                short(theirs),
6051                winner.branch
6052            );
6053            self.state.status = RunStatus::Blocked;
6054            self.state.base_sync = Some(BaseSync {
6055                tip,
6056                behind,
6057                attempts,
6058                conflict: Some(why.clone()),
6059                already_in: None,
6060            });
6061            self.state.event("land", why);
6062            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Divergence)
6063                .await?;
6064            self.state.save()?;
6065            return Ok(());
6066        }
6067
6068        if self.state.base_sync.is_none() {
6069            self.state.base_sync = Some(BaseSync {
6070                tip: tip.clone(),
6071                behind,
6072                attempts: 0,
6073                conflict: None,
6074                already_in: None,
6075            });
6076        }
6077        let scratch = self.state.dir().join("base-sync");
6078        if let Err(error) = crate::rebase::prepare(&mut self.state, &scratch, &winner.branch).await
6079        {
6080            if error.is::<crate::repo_lock::ResourceBlocked>() {
6081                return Ok(());
6082            }
6083            return Err(error);
6084        }
6085        self.state.reserve_base_operation(&head, &tip);
6086        self.state.save()?;
6087        let rebased =
6088            match crate::rebase::rebase_prepared(&mut self.state, &scratch, &winner.branch, &tip)
6089                .await
6090            {
6091                Ok(crate::rebase::Rebased::Applied) => Ok(None),
6092                Ok(crate::rebase::Rebased::Stopped(why)) => Ok(Some(why)),
6093                Err(e) => Err(e),
6094            };
6095        let attempts = self.state.base_sync.as_ref().unwrap().attempts;
6096        let stop_kind = match &rebased {
6097            Ok(None) => crate::base_sync_recovery::StopKind::Publication,
6098            Ok(Some(_)) => crate::base_sync_recovery::StopKind::Conflict,
6099            Err(_) => crate::base_sync_recovery::StopKind::Unknown,
6100        };
6101        match rebased {
6102            Ok(None) => {
6103                // The branch ref moved, but a worktree that already had it
6104                // checked out (the winner's) was not told; sync its index and
6105                // files before anything reads them.
6106                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6107                let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
6108                self.state.finish_base_operation(Some(&fresh));
6109                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
6110                let mut conflict = None;
6111                if let Some(pinned) = &remote_tip {
6112                    let pushed = git::push_pinned(&repo, &remote, &winner.branch, pinned).await;
6113                    match pushed {
6114                        Ok(o) if o.ok() => self.state.event(
6115                            "land",
6116                            format!("pushed rebased {} to {remote}", winner.branch),
6117                        ),
6118                        Ok(o) => {
6119                            conflict = Some(format!(
6120                                "rebased {} locally but {remote} refused the push (it moved                                  since {}; someone may have pushed): {}",
6121                                winner.branch,
6122                                short(pinned),
6123                                o.stderr.chars().take(600).collect::<String>()
6124                            ));
6125                        }
6126                        Err(e) => {
6127                            conflict = Some(format!(
6128                                "rebased {} locally but could not push it: {e:#}",
6129                                winner.branch
6130                            ));
6131                        }
6132                    }
6133                }
6134                if let Some(why) = &conflict {
6135                    self.state.status = RunStatus::Blocked;
6136                    self.state.event("land", why.clone());
6137                }
6138                self.state.base_sync = Some(BaseSync {
6139                    tip: tip.clone(),
6140                    behind: 0,
6141                    attempts,
6142                    conflict,
6143                    already_in: None,
6144                });
6145                self.state
6146                    .event("land", format!("rebased {} onto {tracking}", winner.branch));
6147            }
6148            Ok(Some(conflict)) => {
6149                self.state.finish_base_operation(None);
6150                let why = format!(
6151                    "{} conflicts with {tracking} and did not rebase: {}",
6152                    winner.branch,
6153                    conflict.chars().take(600).collect::<String>()
6154                );
6155                self.state.status = RunStatus::Blocked;
6156                self.state.base_sync = Some(BaseSync {
6157                    tip,
6158                    behind,
6159                    attempts,
6160                    conflict: Some(why.clone()),
6161                    already_in: None,
6162                });
6163                self.state.event("land", why);
6164            }
6165            // A refused Git write or a busy repository: nothing is wrong with
6166            // the branch. The scratch rebase stays standing and the run
6167            // resumes into it (`base_sync` must not claim a conflict).
6168            Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
6169                self.state.save()?;
6170                return Ok(());
6171            }
6172            Err(e) => {
6173                self.state.finish_base_operation(None);
6174                let why = format!("could not rebase {} onto {tracking}: {e:#}", winner.branch);
6175                self.state.status = RunStatus::Blocked;
6176                self.state.base_sync = Some(BaseSync {
6177                    tip,
6178                    behind,
6179                    attempts,
6180                    conflict: Some(why.clone()),
6181                    already_in: None,
6182                });
6183                self.state.event("land", why);
6184            }
6185        }
6186        if !self.state.base_sync_blocked() {
6187            self.state.base_sync_recovery.stop = None;
6188        }
6189        self.hold_base_sync_kind(stop_kind).await?;
6190        self.state.save()?;
6191        Ok(())
6192    }
6193
6194    /// Push a branch an earlier attempt rebased locally but never published,
6195    /// pinned to the remote tip read right after a successful fetch. Returns
6196    /// the reason when the run must stop; `None` when there was nothing to do
6197    /// (no remote copy, the same tip, or a remote copy this branch already
6198    /// contains, which the PR-time push fast-forwards) or the push succeeded.
6199    async fn publish_resumed_rebase(&mut self, branch: &str, head: &str) -> Option<String> {
6200        // Task competitions publish only after the PR text gate, to their
6201        // public head; never resurrect a candidate branch on the remote.
6202        if self.state.task_pr_branch().is_some() {
6203            return None;
6204        }
6205        let repo = self.state.repo.clone();
6206        let remote = self.state.config.merge.remote.clone();
6207        let fetched = git::fetch(&repo, &remote, branch).await;
6208        if !matches!(&fetched, Ok(o) if o.ok()) {
6209            return None;
6210        }
6211        let branch_tracking = format!("{remote}/{branch}");
6212        let theirs = git::rev_parse(&repo, &branch_tracking).await.ok()?;
6213        if theirs == head || git::is_ancestor(&repo, &theirs, head).await {
6214            return None;
6215        }
6216        if !crate::reconcile::origin_missing(&repo, head, &theirs)
6217            .await
6218            .is_ok_and(|missing| missing.is_empty())
6219        {
6220            return Some(format!(
6221                "{branch_tracking} ({}) has commits {branch} does not contain; not pushing over \
6222                 them",
6223                short(&theirs)
6224            ));
6225        }
6226        match git::push_pinned(&repo, &remote, branch, &theirs).await {
6227            Ok(o) if o.ok() => {
6228                self.state
6229                    .event("land", format!("pushed rebased {branch} to {remote}"));
6230                None
6231            }
6232            Ok(o) => Some(format!(
6233                "{branch} is rebased locally but {remote} refused the push (it moved since {}; \
6234                 someone may have pushed): {}",
6235                short(&theirs),
6236                o.stderr.chars().take(600).collect::<String>()
6237            )),
6238            Err(e) => Some(format!(
6239                "{branch} is rebased locally but could not be pushed: {e:#}"
6240            )),
6241        }
6242    }
6243
6244    /// End the run as [`RunStatus::AlreadyInBase`] when `head`'s whole change
6245    /// is already on `tip` under other commit ids ([`crate::already`]); returns
6246    /// whether it did.
6247    ///
6248    /// Checked only when the base is ahead of the branch. A failing check is
6249    /// "not proven" - the ordinary rebase path then decides - never a reason to
6250    /// stop the run.
6251    ///
6252    /// The remote copy of the branch is held to the same standard as the local
6253    /// one: if it carries a tip this worktree does not, that tip must itself be
6254    /// proven in the base, or nothing is settled (a pull request would
6255    /// otherwise be closed over commits nobody checked). The pull request is
6256    /// closed *before* the terminal status is saved; if that fails for a
6257    /// reason other than a refusal (no network, a `gh` error) the run is left
6258    /// `Blocked` with the reason as its conflict, which a resume retries -
6259    /// the same recovery a phantom conflict gets.
6260    async fn settle_already_in(
6261        &mut self,
6262        branch: &str,
6263        tip: &str,
6264        head: &str,
6265        attempts: usize,
6266        behind: usize,
6267    ) -> Result<bool> {
6268        let repo = self.state.repo.clone();
6269        let remote = self.state.config.merge.remote.clone();
6270        let start = self.state.base_commit.clone();
6271        let evidence = match crate::already::classify(&repo, tip, head, Some(&start)).await {
6272            Ok(Some(e)) => e,
6273            Ok(None) => return Ok(false),
6274            Err(e) => {
6275                tracing::warn!("already-in-base check for {branch}: {e:#}");
6276                return Ok(false);
6277            }
6278        };
6279        let mut verified = vec![head.to_owned()];
6280        let public_branch = self.state.pr_branch().unwrap_or(branch).to_owned();
6281        let fetched = git::fetch(&repo, &remote, &public_branch).await;
6282        if matches!(&fetched, Ok(o) if o.ok())
6283            && let Ok(theirs) = git::rev_parse(&repo, &format!("{remote}/{public_branch}")).await
6284            && theirs != head
6285        {
6286            match crate::already::classify(&repo, tip, &theirs, Some(&start)).await {
6287                Ok(Some(_)) => verified.push(theirs),
6288                _ => return Ok(false),
6289            }
6290        }
6291        let base_branch = self.state.base_branch.clone();
6292        let message = format!(
6293            "{branch} is already in {remote}/{base_branch} as {} ({} match); nothing left to \
6294             land",
6295            evidence.names(),
6296            evidence.proof.as_str()
6297        );
6298        let closed =
6299            crate::land::close_superseded_pr(&mut self.state, &public_branch, &evidence, &verified)
6300                .await;
6301        match closed {
6302            Ok(Ok(url)) => self
6303                .state
6304                .event("land", format!("closed {url}: superseded on {base_branch}")),
6305            Ok(Err(why)) => self
6306                .state
6307                .event("land", format!("did not close a pull request: {why}")),
6308            Err(e) => {
6309                let why = format!(
6310                    "{branch} is already in {remote}/{base_branch}, but its pull request could \
6311                     not be closed ({e:#}); resume to retry"
6312                );
6313                self.state.status = RunStatus::Blocked;
6314                self.state.base_sync = Some(BaseSync {
6315                    tip: tip.to_owned(),
6316                    behind,
6317                    attempts,
6318                    conflict: Some(why.clone()),
6319                    already_in: None,
6320                });
6321                self.state.event("land", why);
6322                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::ClosingIntegratedPr)
6323                    .await?;
6324                self.state.save()?;
6325                return Ok(true);
6326            }
6327        }
6328        self.state.status = RunStatus::AlreadyInBase;
6329        self.state.base_sync_recovery.stop = None;
6330        self.state.base_sync = Some(BaseSync {
6331            tip: tip.to_owned(),
6332            behind,
6333            attempts,
6334            conflict: None,
6335            already_in: Some(evidence),
6336        });
6337        self.state.event("land", message);
6338        self.state.save()?;
6339        self.settle_questions();
6340        Ok(true)
6341    }
6342
6343    /// The commit review and gate diff against: the tip [`Self::sync_to_base`]
6344    /// last landed the winner on, once it has run, else the commit the run
6345    /// branched from.
6346    ///
6347    /// Only [`Self::review_loop`] reads this. `prep`, `judge`, `deliberate`
6348    /// and `vote` all happen before there is a winner to rebase, so they
6349    /// compare every candidate against the branch point on purpose, and a
6350    /// base that moves after they are already done cannot change an answer
6351    /// they already gave.
6352    fn landing_base(&self) -> String {
6353        self.state
6354            .base_sync
6355            .as_ref()
6356            .map_or_else(|| self.state.base_commit.clone(), |s| s.tip.clone())
6357    }
6358
6359    // ------------------------------------------------------- operator fix
6360
6361    /// Route specific, already-recorded review findings to a fixer for a
6362    /// targeted, out-of-band fix on the winning branch — `magi fix`'s own
6363    /// entry point.
6364    ///
6365    /// Distinct from `review_loop`'s own fix step in three ways: it never
6366    /// runs a reviewer wave, it never spends review-round budget, and what
6367    /// happened is recorded as an [`OperatorFixRequest`] appended to
6368    /// [`RunState::operator_fixes`], never folded into a [`ReviewRound`] —
6369    /// see `run::SCHEMA`'s doc for schema 9 on why a reviewer's own severity
6370    /// and vote must never be rewritten to look like a manufactured blocking
6371    /// verdict.
6372    ///
6373    /// Only meaningful once review has actually concluded: `Ready` (handed
6374    /// off with findings still open, or simply concluded clean while minor
6375    /// findings sat unaddressed) or `Blocked` (round budget spent, or the
6376    /// gate failed). Everything else is refused: a run still in progress
6377    /// should simply be resumed, and a `Merged` run's branch has already
6378    /// landed — reopening *this* run's own record cannot change that, so the
6379    /// answer there is a fresh `magi review <branch>`.
6380    ///
6381    /// A real commit here re-verifies through a fresh, ordinary review-only
6382    /// run on the same branch ([`Self::review`]) rather than reopening this
6383    /// run's own `review_loop`: once any round in this run's history went
6384    /// clean, `review_conclusion` treats that as permanent by design (the
6385    /// same purity `gate`/`merge` rely on for safe reentry), so there is no
6386    /// way to force one more genuine reviewer wave out of *this* run without
6387    /// either rewriting history or weakening that guarantee for every other
6388    /// caller. A review-only run costs nothing extra — no implementation, no
6389    /// judging, no vote — and exercises the exact same review → verify →
6390    /// gate → (human) merge path, unmodified.
6391    pub async fn fix_selected(
6392        &mut self,
6393        ids: &[String],
6394        reason: &str,
6395        allow_stale: bool,
6396    ) -> Result<()> {
6397        let reason = reason.trim();
6398        if reason.is_empty() {
6399            bail!("a fix request needs a reason — that is the operator's own record of why");
6400        }
6401        if ids.is_empty() {
6402            bail!("no finding id given");
6403        }
6404        if !matches!(self.state.status, RunStatus::Ready | RunStatus::Blocked) {
6405            bail!(
6406                "run {} is `{}`; only a `ready` or `blocked` run — one whose review \
6407                 has already concluded — can be given a targeted fix. A run still \
6408                 in progress should simply be resumed; a `merged` run's branch has \
6409                 already landed, so its answer is a fresh `magi review <branch>`, \
6410                 not reopening this run's own record",
6411                self.state.id,
6412                self.state.status.as_str()
6413            );
6414        }
6415        // Reassignment shares this claim through its atomic task save. Check
6416        // the canonical run identity inside it, before preflight or any await.
6417        let _claim = FixClaim::acquire(&self.state.dir())?;
6418        crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &self.state.id)?;
6419        let home = crate::run::home();
6420        // The ordinary driver takes these same locks at admission. Keep the
6421        // execution lease through the fix, but never the owner lock across Git
6422        // or agent awaits.
6423        let execution = {
6424            let _owner = crate::pr_head::owner_lock(&home, &self.state.id)?;
6425            let disk = RunState::load(&self.state.id)?;
6426            crate::pr_head::ensure_owner(&disk)?;
6427            anyhow::ensure!(
6428                disk.status == self.state.status && disk.released_to.is_none(),
6429                "run changed since it was loaded; reload before fixing"
6430            );
6431            let claimed = crate::daemon::is_working_on(&home, &disk.id, Timestamp::now());
6432            anyhow::ensure!(
6433                disk.liveness_under(&home, claimed) == crate::run::Liveness::Dead,
6434                "run {} is currently being worked on or its ownership is unknown",
6435                disk.id
6436            );
6437            let lease = crate::driver::maintenance(&home, &disk.id).context(
6438                "run is currently being worked on or its execution lease is unavailable",
6439            )?;
6440            self.state = disk;
6441            lease
6442        };
6443        let Some(winner) = self.state.winner().cloned() else {
6444            bail!("run {} has no winning candidate to fix", self.state.id);
6445        };
6446        if !git::branch_exists(&self.state.repo, &winner.branch).await? {
6447            bail!(
6448                "branch `{}` no longer exists; this run cannot be extended",
6449                winner.branch
6450            );
6451        }
6452        // Resolve every id before spending anything — an unknown id refuses
6453        // the whole request rather than silently dropping it — and dedup
6454        // while keeping the operator's own order.
6455        let mut seen = BTreeSet::new();
6456        let mut findings = Vec::new();
6457        let mut missing = Vec::new();
6458        for id in ids {
6459            if !seen.insert(id.clone()) {
6460                continue;
6461            }
6462            match self.state.finding(id) {
6463                Some((round, rec, f)) => findings.push(OperatorFixFinding {
6464                    id: f.id.clone(),
6465                    severity: f.severity,
6466                    reviewer_vote: rec.vote,
6467                    round: round.round,
6468                    round_head: round.head.clone(),
6469                    reviewer: rec.reviewer,
6470                    agent: rec.agent.clone(),
6471                    file: f.file.clone(),
6472                    line: f.line,
6473                    title: f.title.clone(),
6474                    detail: f.detail.clone(),
6475                    outcome: OperatorFixOutcome::Pending,
6476                }),
6477                None => missing.push(id.clone()),
6478            }
6479        }
6480        if !missing.is_empty() {
6481            bail!(
6482                "unknown finding id(s): {}; nothing was changed",
6483                missing.join(", ")
6484            );
6485        }
6486
6487        let head_at_request = git::rev_parse(&self.state.repo, &winner.branch).await?;
6488        let stale_details: Vec<(String, String)> = findings
6489            .iter()
6490            .filter(|f| f.round_head != head_at_request)
6491            .map(|f| (f.id.clone(), f.round_head.clone()))
6492            .collect();
6493        let stale = !stale_details.is_empty();
6494        if stale && !allow_stale {
6495            bail!(
6496                "the branch has moved since some finding(s) were raised — {} — now \
6497                 at {}; pass --allow-stale to fix anyway, or re-run review first",
6498                stale_details
6499                    .iter()
6500                    .map(|(id, head)| format!("{id} (raised against {})", short(head)))
6501                    .collect::<Vec<_>>()
6502                    .join(", "),
6503                short(&head_at_request)
6504            );
6505        }
6506
6507        let request = OperatorFixRequest {
6508            requested_at: Timestamp::now(),
6509            reason: reason.to_owned(),
6510            findings,
6511            head_at_request: head_at_request.clone(),
6512            allow_stale,
6513            stale,
6514            fix: None,
6515            result_head: None,
6516            follow_up_review_run: None,
6517        };
6518        self.state.event(
6519            "fix",
6520            format!(
6521                "operator requested a targeted fix on {} finding(s) ({}): {reason}",
6522                request.findings.len(),
6523                request
6524                    .findings
6525                    .iter()
6526                    .map(|f| f.id.as_str())
6527                    .collect::<Vec<_>>()
6528                    .join(", "),
6529            ),
6530        );
6531        // Recorded now, before any worktree work or the fixer call itself —
6532        // and re-saved at each checkpoint below: a crash at any point after
6533        // this (mid fixer call, mid follow-up review) must not lose the fact
6534        // that this was requested, for which findings, and why. Everything
6535        // past this point reads and writes through `request_index` rather
6536        // than a local variable, since `request` itself is moved here.
6537        self.state.operator_fixes.push(request);
6538        self.state.save()?;
6539        let request_index = self.state.operator_fixes.len() - 1;
6540
6541        // A fresh, dedicated worktree for this one call, never the winner's
6542        // own worktree in place: that one may already be gone (folded away),
6543        // and reusing it in place would leave the branch checked out there
6544        // when the follow-up review below tries to check it out again. Freed
6545        // immediately after, either way — but only once confirmed clean:
6546        // `worktree_remove` is a `git worktree remove --force`, which would
6547        // otherwise discard uncommitted work left there by the operator or
6548        // another process before this had a chance to even look at it.
6549        let repo = self.state.repo.clone();
6550        let coordination = self.coordinate(&repo).await?;
6551        if winner.worktree.exists() {
6552            // Lockfiles a rescue commit withheld stay untracked on purpose and
6553            // are already recorded; they are not the operator's work to protect.
6554            let dirty = git::git(
6555                &winner.worktree,
6556                &["status", "--porcelain", "--untracked-files=all"],
6557            )
6558            .await?;
6559            let only_withheld = dirty.lines().all(|l| {
6560                l.strip_prefix("?? ")
6561                    .is_some_and(|p| self.state.withheld.iter().any(|w| w.path == p))
6562            });
6563            if !only_withheld {
6564                bail!(
6565                    "`{}` has uncommitted changes; refusing to touch it — commit or \
6566                     discard them first",
6567                    winner.worktree.display()
6568                );
6569            }
6570            git::worktree_remove(&self.state.repo, &winner.worktree)
6571                .await
6572                .ok();
6573        }
6574        let fix_worktree = self.state.worktree_root().join("operator-fix");
6575        let fix_worktree_s = fix_worktree.to_string_lossy().to_string();
6576        git::git(
6577            &self.state.repo,
6578            &["worktree", "add", &fix_worktree_s, winner.branch.as_str()],
6579        )
6580        .await
6581        .with_context(|| format!("checking out `{}` for the fix", winner.branch))?;
6582        if !git::is_clean(&fix_worktree).await? {
6583            git::worktree_remove(&self.state.repo, &fix_worktree)
6584                .await
6585                .ok();
6586            bail!(
6587                "`{}` has uncommitted changes; refusing to start a fix on a dirty tree",
6588                winner.branch
6589            );
6590        }
6591        let repo_for_setup = self.state.repo.clone();
6592        let setup = match ensure_setup_config(&mut self.state, &repo_for_setup).await {
6593            Ok(()) => {
6594                worktree_setup::prepare_with(
6595                    &self.state.config,
6596                    &repo_for_setup,
6597                    &fix_worktree,
6598                    crate::build_target::Coordination::Held(coordination.as_ref()),
6599                )
6600                .await
6601            }
6602            Err(e) => Err(e),
6603        };
6604        if let Err(e) = setup {
6605            git::worktree_remove(&self.state.repo, &fix_worktree)
6606                .await
6607                .ok();
6608            return Err(e);
6609        }
6610
6611        // This explicit operator request retries availability independently
6612        // of execute(); the previous call has already saved and cleaned up.
6613        self.state.resource_block = None;
6614
6615        let run_id = self.state.id.clone();
6616        let prompts = self.state.config.prompts.clone();
6617        let language = self.state.config.graph.language.clone();
6618        let sessions = self.state.config.graph.sessions;
6619        let artifacts = agent::artifacts_dir(&self.state.dir());
6620        let finding_list: Vec<Finding> = self.state.operator_fixes[request_index]
6621            .findings
6622            .iter()
6623            .map(|f| Finding {
6624                id: f.id.clone(),
6625                severity: f.severity,
6626                file: f.file.clone(),
6627                line: f.line,
6628                title: f.title.clone(),
6629                detail: f.detail.clone(),
6630            })
6631            .collect();
6632        let fix_prompt = prompt::operator_fix_in(
6633            &self.state.instruction,
6634            &finding_list,
6635            reason,
6636            &stale_details,
6637            &head_at_request,
6638            &language,
6639            &self.state.config.graph.github_language,
6640        );
6641        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
6642        drop(coordination);
6643        let (job, seat, out) = self
6644            .ask_fixer(&winner, "fix", None, |spec, seat| SeatJob {
6645                prompt: fix_prompt.clone(),
6646                spec,
6647                seat,
6648                cwd: fix_worktree.clone(),
6649                timeout,
6650                allow_write: true,
6651                sessions,
6652                artifacts: artifacts.clone(),
6653                stem: "operator-fix".to_owned(),
6654                handover: None,
6655            })
6656            .await;
6657        let agent_id = seat.agent.clone();
6658
6659        let mut fix = FixRecord {
6660            agent: agent_id,
6661            addressed: Vec::new(),
6662            rejected: Vec::new(),
6663            notes: String::new(),
6664            committed: false,
6665            failed: None,
6666            duration_ms: 0,
6667            continuation: None,
6668        };
6669        let mut final_seat = seat.clone();
6670        match out {
6671            AgentOutcome::Ok(o) => {
6672                fix.duration_ms = o.duration_ms;
6673                let parsed = verdict::extract_json::<FixReport>(&o.text);
6674                let incomplete_reason = match &parsed {
6675                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
6676                        "the reply parsed, but it reported a command whose own CLI \
6677                         never confirmed an exit status"
6678                            .to_owned(),
6679                    ),
6680                    Ok(_) => None,
6681                    Err(e) => Some(e.to_string()),
6682                };
6683                match incomplete_reason {
6684                    None => {
6685                        let report = parsed.expect("checked Ok above");
6686                        fix.addressed = report.addressed;
6687                        fix.rejected = report.rejected;
6688                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
6689                    }
6690                    Some(reason) => {
6691                        let (resumed_seat, resolved, failure, cont) = self
6692                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, 0)
6693                            .await;
6694                        fix.duration_ms += cont.cumulative_wait_ms;
6695                        fix.continuation = Some(cont);
6696                        final_seat = resumed_seat;
6697                        match resolved {
6698                            Some(report) => {
6699                                fix.addressed = report.addressed;
6700                                fix.rejected = report.rejected;
6701                                fix.notes =
6702                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
6703                            }
6704                            None => fix.failed = failure,
6705                        }
6706                    }
6707                }
6708            }
6709            AgentOutcome::Dropped(o) => {
6710                fix.duration_ms = o.duration_ms;
6711                let why = o
6712                    .dropped
6713                    .as_ref()
6714                    .map(|d| d.why.as_str())
6715                    .unwrap_or("the CLI ended the stream without delivering its answer");
6716                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
6717            }
6718            AgentOutcome::Quota(o) => {
6719                self.state.quota.push(QuotaLoss::from_report(
6720                    final_seat.key.clone(),
6721                    "fix",
6722                    o.quota.as_ref(),
6723                ));
6724                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
6725            }
6726            AgentOutcome::Failed(e) => fix.failed = Some(e),
6727            AgentOutcome::ResourceBlocked(e) => {
6728                fix.failed = Some(format!("the fixer was not started: {e}"));
6729            }
6730        }
6731        // Even a deferred call must rescue edits, release the worktree and
6732        // finalize its record below so an explicit `magi fix` can retry.
6733        if fix.continuation.is_none() {
6734            fix.continuation = Some(ContinuationRecord::not_needed());
6735        }
6736        self.state.seats.insert(final_seat.key.clone(), final_seat);
6737
6738        let rescue_message = format!(
6739            "magi: operator-selected fix ({}) (uncommitted work)",
6740            self.state.operator_fixes[request_index]
6741                .findings
6742                .iter()
6743                .map(|f| f.id.as_str())
6744                .collect::<Vec<_>>()
6745                .join(", ")
6746        );
6747        let repo = self.state.repo.clone();
6748        let coordination = self.coordinate(&repo).await?;
6749        if let Ok(r) = git::rescue_commit(&fix_worktree, &rescue_message).await {
6750            self.state.note_withheld("fix", &r.withheld);
6751        }
6752        let after = git::rev_parse(&fix_worktree, "HEAD").await?;
6753        fix.committed = after != head_at_request;
6754        git::worktree_remove(&self.state.repo, &fix_worktree)
6755            .await
6756            .ok();
6757        drop(coordination);
6758
6759        self.state.event(
6760            "fix",
6761            match &fix.failed {
6762                Some(reason) => format!(
6763                    "operator fix: adoption report was lost ({reason}); {}",
6764                    if fix.committed {
6765                        "committed"
6766                    } else {
6767                        "NO new commit"
6768                    }
6769                ),
6770                None => format!(
6771                    "operator fix: {} addressed, {} rejected, {}",
6772                    fix.addressed.len(),
6773                    fix.rejected.len(),
6774                    if fix.committed {
6775                        "committed"
6776                    } else {
6777                        "NO new commit"
6778                    }
6779                ),
6780            },
6781        );
6782
6783        // Every selected finding gets an outcome — never left `Pending` once
6784        // the fixer's own turn is over. A report that never came back at all
6785        // marks every one of them `Unreported`, not silently "not addressed":
6786        // quota, a dropped stream, or an exhausted continuation are gaps in
6787        // the report, not evidence about the finding itself (see [`SCHEMA`]'s
6788        // doc for schema 9 and [`OperatorFixOutcome::Unreported`]).
6789        for f in &mut self.state.operator_fixes[request_index].findings {
6790            f.outcome = if fix.failed.is_some() {
6791                OperatorFixOutcome::Unreported
6792            } else if fix.addressed.contains(&f.id) {
6793                OperatorFixOutcome::Addressed
6794            } else if let Some(r) = fix.rejected.iter().find(|r| r.id == f.id) {
6795                OperatorFixOutcome::Rejected { why: r.why.clone() }
6796            } else {
6797                OperatorFixOutcome::Unreported
6798            };
6799        }
6800
6801        let committed = fix.committed;
6802        if committed {
6803            self.state.operator_fixes[request_index].result_head = Some(after.clone());
6804        }
6805        self.state.operator_fixes[request_index].fix = Some(fix);
6806        // Saved again now that the fixer's own outcome is final, on top of
6807        // the save right after the request was first pushed above.
6808        self.state.save()?;
6809        if self.state.resource_block.is_some() {
6810            return self.stop_for_resource();
6811        }
6812
6813        if committed {
6814            self.state.event(
6815                "fix",
6816                format!(
6817                    "operator fix committed {}; opening a follow-up review-only run",
6818                    short(&after)
6819                ),
6820            );
6821            self.state.save()?;
6822            drop(execution);
6823            // The new review owns its own execution. Update only its audit link
6824            // afterwards, since publication may have changed the old record.
6825            let event_count = self.state.events.len();
6826            let save_follow_up = |state: &mut RunState| -> Result<()> {
6827                let _owner = crate::pr_head::owner_lock(&home, &state.id)?;
6828                let _execution = crate::driver::maintenance(&home, &state.id)?;
6829                let mut disk = RunState::load(&state.id)?;
6830                disk.events.extend(state.events.drain(event_count..));
6831                let follow_up = state.operator_fixes[request_index]
6832                    .follow_up_review_run
6833                    .clone();
6834                disk.operator_fixes[request_index].follow_up_review_run = follow_up;
6835                disk.save()?;
6836                *state = disk;
6837                Ok(())
6838            };
6839            // The operator asked for the fix, and the follow-up serves whatever
6840            // task the run it follows served.
6841            let origin =
6842                Origin::operator().serving(self.state.origin.as_ref().and_then(|o| o.task.clone()));
6843            match Self::review(
6844                &self.state.repo,
6845                &winner.branch,
6846                self.state.config.clone(),
6847                origin,
6848            )
6849            .await
6850            {
6851                Ok(mut follow_up) => {
6852                    follow_up.state.event(
6853                        "start",
6854                        format!(
6855                            "requested by an operator fix on run {} for finding(s) {}",
6856                            self.state.id,
6857                            self.state.operator_fixes[request_index]
6858                                .findings
6859                                .iter()
6860                                .map(|f| f.id.as_str())
6861                                .collect::<Vec<_>>()
6862                                .join(", "),
6863                        ),
6864                    );
6865                    follow_up.state.save()?;
6866                    let follow_up_id = follow_up.state.id.clone();
6867                    // The follow-up is a run like any other: it belongs to the
6868                    // task of the run it follows, or to one filed for it.
6869                    let adopted = match crate::direct::adopt(
6870                        &follow_up.state,
6871                        self.state.origin.as_ref().and_then(|o| o.task.as_deref()),
6872                    ) {
6873                        Ok(a) => a,
6874                        Err(e) => {
6875                            // An ownerless run must not spend agent calls; it
6876                            // stays saved, and `magi run --resume` adopts it.
6877                            self.state.event(
6878                                "fix",
6879                                format!(
6880                                    "follow-up review {follow_up_id} got no owning task and was not executed: {e:#}"
6881                                ),
6882                            );
6883                            save_follow_up(&mut self.state)?;
6884                            return Ok(());
6885                        }
6886                    };
6887                    let executed = follow_up.execute().await;
6888                    let failure = executed.as_ref().err().map(|e| format!("{e:#}"));
6889                    if let Some(a) = adopted {
6890                        a.finish(&follow_up.state, executed);
6891                    }
6892                    if let Some(e) = failure {
6893                        self.state.event(
6894                            "fix",
6895                            format!(
6896                                "follow-up review {follow_up_id} did not complete cleanly: {e:#}"
6897                            ),
6898                        );
6899                    }
6900                    self.state.operator_fixes[request_index].follow_up_review_run =
6901                        Some(follow_up_id);
6902                }
6903                Err(e) => {
6904                    self.state.event(
6905                        "fix",
6906                        format!("committed the fix but could not open a follow-up review: {e:#}"),
6907                    );
6908                }
6909            }
6910            save_follow_up(&mut self.state)?;
6911        }
6912
6913        Ok(())
6914    }
6915
6916    // --------------------------------------------------------------- review
6917
6918    /// Ask the fixer chain once for one fix call: the agents [`fixer::attempts`]
6919    /// names, in order, each at most once, moving on only when the call
6920    /// advances (an error, a quota hit or nothing usable - the same decision
6921    /// point `agent::chain_advances` is for the other chained roles).
6922    ///
6923    /// Each agent gets its own seat from `Runner::seat`: the same agent
6924    /// continues its conversation (the winner's own implementer seat when it
6925    /// is the winner's author, now that the competition is over), another
6926    /// takes a fresh one so the full prompt is sent again. A handover is
6927    /// recorded under `node`, which is what makes the fallback stick for the
6928    /// rest of the run (see `crate::fixer`). Only the last attempt's outcome
6929    /// is returned, so an exhausted chain reads exactly like a single failed
6930    /// fixer: one quota loss, the same wording, the same refund. An earlier
6931    /// attempt's edits are left in the tree and judged, with the final
6932    /// attempt's, by what git says afterwards.
6933    ///
6934    /// Returns the job that produced the outcome, for `continue_fix_report`.
6935    async fn ask_fixer(
6936        &mut self,
6937        winner: &Candidate,
6938        node: &'static str,
6939        round: Option<usize>,
6940        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
6941    ) -> (SeatJob, SeatState, AgentOutcome) {
6942        let attempts = fixer::attempts(&self.state, &self.roles, winner);
6943        self.ask_fixer_among(attempts, node, round, None, build)
6944            .await
6945    }
6946
6947    /// [`Self::ask_fixer`] over an explicit attempt list. `restore` is a
6948    /// worktree and a commit: before the next agent is asked after one that
6949    /// did not satisfy the call, the worktree is put back on that commit, so
6950    /// a failed agent's partial edits are not carried into the next one.
6951    async fn ask_fixer_among(
6952        &mut self,
6953        attempts: Vec<(AgentSpec, String)>,
6954        node: &'static str,
6955        round: Option<usize>,
6956        restore: Option<(&Path, &str)>,
6957        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
6958    ) -> (SeatJob, SeatState, AgentOutcome) {
6959        let run_id = self.state.id.clone();
6960        let prompts = self.state.config.prompts.clone();
6961        let cache = self.state.config.cache_dir();
6962        let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
6963        let mut last = None;
6964        for (i, (spec, key)) in attempts.into_iter().enumerate() {
6965            let seat = self.seat(&key, &spec.id);
6966            let mut job = build(spec.clone(), seat);
6967            if i > 0 {
6968                job.stem = format!("{}-{}", job.stem, spec.id);
6969            }
6970            let ctx = WaveCtx {
6971                carry_seats: false,
6972                pauses: Some((&self.pause, &self.interrupt)),
6973                run: &run_id,
6974                node,
6975                prompts: &prompts,
6976                cache: cache.as_deref(),
6977                round,
6978            };
6979            let (seat, out) =
6980                run_one(job.clone(), Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
6981            // A resource block never advances the chain: the chosen agent
6982            // was not asked, so it must be the one asked again on resume.
6983            let advances = match &out {
6984                AgentOutcome::Ok(o) => agent::output_advances(o),
6985                AgentOutcome::ResourceBlocked(_) => false,
6986                _ => true,
6987            };
6988            if let Some(next) = ids.get(i + 1)
6989                && advances
6990            {
6991                self.state.seats.insert(seat.key.clone(), seat.clone());
6992                let class =
6993                    FailClass::of(&out).unwrap_or_else(|| FailClass::Other("unusable".to_owned()));
6994                let reason = match &out {
6995                    AgentOutcome::Ok(_) => "nothing usable".to_owned(),
6996                    other => fail_reason(other),
6997                };
6998                // A failed agent's edits must not reach the next one, and a
6999                // restore that did not work ends the chain: the call fails
7000                // and the caller's own (confirmed) restore decides.
7001                if let Some((wt, rev)) = restore
7002                    && let Err(e) = self.graft_restore(wt, rev).await
7003                {
7004                    let why =
7005                        format!("could not restore the worktree before the next fixer: {e:#}");
7006                    tracing::warn!("{why}");
7007                    let out = if e.is::<crate::repo_lock::ResourceBlocked>() {
7008                        AgentOutcome::ResourceBlocked(why)
7009                    } else {
7010                        AgentOutcome::Failed(why)
7011                    };
7012                    last = Some((job, seat, out));
7013                    break;
7014                }
7015                record_handover(
7016                    &mut self.state,
7017                    node,
7018                    &seat.key,
7019                    &spec.id,
7020                    next,
7021                    &class,
7022                    &reason,
7023                );
7024                continue;
7025            }
7026            last = Some((job, seat, out));
7027            break;
7028        }
7029        let (job, seat, out) = last.expect("the fixer chain always has an entry");
7030        if let AgentOutcome::Quota(output) = &out
7031            && node != "graft"
7032        {
7033            // Graft is best effort: its caller records the loss and restores
7034            // the pre-graft tree, then proceeds to review and gate.
7035            // Every fallback was tried. Machine outages cannot be repaired by
7036            // spending a fix round; use each caller's resumable resource path.
7037            let loss = QuotaLoss::from_report(seat.key.clone(), node, output.quota.as_ref());
7038            block_machine_outage(&mut self.state, node, std::slice::from_ref(&loss));
7039            self.state.quota.push(loss);
7040            self.state.seats.insert(seat.key.clone(), seat.clone());
7041            self.state.status = RunStatus::Blocked;
7042            return (
7043                job,
7044                seat,
7045                AgentOutcome::ResourceBlocked(
7046                    "fixer unavailable; restore agent availability and resume".into(),
7047                ),
7048            );
7049        }
7050        (job, seat, out)
7051    }
7052
7053    /// The one repair a verification-only failure earns (see
7054    /// [`crate::recovery`]), before the first review round of a run that took
7055    /// a branch over.
7056    ///
7057    /// Saved as started *before* the fixer is called, so a resume never
7058    /// repairs twice; a start found on re-entry is rolled back to the commit
7059    /// it began from. A failed or unusable fixer leaves the tree as it was and
7060    /// the review goes on over it, so the first round's own verification
7061    /// reports the failure again. The failure is never carried into a round as
7062    /// a result: verification is re-run on whatever commit this leaves.
7063    async fn recovery_repair(&mut self, winner: &Candidate) -> Result<()> {
7064        use crate::recovery::{Mode, Repair};
7065        if !self.state.reviews.is_empty() {
7066            return Ok(());
7067        }
7068        let Some(mut rec) = self.state.recovery.clone() else {
7069            return Ok(());
7070        };
7071        if rec.mode != Mode::VerifyRepair {
7072            return Ok(());
7073        }
7074        let wt = winner.worktree.clone();
7075        let mut head = git::rev_parse(&wt, "HEAD").await?;
7076        match rec.repair.clone() {
7077            Repair::Done { .. } => return Ok(()),
7078            Repair::WaitingForRestore { before } => {
7079                self.graft_restore(&wt, &before).await?;
7080                head = before;
7081                rec.repair = Repair::NotStarted;
7082                self.state.recovery = Some(rec.clone());
7083                self.state.save()?;
7084            }
7085            Repair::Started { before } => {
7086                // Interrupted: the unfinished edits are not trusted.
7087                // An unconfirmed rollback blocks the run with `Started` kept,
7088                // so a resume retries it; the tree is never reviewed as is.
7089                if let Err(e) = self.graft_restore(&wt, &before).await {
7090                    if e.is::<crate::repo_lock::ResourceBlocked>() {
7091                        return Err(e);
7092                    }
7093                    return self
7094                        .stop_recovery(rec, &before, format!("interrupted; rollback failed: {e:#}"))
7095                        .await;
7096                }
7097                rec.repair = Repair::Done {
7098                    before: before.clone(),
7099                    after: before,
7100                    committed: false,
7101                    failed: Some("interrupted; rolled back".to_owned()),
7102                };
7103                self.state
7104                    .event("recovery", "the repair was interrupted and rolled back");
7105                self.state.recovery = Some(rec);
7106                self.state.save()?;
7107                return Ok(());
7108            }
7109            Repair::NotStarted => {}
7110        }
7111        if crate::recovery::recheck(&mut rec, &head) {
7112            self.state.event("recovery", rec.summary());
7113            self.state.recovery = Some(rec);
7114            self.state.save()?;
7115            return Ok(());
7116        }
7117        rec.repair = Repair::Started {
7118            before: head.clone(),
7119        };
7120        self.state.recovery = Some(rec.clone());
7121        self.state.save()?;
7122
7123        let language = self.state.config.graph.language.clone();
7124        let sessions = self.state.config.graph.sessions;
7125        let artifacts = agent::artifacts_dir(&self.state.dir());
7126        let fix_prompt = prompt::recovery_fix(
7127            &self.state.instruction,
7128            &rec,
7129            self.state.config.graph.review_rounds,
7130            &language,
7131        );
7132        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
7133        self.state.event(
7134            "recovery",
7135            format!(
7136                "repair: the fixer starts from the failed verification on {}",
7137                short(&head)
7138            ),
7139        );
7140        let (_job, seat, out) = self
7141            .ask_fixer(winner, "fix", None, |spec, seat| SeatJob {
7142                prompt: fix_prompt.clone(),
7143                spec,
7144                seat,
7145                cwd: wt.clone(),
7146                timeout,
7147                allow_write: true,
7148                sessions,
7149                artifacts: artifacts.clone(),
7150                stem: "fix-recovery".to_owned(),
7151                handover: None,
7152            })
7153            .await;
7154        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
7155            rec.repair = Repair::WaitingForRestore { before: head };
7156            self.state.recovery = Some(rec);
7157            return self.stop_for_resource();
7158        }
7159        let failed = match &out {
7160            AgentOutcome::Ok(_) | AgentOutcome::ResourceBlocked(_) => None,
7161            AgentOutcome::Quota(o) => {
7162                self.state.quota.push(QuotaLoss::from_report(
7163                    seat.key.clone(),
7164                    "fix",
7165                    o.quota.as_ref(),
7166                ));
7167                Some("rate limited (quota); the fixer could not run".to_owned())
7168            }
7169            AgentOutcome::Dropped(_) => Some("the CLI dropped the stream".to_owned()),
7170            AgentOutcome::Failed(e) => Some(e.clone()),
7171        };
7172        self.state.seats.insert(seat.key.clone(), seat);
7173        let coordination = self.coordinate(&wt).await?;
7174        let failed = match failed {
7175            // The agent's partial edits are not kept.
7176            Some(why) => {
7177                if let Err(e) = git::restore_to(&wt, &head).await {
7178                    return self
7179                        .stop_recovery(rec, &head, format!("{why}; restore failed: {e:#}"))
7180                        .await;
7181                }
7182                Some(why)
7183            }
7184            None => {
7185                if let Ok(r) = git::rescue_commit(
7186                    &wt,
7187                    "magi: recovery repair of the failed verification (uncommitted work)",
7188                )
7189                .await
7190                {
7191                    self.state.note_withheld("fix", &r.withheld);
7192                }
7193                None
7194            }
7195        };
7196        let after = git::rev_parse(&wt, "HEAD").await?;
7197        drop(coordination);
7198        self.state.event(
7199            "recovery",
7200            match &failed {
7201                Some(why) => format!("repair: nothing kept ({why})"),
7202                None if after != head => {
7203                    format!("repair: committed {}", short(&after))
7204                }
7205                None => "repair: the fixer made no commit".to_owned(),
7206            },
7207        );
7208        rec.repair = Repair::Done {
7209            before: head.clone(),
7210            committed: after != head,
7211            after,
7212            failed,
7213        };
7214        self.state.recovery = Some(rec);
7215        self.state.save()?;
7216        Ok(())
7217    }
7218
7219    /// A repair whose rollback could not be confirmed: the run is blocked and
7220    /// resumable, and the unconfirmed state is never reviewed.
7221    async fn stop_recovery(
7222        &mut self,
7223        mut rec: crate::recovery::RecoveryRecord,
7224        head: &str,
7225        why: String,
7226    ) -> Result<()> {
7227        // `Started` stays recorded: a resume retries the restore.
7228        rec.repair = crate::recovery::Repair::Started {
7229            before: head.to_owned(),
7230        };
7231        self.state.recovery = Some(rec);
7232        self.state
7233            .event("recovery", format!("repair could not be undone: {why}"));
7234        self.state.status = RunStatus::Blocked;
7235        self.state.save()?;
7236        bail!("recovery repair could not be rolled back: {why}")
7237    }
7238
7239    async fn review_loop(&mut self) -> Result<()> {
7240        if self.hold_base_sync().await? {
7241            return Ok(());
7242        }
7243        loop {
7244            if self
7245                .state
7246                .base_sync
7247                .as_ref()
7248                .is_some_and(|s| s.conflict.is_some())
7249            {
7250                return Ok(());
7251            }
7252            if self.catchup_repairable() {
7253                let record = self.state.reviews.last().expect("repairable round").clone();
7254                let winner = self
7255                    .state
7256                    .winner()
7257                    .cloned()
7258                    .context("catch-up repair has no winner")?;
7259                if !self.fix_review_round(&winner, record).await? {
7260                    return Ok(());
7261                }
7262            }
7263            self.review_loop_pass().await?;
7264            if !self.catchup_repairable() {
7265                return Ok(());
7266            }
7267        }
7268    }
7269
7270    /// Derive an owed catch-up repair from durable round evidence, including
7271    /// reentry after a crash before the fixer was dispatched.
7272    fn catchup_repairable(&self) -> bool {
7273        self.state.reviews.len() < self.state.config.graph.review_rounds
7274            && self.state.reviews.last().is_some_and(|r| {
7275                !r.clean
7276                    && r.blocking == 0
7277                    && r.fix.is_none()
7278                    && r.e2e_status() == E2eStatus::Failed
7279            })
7280    }
7281
7282    async fn review_loop_pass(&mut self) -> Result<()> {
7283        // A base that would not rebase is a person's decision, not a review
7284        // round: nothing here would change the answer, and reviewers and a
7285        // fixer would be spending real budget on a tree that cannot land
7286        // regardless of what they find.
7287        if self
7288            .state
7289            .base_sync
7290            .as_ref()
7291            .is_some_and(|s| s.conflict.is_some())
7292        {
7293            return Ok(());
7294        }
7295        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
7296        // agent files with `magi task add` name the run that paid for it. The
7297        // prompt overlay is cloned alongside it because the waves borrow it
7298        // while `self` is mutably borrowed by the node's own bookkeeping.
7299        let run_id = self.state.id.clone();
7300        let prompts = self.state.config.prompts.clone();
7301        let Some(winner) = self.state.winner().cloned() else {
7302            return Ok(());
7303        };
7304        let granted_review = self
7305            .state
7306            .repair_grants
7307            .last()
7308            .filter(|g| g.phase == crate::repair_budget::Phase::Reviewing)
7309            .cloned();
7310        let fresh_review = granted_review
7311            .as_ref()
7312            .is_some_and(|g| self.state.reviews.len() == g.review_start);
7313        let max_rounds = granted_review
7314            .as_ref()
7315            .map_or(self.state.config.graph.review_rounds, |g| {
7316                g.review_start.saturating_add(1)
7317            });
7318        // A clean round, an exhausted round budget, or a stalled tree (see
7319        // `STAGNANT_LIMIT`) are all already-decided conclusions the moment
7320        // they are recorded — recomputed here, not read off `status`, so a
7321        // reentry into a run that already stopped restates the identical
7322        // verdict instead of silently handing back whatever an earlier node
7323        // in this same walk clobbered `status` to (a solo-candidate
7324        // `judge`/`deliberate` skip rewrites it on every reentry). The loop
7325        // below runs an empty range once the budget is spent, and would
7326        // otherwise fall through without touching `status` at all.
7327        if let Some(status) =
7328            review_conclusion(&self.state.reviews, max_rounds).filter(|_| !fresh_review)
7329        {
7330            // A reentry after a crash between the last round's save and
7331            // `stop_reviewing` reaches the hand-off here, not there.
7332            if status == RunStatus::Gating {
7333                self.record_contested_handoff();
7334            }
7335            self.state.status = status;
7336            self.state.save()?;
7337            return Ok(());
7338        }
7339        self.state.status = RunStatus::Reviewing;
7340        // A last recorded round whose own verification never resolved
7341        // (`ResourceBlocked` — the shared build cache, not the patch) is
7342        // never a concluded round, whatever the round budget says: starting
7343        // a fresh round on top of it would spend a whole new reviewer wave
7344        // re-reading an unchanged patch instead of just retrying the one
7345        // check that actually needs it, and once the budget is spent the
7346        // loop below has nothing left to do at all (its range is empty).
7347        // Retry that check directly instead, exactly the same retry
7348        // `stop_reviewing` already does for its own catch-up case.
7349        if !fresh_review
7350            && self.state.reviews.last().is_some_and(|r| {
7351                r.e2e_status() == E2eStatus::ResourceBlocked
7352                    || (r.e2e_status() == E2eStatus::Deferred && r.blocking == 0 && r.fix.is_none())
7353            })
7354        {
7355            let shell = self.state.config.shell();
7356            return self
7357                .stop_unresolved_review(
7358                    "the last round's own verification never resolved",
7359                    &shell,
7360                    &winner.worktree,
7361                )
7362                .await;
7363        }
7364
7365        if granted_review.is_none() {
7366            self.recovery_repair(&winner).await?;
7367        }
7368        if self.resource_halt()? {
7369            return Ok(());
7370        }
7371
7372        let repo = self.state.repo.clone();
7373        let root = self.state.worktree_root();
7374        let language = self.state.config.graph.language.clone();
7375        let sessions = self.state.config.graph.sessions;
7376        let artifacts = self.merge_repair_artifacts();
7377        let base = self.landing_base();
7378        let base_short = short(&base);
7379        let reviewers = self.roles.reviewers.clone();
7380        let shell = self.state.config.shell();
7381
7382        for round in (self.state.reviews.len() + 1)..=max_rounds {
7383            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
7384            let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
7385            let stat = git::diff_stat(&winner.worktree, &base, "HEAD").await?;
7386            // The prior round's own record, already persisted — never a
7387            // hand-carried variable of just its failing output: that is
7388            // exactly what let a round's e2e result drift out of sync with
7389            // which commit it was actually about (see `SCHEMA`'s doc for
7390            // schema 8). Judged against `head`, the commit reviewers are
7391            // about to look at now, so the summary always reads as "an
7392            // earlier head" here — this round's own patch has not been
7393            // checked yet.
7394            let prev_verification = self
7395                .state
7396                .reviews
7397                .last()
7398                .and_then(|r| r.verification_summary(&head));
7399            // Only the first round of a run that took a branch over: later
7400            // rounds have this run's own history.
7401            let prior_section = match (&self.state.recovery, round) {
7402                (Some(rec), 1) if self.state.reviews.is_empty() => {
7403                    let since = match (rec.mode, rec.reviewed_head.as_deref()) {
7404                        (crate::recovery::Mode::VerifyRepair, Some(reviewed)) => {
7405                            Some(crate::recovery::head_of(
7406                                &git::diff(&winner.worktree, reviewed, "HEAD")
7407                                    .await
7408                                    .unwrap_or_default(),
7409                                crate::recovery::SINCE_DIFF_MAX,
7410                            ))
7411                        }
7412                        _ => None,
7413                    };
7414                    Some(prompt::recovery_review(rec, since.as_deref()))
7415                }
7416                _ => None,
7417            };
7418
7419            // Each reviewer gets its own detached checkout of exactly this
7420            // commit: nobody can perturb the winner's tree, and the fixer can
7421            // keep working without racing a reviewer.
7422            let mut jobs = Vec::new();
7423            let coordination = if self.state.config.worktree.pre_clean.is_empty() {
7424                self.coordinate(&repo).await?
7425            } else {
7426                None
7427            };
7428            for (r, spec) in reviewers.iter().cloned().enumerate() {
7429                let wt = root.join(format!("review-{}", r + 1));
7430                // `clean -fdx` in a reset wipes setup's products, so every
7431                // round sets the seat up again.
7432                if wt.exists() {
7433                    crate::worktree_clean::reset(&mut self.state, &wt, Some(&head)).await?;
7434                } else {
7435                    let _lease = if self.state.config.worktree.pre_clean.is_empty() {
7436                        None
7437                    } else {
7438                        self.coordinate(&repo).await?
7439                    };
7440                    git::worktree_add_detached(&repo, &wt, &head).await?;
7441                }
7442                let _setup_lease = if self.state.config.worktree.pre_clean.is_empty() {
7443                    None
7444                } else {
7445                    self.coordinate(&repo).await?
7446                };
7447                self.setup_seat_worktree(
7448                    &repo,
7449                    &wt,
7450                    false,
7451                    coordination.as_ref().or(_setup_lease.as_ref()),
7452                )
7453                .await?;
7454                let seat_key = format!("review-{}", r + 1);
7455                // The seat starts the round on whoever answered it last, not
7456                // on the agent the spec names, so a failure is not re-paid.
7457                let spec = pick_start_spec(
7458                    &self.roles.reviewer_roster,
7459                    spec,
7460                    self.state.seat_history.get(&seat_key),
7461                );
7462                let seat = self.seat(&seat_key, &spec.id);
7463                jobs.push(SeatJob {
7464                    prompt: prompt::review(&prompt::ReviewCtx {
7465                        instruction: &self.state.instruction,
7466                        branch: &winner.branch,
7467                        base_short: &base_short,
7468                        stat: &stat,
7469                        patch: &patch,
7470                        verification: prev_verification.as_ref(),
7471                        prior: prior_section.as_deref(),
7472                        reviewers: reviewers.len(),
7473                        round,
7474                        rounds: max_rounds,
7475                        // A review-only run has no rankings, so nothing
7476                        // competed for this patch and the reviewer is told so.
7477                        competed: self.state.tally.as_ref().is_some_and(|t| t.rankings > 0),
7478                        lens: Lens::for_seat(r),
7479                        language: &language,
7480                        github_language: &self.state.config.graph.github_language,
7481                    }),
7482                    spec,
7483                    seat,
7484                    cwd: wt,
7485                    timeout: Duration::from_secs(self.state.config.graph.timeout_review),
7486                    allow_write: false,
7487                    sessions,
7488                    artifacts: artifacts.clone(),
7489                    stem: format!("review-{round}-{}", r + 1),
7490                    handover: None,
7491                });
7492            }
7493
7494            drop(coordination);
7495            self.state.event(
7496                "review",
7497                format!(
7498                    "round {round}: {} reviewers on {}",
7499                    jobs.len(),
7500                    short(&head)
7501                ),
7502            );
7503            let mut quota_losses = Vec::new();
7504            let review_retries = self.state.config.graph.retries;
7505            let review_cache = self.state.config.cache_dir();
7506            let ctx = WaveCtx {
7507                carry_seats: true,
7508                pauses: Some((&self.pause, &self.interrupt)),
7509                run: &run_id,
7510                node: "review",
7511                prompts: &prompts,
7512                cache: review_cache.as_deref(),
7513                round: Some(round),
7514            };
7515            let results = ask_json_wave::<Review>(
7516                jobs,
7517                Arc::clone(&self.sem),
7518                review_retries,
7519                &self.roles.reviewer_roster,
7520                &ctx,
7521                &mut quota_losses,
7522                &mut self.state,
7523                &|_: &Review| Ok(()),
7524            )
7525            .await;
7526            if self.state.resource_block.is_some() {
7527                return self.stop_for_resource();
7528            }
7529            // Counted before the move below: how many of *this* round's
7530            // reviewer seats were lost to their own rate limit, as opposed to
7531            // a crash, a timeout, or unparsable output — see `round_is_clean`.
7532            let round_quota_missing = quota_losses.len();
7533            self.state.quota.extend(quota_losses);
7534
7535            let mut records = Vec::new();
7536            let mut all_findings = Vec::new();
7537            for (r, (seat, res, attempts)) in results.into_iter().enumerate() {
7538                let agent_id = seat.agent.clone();
7539                self.state.seats.insert(seat.key.clone(), seat);
7540                let mut record = ReviewRecord {
7541                    reviewer: r + 1,
7542                    agent: agent_id,
7543                    summary: String::new(),
7544                    findings: Vec::new(),
7545                    vote: None,
7546                    failed: None,
7547                    duration_ms: 0,
7548                    // Set for both outcomes: `failed: Some(_)` with
7549                    // `attempts > 0` is a seat every retry still lost, not a
7550                    // recovered one — only `failed: None` with `attempts > 0`
7551                    // reads as "answered after a nudge" (see this field's own
7552                    // doc).
7553                    attempts,
7554                };
7555                match res {
7556                    Ok((review, out)) => {
7557                        // Sanitized here, at the point every other piece of
7558                        // agent prose in this file is (candidate summaries,
7559                        // deliberation turns, vote reasons): a reviewer's own
7560                        // words are the one thing about it that could name
7561                        // it, and reconsideration below broadcasts this same
7562                        // summary and these same findings to every other
7563                        // seat on the panel.
7564                        record.summary =
7565                            blind::sanitize_prose(&review.summary, &self.state.config.blind);
7566                        record.vote = Some(review.vote);
7567                        record.duration_ms = out.duration_ms;
7568                        for (n, mut f) in review.findings.into_iter().enumerate() {
7569                            // ids are magi's, never the agent's: the fixer's
7570                            // adoption report is keyed by them.
7571                            f.id = format!("R{round}-{}-{}", r + 1, n + 1);
7572                            f.title = blind::sanitize_prose(&f.title, &self.state.config.blind);
7573                            f.detail = blind::sanitize_prose(&f.detail, &self.state.config.blind);
7574                            // `file` is agent-supplied prose too, never
7575                            // checked against the real tree — the same
7576                            // exposure `title`/`detail` above have, just in
7577                            // a field easy to forget because it looks like a
7578                            // path rather than free text.
7579                            f.file = f
7580                                .file
7581                                .map(|file| blind::sanitize_prose(&file, &self.state.config.blind));
7582                            all_findings.push(f.clone());
7583                            record.findings.push(f);
7584                        }
7585                        self.state.event(
7586                            "review",
7587                            format!(
7588                                "round {round}: reviewer {} voted {} with {} finding(s)",
7589                                r + 1,
7590                                review.vote.label(),
7591                                record.findings.len()
7592                            ),
7593                        );
7594                    }
7595                    Err(e) => {
7596                        record.failed = Some(e.to_string());
7597                        self.state.event(
7598                            "review",
7599                            format!("round {round}: reviewer {} produced nothing: {e}", r + 1),
7600                        );
7601                    }
7602                }
7603                records.push(record);
7604            }
7605
7606            // Tally the round's votes and, if they split, spend the one
7607            // round of reconsideration the split -> deliberate -> revote
7608            // shape `judge`/`vote` use for the panel, sized down to what a
7609            // read-only review round can afford: one round, and a revote
7610            // rather than an argument, because the panel already wrote its
7611            // reasoning down as findings the first time around.
7612            let initial_votes: Vec<ReviewVote> = records.iter().filter_map(|r| r.vote).collect();
7613            let vote_split =
7614                initial_votes.len() > 1 && !initial_votes.iter().all(|v| *v == initial_votes[0]);
7615            let mut reconsideration: Vec<ReviewRevoteRecord> = Vec::new();
7616            if vote_split {
7617                self.state.event(
7618                    "review",
7619                    format!(
7620                        "round {round}: votes split ({}) — one round of reconsideration",
7621                        initial_votes
7622                            .iter()
7623                            .map(|v| v.label())
7624                            .collect::<Vec<_>>()
7625                            .join(", ")
7626                    ),
7627                );
7628                // Seats read every seat's findings and votes, still numbered
7629                // and never named — the same anonymity `review` itself keeps.
7630                let panel: Vec<ReviewSeatReport<'_>> = records
7631                    .iter()
7632                    .filter_map(|r| {
7633                        r.vote.map(|vote| ReviewSeatReport {
7634                            reviewer: r.reviewer,
7635                            vote,
7636                            summary: &r.summary,
7637                            findings: &r.findings,
7638                        })
7639                    })
7640                    .collect();
7641
7642                let mut jobs = Vec::new();
7643                let mut seats_at = Vec::new();
7644                for (r, spec) in reviewers.iter().cloned().enumerate() {
7645                    // A seat with no initial vote has nothing to reconsider
7646                    // from and stays absent, the same as it stayed absent
7647                    // from `panel` above.
7648                    if records[r].vote.is_none() {
7649                        continue;
7650                    }
7651                    let wt = root.join(format!("review-{}", r + 1));
7652                    let seat_key = format!("review-{}", r + 1);
7653                    let spec = self.occupant(&seat_key, spec);
7654                    let seat = self.seat(&seat_key, &spec.id);
7655                    // A seat with no live session has already forgotten the
7656                    // initial review's prompt — restate the patch it is
7657                    // voting on, the same as `deliberate`/`vote` do for a
7658                    // judge in the same position.
7659                    // The panel already carries this seat's own review and
7660                    // vote, so restating the patch makes the prompt whole for
7661                    // a seat handed to another agent.
7662                    let build = |with_patch: bool| {
7663                        prompt::review_reconsider(&ReviewReconsiderCtx {
7664                            instruction: &self.state.instruction,
7665                            reviewer: r + 1,
7666                            lens: Lens::for_seat(r),
7667                            panel: &panel,
7668                            patch: with_patch.then_some(ReviewPatch {
7669                                branch: &winner.branch,
7670                                base_short: &base_short,
7671                                stat: &stat,
7672                                patch: &patch,
7673                            }),
7674                            round,
7675                            rounds: max_rounds,
7676                            language: &language,
7677                        })
7678                    };
7679                    let full = build(true);
7680                    let prompt = if has_context(&spec, &seat, sessions) {
7681                        build(false)
7682                    } else {
7683                        full.clone()
7684                    };
7685                    jobs.push(SeatJob {
7686                        prompt,
7687                        spec,
7688                        seat,
7689                        cwd: wt,
7690                        timeout: Duration::from_secs(self.state.config.graph.timeout_review),
7691                        allow_write: false,
7692                        sessions,
7693                        artifacts: artifacts.clone(),
7694                        stem: format!("review-{round}-reconsider-{}", r + 1),
7695                        handover: Some(full),
7696                    });
7697                    seats_at.push(r);
7698                }
7699
7700                let mut recon_quota_losses = Vec::new();
7701                let recon_cache = self.state.config.cache_dir();
7702                let recon_ctx = WaveCtx {
7703                    carry_seats: true,
7704                    pauses: Some((&self.pause, &self.interrupt)),
7705                    run: &run_id,
7706                    node: "review",
7707                    prompts: &prompts,
7708                    cache: recon_cache.as_deref(),
7709                    round: Some(round),
7710                };
7711                let recon_results = ask_json_wave::<ReviewRevote>(
7712                    jobs,
7713                    Arc::clone(&self.sem),
7714                    review_retries,
7715                    &self.roles.reviewer_roster,
7716                    &recon_ctx,
7717                    &mut recon_quota_losses,
7718                    &mut self.state,
7719                    &|_: &ReviewRevote| Ok(()),
7720                )
7721                .await;
7722                if self.state.resource_block.is_some() {
7723                    return self.stop_for_resource();
7724                }
7725                self.state.quota.extend(recon_quota_losses);
7726
7727                for (&r, (seat, res, _attempts)) in seats_at.iter().zip(recon_results) {
7728                    let agent_id = seat.agent.clone();
7729                    self.state.seats.insert(seat.key.clone(), seat);
7730                    let mut rec = ReviewRevoteRecord {
7731                        reviewer: r + 1,
7732                        agent: agent_id,
7733                        vote: None,
7734                        reason: String::new(),
7735                        failed: None,
7736                    };
7737                    match res {
7738                        Ok((rv, _)) => {
7739                            rec.vote = Some(rv.vote);
7740                            rec.reason =
7741                                blind::sanitize_prose(&rv.reason, &self.state.config.blind);
7742                            self.state.event(
7743                                "review",
7744                                format!(
7745                                    "round {round}: reviewer {} revoted {}",
7746                                    r + 1,
7747                                    rv.vote.label()
7748                                ),
7749                            );
7750                        }
7751                        Err(e) => {
7752                            rec.failed = Some(e.to_string());
7753                            self.state.event(
7754                                "review",
7755                                format!("round {round}: reviewer {} did not revote: {e}", r + 1),
7756                            );
7757                        }
7758                    }
7759                    reconsideration.push(rec);
7760                }
7761            } else if initial_votes.len() > 1 {
7762                self.state.event(
7763                    "review",
7764                    format!(
7765                        "round {round}: votes agreed ({}) — no reconsideration",
7766                        initial_votes[0].label()
7767                    ),
7768                );
7769            }
7770
7771            let blocking = all_findings.iter().filter(|f| f.severity.blocks()).count();
7772            let verify_timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
7773            // A round that already has a blocking finding and a round left to
7774            // try is going back to the fixer no matter what `verify.e2e`
7775            // says, so running it first only spends the loop's slowest step
7776            // (minutes, for a Rust repo's full test suite) on a head about
7777            // to be rewritten. Deferred, never skipped: `verify.e2e` still
7778            // runs once a round has no blocking findings left (see
7779            // `round_is_clean`, which a deferred — empty — `e2e` can never
7780            // satisfy since `blocking` is nonzero whenever this branch is
7781            // taken), and `stop_reviewing` forces a real run before it will
7782            // ever read a deferred round as green.
7783            let defer_e2e =
7784                blocking > 0 && round < max_rounds && !self.state.config.graph.e2e_every_round;
7785            let (e2e, verify_retried, e2e_deferred, e2e_defer_reason) = if defer_e2e {
7786                let reason =
7787                    format!("{blocking} blocking finding(s) already required a fix this round");
7788                self.state.event(
7789                    "verify",
7790                    format!(
7791                        "round {round}: {reason} — e2e deferred to the fixer (reviewed head \
7792                         {}); it will run once a round has none left",
7793                        short(&head)
7794                    ),
7795                );
7796                (Vec::new(), false, true, Some(reason))
7797            } else {
7798                let e2e_commands = self.state.config.verify.e2e.clone();
7799                let cache_dir = self.state.config.cache_dir();
7800                let context = format!("round {round}");
7801                let wait = self.repository_wait();
7802                let (e2e, verify_retried) = with_cache_lease(
7803                    &mut self.state,
7804                    cache_dir.as_deref(),
7805                    "e2e",
7806                    "e2e",
7807                    &winner.worktree,
7808                    &head,
7809                    verify_timeout,
7810                    &context,
7811                    &wait,
7812                    |state, budget| {
7813                        let shell = shell.clone();
7814                        let e2e_commands = e2e_commands.clone();
7815                        let worktree = winner.worktree.clone();
7816                        let context = context.clone();
7817                        let winner = winner.clone();
7818                        async move {
7819                            if !e2e_commands.is_empty() {
7820                                // The suite certifies one SHA. Format before it
7821                                // runs, or the commit `pre_gate` makes at the
7822                                // gate owes the whole suite again.
7823                                Self::run_pre_gate(state, &winner).await;
7824                            }
7825                            run_e2e_with_retry(
7826                                state,
7827                                &shell,
7828                                &e2e_commands,
7829                                &worktree,
7830                                budget,
7831                                &context,
7832                                Some(round),
7833                            )
7834                            .await
7835                        }
7836                    },
7837                )
7838                .await?;
7839                (e2e, verify_retried, false, None)
7840            };
7841
7842            let expected = records.len();
7843            let answered = records.iter().filter(|r| r.failed.is_none()).count();
7844            let incomplete = answered < expected;
7845            let e2e_ok = e2e.iter().all(CommandOutcome::ok);
7846            let policy = self.state.config.graph.incomplete_review;
7847            let clean = round_is_clean(
7848                blocking,
7849                e2e_ok,
7850                answered,
7851                expected,
7852                round_quota_missing,
7853                policy,
7854            );
7855
7856            let mut round_record = ReviewRound {
7857                round,
7858                head: head.clone(),
7859                verified_head: None,
7860                verified_at: None,
7861                reviews: records,
7862                e2e,
7863                verify_retried,
7864                e2e_deferred,
7865                e2e_defer_reason,
7866                fix: None,
7867                blocking,
7868                answered,
7869                expected,
7870                clean,
7871                progressed: false,
7872                vote_split,
7873                reconsideration,
7874                verdict: None,
7875            };
7876            // The final vote per seat is its revote where reconsideration
7877            // ran and answered, its initial vote otherwise — the same
7878            // fallback `tally` uses for a judge whose private vote failed.
7879            round_record.verdict = ReviewVote::worst(
7880                round_record
7881                    .final_votes()
7882                    .into_iter()
7883                    .map(|(_, _, vote)| vote),
7884            );
7885            // Which commit and when magi actually attempted to check —
7886            // known the moment a command was dispatched against `head`,
7887            // whether or not it finished: a resource-blocked attempt still
7888            // targeted a specific commit at a specific time, and leaving
7889            // that unrecorded is exactly what made `verification_summary`
7890            // report a fresh attempt as "commit unknown ... recorded before
7891            // this was tracked", indistinguishable from a genuinely old,
7892            // untracked record. Only a deferred or unconfigured round never
7893            // ran at all and has nothing to record — see
7894            // `ReviewRound::verified_head`'s own doc.
7895            if !matches!(
7896                round_record.e2e_status(),
7897                E2eStatus::Deferred | E2eStatus::NotConfigured
7898            ) {
7899                // HEAD, not the reviewed `head`: `pre_gate` may have committed
7900                // mechanical fixes before the commands ran.
7901                round_record.verified_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
7902                round_record.verified_at = Some(Timestamp::now());
7903            }
7904
7905            if incomplete {
7906                let missing: Vec<String> = round_record
7907                    .reviews
7908                    .iter()
7909                    .filter(|r| r.failed.is_some())
7910                    .map(|r| format!("review-{}", r.reviewer))
7911                    .collect();
7912                self.state.event(
7913                    "review",
7914                    format!(
7915                        "round {round}: {answered}/{expected} reviewer(s) answered ({} never answered)",
7916                        missing.join(", ")
7917                    ),
7918                );
7919            }
7920
7921            if clean {
7922                self.state.event(
7923                    "review",
7924                    if incomplete && policy == IncompleteReviewPolicy::Warn {
7925                        format!(
7926                            "round {round}: clean (warn policy, incomplete panel) — no \
7927                             blocking findings from the seats that answered, verification green"
7928                        )
7929                    } else if incomplete {
7930                        format!(
7931                            "round {round}: clean ({} rate-limited reviewer(s) excluded from \
7932                             quorum) — no blocking findings from the seats that answered, \
7933                             verification green",
7934                            expected - answered
7935                        )
7936                    } else {
7937                        format!("round {round}: clean — no blocking findings, verification green")
7938                    },
7939                );
7940                self.state.reviews.push(round_record);
7941                self.state.status = RunStatus::Gating;
7942                self.state.save()?;
7943                return Ok(());
7944            }
7945
7946            // Nothing was raised and verification passed, but not every seat
7947            // answered and `round_is_clean` still refused to call it clean —
7948            // either a seat is missing for a reason other than its own quota
7949            // (a crash, a timeout, unparsable output — worth another try), or
7950            // every seat that could have answered lost its quota and nobody
7951            // is left to decide on: re-review rather than send the fixer
7952            // after a round with nothing to fix.
7953            if incomplete && blocking == 0 && e2e_ok {
7954                self.state.reviews.push(round_record);
7955                self.state.save()?;
7956                if round == max_rounds {
7957                    self.state.status = RunStatus::Blocked;
7958                    self.state.event(
7959                        "review",
7960                        format!(
7961                            "{} reviewer seat(s) never answered after {max_rounds} rounds; \
7962                             refusing to call it clean",
7963                            expected - answered
7964                        ),
7965                    );
7966                    return Ok(());
7967                }
7968                continue;
7969            }
7970
7971            // Nothing for the fixer to act on (`blocking == 0`) and the only
7972            // reason this round is not clean is that magi itself never got
7973            // a command to run — the shared build cache, not the patch (see
7974            // `CommandOutcome::resource_blocked`'s own doc). Sending that to
7975            // the fixer would invite a change to appease contention that has
7976            // nothing to do with the diff, and would leave this attempt
7977            // sitting in the next round's prompt as if it were about an
7978            // earlier, superseded commit rather than what it actually is:
7979            // the same head, still waiting to be checked. Wait for it the
7980            // same way the final round's own contention is already handled,
7981            // whatever round this happens to be.
7982            if blocking == 0 && round_record.e2e_status() == E2eStatus::ResourceBlocked {
7983                self.state.reviews.push(round_record);
7984                return self
7985                    .stop_unresolved_review(
7986                        "the round's own verification could not run",
7987                        &shell,
7988                        &winner.worktree,
7989                    )
7990                    .await;
7991            }
7992
7993            if round == max_rounds {
7994                self.state.reviews.push(round_record);
7995                return self
7996                    .stop_reviewing(
7997                        &format!(
7998                            "{blocking} blocking finding(s) still open after {max_rounds} round(s)"
7999                        ),
8000                        &shell,
8001                        &winner.worktree,
8002                    )
8003                    .await;
8004            }
8005
8006            if !self.fix_review_round(&winner, round_record).await? {
8007                return Ok(());
8008            }
8009        }
8010        Ok(())
8011    }
8012
8013    /// Run the same fix chain for an in-loop failure or a persisted catch-up failure.
8014    /// False means admission or continuation policy stopped the review loop.
8015    async fn fix_review_round(
8016        &mut self,
8017        winner: &Candidate,
8018        mut round_record: ReviewRound,
8019    ) -> Result<bool> {
8020        let round = round_record.round;
8021        let shell = self.state.config.shell();
8022        let step = self.run_fix_round(winner, &mut round_record).await?;
8023        if matches!(step, FixStep::Resource) {
8024            self.stop_for_resource()?;
8025            return Ok(false);
8026        }
8027        if self.state.reviews.len() < round {
8028            self.state.reviews.push(round_record);
8029        } else {
8030            self.state.reviews[round - 1] = round_record;
8031        }
8032        self.state.save()?;
8033
8034        // The fixer's own report never came back this round, even after
8035        // `continue_fix_report`'s own budget was spent on it — not an
8036        // ordinary "no report" (dropped stream, quota, plain failure),
8037        // which already reads that way and is left to the existing round
8038        // budget. Stopping here, rather than opening another round, is
8039        // what keeps a next reviewer/fixer wave from ever being
8040        // dispatched onto `winner.worktree` while whatever the seat's
8041        // last call may still have running there is unaccounted for: no
8042        // process liveness check exists (and none is being added — see
8043        // AGENTS.md/this task's own scope), so the only way to honour
8044        // "nothing starts before a valid report returns" is to not start
8045        // anything further on this worktree from this run at all.
8046        if matches!(step, FixStep::Recorded { report_lost: true }) {
8047            self.stop_reviewing(
8048                "the fixer's adoption report never came back, even after resuming its \
8049                         own seat; refusing to start another round against the same worktree \
8050                         while that is unresolved",
8051                &shell,
8052                &winner.worktree,
8053            )
8054            .await?;
8055            return Ok(false);
8056        }
8057
8058        let streak = self
8059            .state
8060            .reviews
8061            .iter()
8062            .rev()
8063            .take_while(|r| !r.progressed)
8064            .count();
8065        if streak >= STAGNANT_LIMIT {
8066            self.stop_reviewing(
8067                &format!("the tree has not moved against base for {streak} round(s) in a row"),
8068                &shell,
8069                &winner.worktree,
8070            )
8071            .await?;
8072            return Ok(false);
8073        }
8074        Ok(true)
8075    }
8076
8077    /// Execute the shared fixer chain; the caller owns persistence and stop policy.
8078    async fn run_fix_round(
8079        &mut self,
8080        winner: &Candidate,
8081        round_record: &mut ReviewRound,
8082    ) -> Result<FixStep> {
8083        let round = round_record.round;
8084        let max_rounds = self.state.config.graph.review_rounds;
8085        let run_id = self.state.id.clone();
8086        let prompts = self.state.config.prompts.clone();
8087        let language = self.state.config.graph.language.clone();
8088        let sessions = self.state.config.graph.sessions;
8089        let artifacts = self.merge_repair_artifacts();
8090        let base = self.landing_base();
8091        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
8092        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
8093        let this_round_verification = round_record.verification_summary(&head);
8094        let all_findings: Vec<_> = round_record
8095            .reviews
8096            .iter()
8097            .flat_map(|r| r.findings.iter().cloned())
8098            .collect();
8099        // Fix. The winner's own implementer seat continues its conversation:
8100        // the competition is over, so context is pure benefit now.
8101        let blocking_findings: Vec<_> = all_findings
8102            .iter()
8103            .filter(|f| f.severity.blocks())
8104            .cloned()
8105            .collect();
8106        let fix_prompt = prompt::fix_in(
8107            &self.state.instruction,
8108            &blocking_findings,
8109            this_round_verification.as_ref(),
8110            round,
8111            max_rounds,
8112            &language,
8113            &self.state.config.graph.github_language,
8114        );
8115        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
8116        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
8117        let (job, seat, out) = self
8118            .ask_fixer(winner, "fix", Some(round), |spec, seat| SeatJob {
8119                prompt: fix_prompt.clone(),
8120                spec,
8121                seat,
8122                cwd: winner.worktree.clone(),
8123                timeout,
8124                allow_write: true,
8125                sessions,
8126                artifacts: artifacts.clone(),
8127                stem: format!("fix-{round}"),
8128                handover: None,
8129            })
8130            .await;
8131        // Not asked: the round is not recorded (so a resume repeats it),
8132        // no fixer was handed over to, and the seat is left as it was.
8133        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
8134            return Ok(FixStep::Resource);
8135        }
8136        let agent_id = seat.agent.clone();
8137
8138        let mut fix = FixRecord {
8139            agent: agent_id,
8140            addressed: Vec::new(),
8141            rejected: Vec::new(),
8142            notes: String::new(),
8143            committed: false,
8144            failed: None,
8145            duration_ms: 0,
8146            continuation: None,
8147        };
8148        let mut continuation = ContinuationRecord::not_needed();
8149        let mut final_seat = seat.clone();
8150        match out {
8151            AgentOutcome::Ok(o) => {
8152                fix.duration_ms = o.duration_ms;
8153                let parsed = verdict::extract_json::<FixReport>(&o.text);
8154                // A parsed report standing next to a command this same
8155                // reply's own CLI never confirmed the exit status of is
8156                // not a resolved answer — the identical `CommandEvidence`
8157                // `state.jobs` renders, read here instead of only on
8158                // display, per the completion judgment and the shown
8159                // record needing to agree.
8160                let incomplete_reason = match &parsed {
8161                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
8162                        "the reply parsed, but it reported a command whose own CLI never \
8163                             confirmed an exit status"
8164                            .to_owned(),
8165                    ),
8166                    Ok(_) => None,
8167                    Err(e) => Some(e.to_string()),
8168                };
8169                match incomplete_reason {
8170                    None => {
8171                        let report = parsed.expect("checked Ok above");
8172                        fix.addressed = report.addressed;
8173                        fix.rejected = report.rejected;
8174                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
8175                    }
8176                    Some(reason) => {
8177                        let (resumed_seat, resolved, failure, cont) = self
8178                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, round)
8179                            .await;
8180                        fix.duration_ms += cont.cumulative_wait_ms;
8181                        continuation = cont;
8182                        final_seat = resumed_seat;
8183                        match resolved {
8184                            Some(report) => {
8185                                fix.addressed = report.addressed;
8186                                fix.rejected = report.rejected;
8187                                fix.notes =
8188                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
8189                            }
8190                            None => fix.failed = failure,
8191                        }
8192                    }
8193                }
8194            }
8195            // The CLI's raw error JSON is not a fix report to parse.
8196            AgentOutcome::Dropped(o) => {
8197                fix.duration_ms = o.duration_ms;
8198                let why = o
8199                    .dropped
8200                    .as_ref()
8201                    .map(|d| d.why.as_str())
8202                    .unwrap_or("the CLI ended the stream without delivering its answer");
8203                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
8204            }
8205            AgentOutcome::Quota(o) => {
8206                self.state.quota.push(QuotaLoss::from_report(
8207                    final_seat.key.clone(),
8208                    "fix",
8209                    o.quota.as_ref(),
8210                ));
8211                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
8212            }
8213            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => fix.failed = Some(e),
8214        }
8215        if self.state.resource_block.is_some() {
8216            self.state.seats.insert(final_seat.key.clone(), final_seat);
8217            return Ok(FixStep::Resource);
8218        }
8219        fix.continuation = Some(continuation);
8220        self.state.seats.insert(final_seat.key.clone(), final_seat);
8221        let coordination = self.coordinate(&winner.worktree).await?;
8222        if let Ok(r) = git::rescue_commit(
8223            &winner.worktree,
8224            &format!("magi: review round {round} fixes (uncommitted work)"),
8225        )
8226        .await
8227        {
8228            self.state.note_withheld("fix", &r.withheld);
8229        }
8230        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
8231        fix.committed = after != before;
8232        // Judged by what `git` says moved against base, never by the
8233        // fixer's own `addressed`/`rejected` count — see
8234        // `ReviewRound::progressed`. Propagated with `?`, the same as the
8235        // `patch` snapshot above: swallowing this error would default
8236        // `diff_after` to empty, which almost always differs from a
8237        // non-empty `patch` and reads as "progressed" — exactly backwards
8238        // for a `git` failure the stagnation check cannot see through.
8239        let diff_after = git::diff(&winner.worktree, &base, "HEAD").await?;
8240        drop(coordination);
8241        let progressed = diff_after != patch;
8242        let commit_note = if fix.committed {
8243            "committed"
8244        } else {
8245            "NO new commit"
8246        };
8247        let tree_note = if progressed {
8248            "changed vs base"
8249        } else {
8250            "unchanged vs base"
8251        };
8252        self.state.event(
8253            "fix",
8254            match &fix.failed {
8255                // Distinct on purpose from "0 addressed, 0 rejected": the
8256                // fixer's own diff still landed (blocking counts do keep
8257                // falling round over round), only its adoption report did
8258                // not come back, so this must never read like every
8259                // finding was reviewed and declined.
8260                Some(reason) => {
8261                    format!(
8262                        "round {round}: fixer's adoption report was lost ({reason}); \
8263                             {commit_note}, tree {tree_note}"
8264                    )
8265                }
8266                None => format!(
8267                    "round {round}: {} addressed, {} rejected, {commit_note}, tree \
8268                         {tree_note}{}",
8269                    fix.addressed.len(),
8270                    fix.rejected.len(),
8271                    if continuation.outcome == ContinuationOutcome::Resumed {
8272                        format!(
8273                            " (adoption report recovered after {} continuation(s))",
8274                            continuation.attempts
8275                        )
8276                    } else {
8277                        String::new()
8278                    },
8279                ),
8280            },
8281        );
8282        round_record.fix = Some(fix);
8283        round_record.progressed = progressed;
8284        Ok(FixStep::Recorded {
8285            report_lost: matches!(
8286                continuation.outcome,
8287                ContinuationOutcome::Exhausted
8288                    | ContinuationOutcome::QuotaLost
8289                    | ContinuationOutcome::NoSession
8290            ),
8291        })
8292    }
8293
8294    /// Decide, from the last recorded round's own verification, whether
8295    /// stopping the review loop is a hand-off or a genuine block.
8296    ///
8297    /// Called once the loop has given up trying — the round budget is spent,
8298    /// or the tree stopped moving (see [`STAGNANT_LIMIT`]) — with blocking
8299    /// findings still open, never while a round is still clean or the
8300    /// incomplete-panel case handled inline above. Gate and e2e are facts
8301    /// about the tree; a lingering review finding is an opinion, and this
8302    /// workload's own `magi stats` puts reviewer precision low enough
8303    /// (12-33%, 0.18-0.29 adopted per round) that a panel of open findings
8304    /// must not by itself stand between a green, verified change and the
8305    /// human who decides what to do with it. A red e2e is not an opinion, so
8306    /// that case still blocks, with the failing command and a tail of its
8307    /// output recorded here rather than left in `run.json` for someone to go
8308    /// find.
8309    ///
8310    /// A round that deferred its own e2e (see [`Config::graph`]'s
8311    /// `e2e_every_round`) is never read as that green: its `e2e` is empty
8312    /// only because nothing ran, and treating an empty list as a passing one
8313    /// here is exactly the "deferred painted green" bug this function exists
8314    /// to not have. When the last round's own verification never resolved —
8315    /// deferred on purpose, or a real attempt the shared build cache blocked
8316    /// — this makes (or retries) the real run, on the actual worktree this
8317    /// loop is about to stop touching, before deciding anything. A
8318    /// resource-blocked attempt is likewise never read as either green or
8319    /// red: it is evidence about the machine, not the patch (see
8320    /// [`CommandOutcome::resource_blocked`]'s own doc), so a persistently
8321    /// blocked cache leaves this call without deciding rather than guessing
8322    /// — the caller retries on a later reentry.
8323    /// Record, once, that the review loop handed off over a blocking finding
8324    /// a reviewer rejected on (see [`ReviewRound::contested_handoff`]), so
8325    /// `land` asks the owner even with `land_approval` off. Called from every
8326    /// path that concludes `Gating`; a reentry keeps the first record.
8327    fn record_contested_handoff(&mut self) {
8328        if self.state.contested_handoff.is_some() {
8329            return;
8330        }
8331        let Some(contested) = self
8332            .state
8333            .reviews
8334            .last()
8335            .and_then(ReviewRound::contested_handoff)
8336        else {
8337            return;
8338        };
8339        self.state.event(
8340            "review",
8341            format!(
8342                "{} blocking finding(s) open and {} reviewer(s) rejecting — the merge will \
8343                 wait for the owner's approval",
8344                contested.findings.len(),
8345                contested.rejecters.len()
8346            ),
8347        );
8348        self.state.contested_handoff = Some(contested);
8349    }
8350
8351    async fn stop_unresolved_review(
8352        &mut self,
8353        why: &str,
8354        shell: &[String],
8355        worktree: &Path,
8356    ) -> Result<()> {
8357        self.stop_reviewing_inner(why, shell, worktree, true).await
8358    }
8359
8360    async fn stop_reviewing(&mut self, why: &str, shell: &[String], worktree: &Path) -> Result<()> {
8361        self.stop_reviewing_inner(why, shell, worktree, false).await
8362    }
8363
8364    async fn stop_reviewing_inner(
8365        &mut self,
8366        why: &str,
8367        shell: &[String],
8368        worktree: &Path,
8369        repairable: bool,
8370    ) -> Result<()> {
8371        let round_idx = self.state.reviews.len() - 1;
8372        // A deferred round and a resource-blocked one are the same shape
8373        // here: neither has a real result yet, and both get one more
8374        // attempt. Read off `e2e_status` — the single source for this —
8375        // rather than `e2e.is_empty()` alone, so a resource-blocked attempt
8376        // (whose `e2e` is *not* empty; see `CommandOutcome::resource_blocked`)
8377        // still retries instead of being read as a settled result the
8378        // instant it stops being empty.
8379        let needs_catchup_run = matches!(
8380            self.state.reviews[round_idx].e2e_status(),
8381            E2eStatus::Deferred | E2eStatus::ResourceBlocked
8382        );
8383        if needs_catchup_run {
8384            let round = self.state.reviews[round_idx].round;
8385            let timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
8386            let commands = self.state.config.verify.e2e.clone();
8387            let before_head = git::rev_parse(worktree, "HEAD").await?;
8388            let winner = self.state.winner().cloned();
8389            let cache_dir = self.state.config.cache_dir();
8390            let context = format!(
8391                "round {round}: verification unresolved, catching up before the final decision"
8392            );
8393            let wait = self.repository_wait();
8394            let (outcomes, verify_retried) = with_cache_lease(
8395                &mut self.state,
8396                cache_dir.as_deref(),
8397                "e2e",
8398                "e2e",
8399                worktree,
8400                &before_head,
8401                timeout,
8402                &context,
8403                &wait,
8404                |state, budget| {
8405                    let shell = shell.to_vec();
8406                    let commands = commands.clone();
8407                    let context = context.clone();
8408                    async move {
8409                        if let Some(winner) = winner.filter(|_| !commands.is_empty()) {
8410                            // Same reason as in the round itself: format before
8411                            // the suite, not after it.
8412                            Self::run_pre_gate(state, &winner).await;
8413                        }
8414                        run_e2e_with_retry(
8415                            state,
8416                            &shell,
8417                            &commands,
8418                            worktree,
8419                            budget,
8420                            &context,
8421                            Some(round),
8422                        )
8423                        .await
8424                    }
8425                },
8426            )
8427            .await?;
8428            // After `pre_gate`: the commit the commands actually ran against.
8429            let attempted_head = git::rev_parse(worktree, "HEAD").await?;
8430            if !outcomes.is_empty() && !verify_inconclusive(&outcomes) {
8431                self.state.record_base_progress(&attempted_head);
8432            }
8433            let last = &mut self.state.reviews[round_idx];
8434            last.e2e = outcomes;
8435            last.verify_retried = verify_retried;
8436            // Always the commit and time this attempt actually targeted,
8437            // whether or not it happens to equal the reviewed `head` and
8438            // whether or not a command finished — see
8439            // `ReviewRound::verified_head`'s own doc. A still-inconclusive
8440            // attempt is recorded too, so a later reader sees "attempted
8441            // again at T2" rather than silence.
8442            last.verified_head = Some(attempted_head);
8443            last.verified_at = Some(Timestamp::now());
8444            if verify_inconclusive(&last.e2e) {
8445                // Still not a real result: `e2e_deferred` is left exactly
8446                // as it was, so `needs_catchup_run` above reads
8447                // `ResourceBlocked` (via `e2e_status`, which checks
8448                // `resource_blocked` before `e2e_deferred`) and retries
8449                // again on the next reentry, rather than recording
8450                // contention as a red e2e and blocking the run on it.
8451                self.state.save()?;
8452                return Ok(());
8453            }
8454            last.e2e_deferred = false;
8455            // A complete panel may have been saved as unclean solely because
8456            // verification could not run. Refresh that verdict with the new
8457            // outcomes before a granted repair consumes the round's result.
8458            // Incomplete panels retain their original policy/quota decision.
8459            if last.answered == last.expected {
8460                last.clean = round_is_clean(
8461                    last.blocking,
8462                    last.e2e.iter().all(CommandOutcome::ok),
8463                    last.answered,
8464                    last.expected,
8465                    0,
8466                    self.state.config.graph.incomplete_review,
8467                );
8468            }
8469        }
8470        let last = &self.state.reviews[round_idx];
8471        let open: usize = last.reviews.iter().map(|r| r.findings.len()).sum();
8472
8473        match last.e2e_status() {
8474            E2eStatus::Failed => {
8475                let red: Vec<String> = last
8476                    .e2e
8477                    .iter()
8478                    .filter(|o| !o.ok())
8479                    .map(|o| {
8480                        format!(
8481                            "`{}` -> {:?}\n{}",
8482                            o.command,
8483                            o.code,
8484                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
8485                        )
8486                    })
8487                    .collect();
8488                let can_repair = last.blocking == 0 && last.fix.is_none();
8489                self.state.reviews[round_idx].clean = false;
8490                self.state
8491                    .event("review", format!("{why}; e2e failed:\n{}", red.join("\n")));
8492                self.state.status = RunStatus::Blocked;
8493                if repairable
8494                    && can_repair
8495                    && self.state.reviews.len() < self.state.config.graph.review_rounds
8496                {
8497                    self.state.status = RunStatus::Reviewing;
8498                }
8499            }
8500            // `needs_catchup_run` above already retried once this call; if
8501            // it is still blocked, this is magi's own admission it could
8502            // not get a command to run, never a verdict on the patch — the
8503            // run is left exactly where a later reentry can retry again.
8504            E2eStatus::ResourceBlocked => {
8505                self.state.event(
8506                    "review",
8507                    format!(
8508                        "{why}; e2e could not run (resource unavailable); not \
8509                         deciding yet"
8510                    ),
8511                );
8512            }
8513            E2eStatus::Passed | E2eStatus::Deferred | E2eStatus::NotConfigured => {
8514                self.state.event(
8515                    "review",
8516                    format!("{why}; e2e is green — handing off with {open} finding(s) still open"),
8517                );
8518                self.record_contested_handoff();
8519                self.state.status = RunStatus::Gating;
8520            }
8521        }
8522        self.state.save()?;
8523        Ok(())
8524    }
8525
8526    // ----------------------------------------------------------------- gate
8527
8528    async fn gate(&mut self) -> Result<()> {
8529        if self.hold_base_sync().await? {
8530            return Ok(());
8531        }
8532        // Judged by the review record itself, not by `status`: a solo
8533        // candidate's `judge`/`deliberate` skip rewrites `status` on every
8534        // reentry (see `judge`), and trusting it here is exactly how a run
8535        // that exhausted its review budget got gated and merged a second
8536        // time around. `review_conclusion` recomputes the review loop's own
8537        // verdict from the round records themselves — `Gating` for a clean
8538        // round or a hand-off (see `stop_reviewing`), anything else means the
8539        // loop is still going or genuinely blocked.
8540        // A base the winner could not be replayed onto is a decision, not a
8541        // round: there is no landing tree to gate. Read as its own record for
8542        // the same reason the review verdict is.
8543        if self.state.status == RunStatus::Failed
8544            || self
8545                .state
8546                .base_sync
8547                .as_ref()
8548                .is_some_and(|s| s.conflict.is_some())
8549            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
8550                != Some(RunStatus::Gating)
8551        {
8552            return Ok(());
8553        }
8554        let Some(winner) = self.state.winner().cloned() else {
8555            return Ok(());
8556        };
8557        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
8558        self.state.reconcile_verification_head(&head);
8559        self.state.save()?;
8560        let wait = self.repository_wait();
8561        if !verify_current_head(&mut self.state, &winner, &wait).await? {
8562            return Ok(());
8563        }
8564        if self.state.gate_ran {
8565            // `review_loop` derives its conclusion from the clean review
8566            // record on every reentry and therefore puts a completed run back
8567            // in `Gating`. A recorded gate is a stronger, terminal fact:
8568            // retain its original command output (or lack of any, for a repo
8569            // with no `verify.gate` commands — see `RunState::gate_ran`'s own
8570            // doc) and restore `Blocked` on a real failure rather than
8571            // pretending the command is still running or running it a second
8572            // time. `gate_ran == false` remains the only shape — unattempted,
8573            // or a resource-blocked retry — that may still need to execute a
8574            // command.
8575            if self.state.gate.iter().any(|outcome| !outcome.ok()) {
8576                self.state.status = RunStatus::Blocked;
8577                self.state.save()?;
8578            }
8579            return Ok(());
8580        }
8581        self.state.status = RunStatus::Gating;
8582        let mut outcomes = self.run_gate(&winner).await?;
8583        let mut attempted_head = self.state.gate_head.clone();
8584        loop {
8585            // A resource-blocked outcome means the gate command never actually
8586            // ran - the shared build cache could not be acquired or confirmed
8587            // fresh in time - which is evidence about the machine, not about
8588            // the tree (see `CommandOutcome::resource_blocked`'s own doc).
8589            // Recording it as a red gate would mark a run `Blocked` on nothing
8590            // but contention magi has already logged; leaving `self.state.gate`
8591            // empty and `self.state.gate_ran` false instead keeps the shape
8592            // this function already treats as "still needs to run" (see the
8593            // early-return above), so the next call retries the command
8594            // rather than concluding anything.
8595            if verify_inconclusive(&outcomes) {
8596                self.state.save()?;
8597                return Ok(());
8598            }
8599            if outcomes.iter().all(CommandOutcome::ok) {
8600                break;
8601            }
8602            let fixes_before = self.state.gate_fixes.len();
8603            match self.gate_fix_round(&winner, &outcomes).await? {
8604                GateFix::Retry => {
8605                    outcomes = self.run_gate(&winner).await?;
8606                    attempted_head = self.state.gate_head.clone();
8607                }
8608                GateFix::Stop => {
8609                    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
8610                    if self.state.gate_fixes.len() > fixes_before
8611                        && attempted_head.as_deref() != Some(current.as_str())
8612                        && verify_current_head(&mut self.state, &winner, &wait).await?
8613                    {
8614                        // A new SHA owes a gate even when a spent fixer changed only
8615                        // commit metadata. This does not grant another repair round.
8616                        outcomes = self.run_gate(&winner).await?;
8617                        attempted_head = self.state.gate_head.clone();
8618                    } else {
8619                        break;
8620                    }
8621                }
8622                GateFix::Defer => {
8623                    self.state.save()?;
8624                    return Ok(());
8625                }
8626            }
8627        }
8628        let passed = outcomes.iter().all(CommandOutcome::ok);
8629        self.state.gate = outcomes;
8630        self.state.gate_ran = true;
8631        self.state.gate_head = attempted_head;
8632        if !self.state.gate.is_empty()
8633            && !verify_inconclusive(&self.state.gate)
8634            && let Some(head) = self.state.gate_head.clone()
8635        {
8636            self.state.record_base_progress(&head);
8637        }
8638        self.state.save()?;
8639        if !verify_current_head(&mut self.state, &winner, &wait).await? {
8640            return Ok(());
8641        }
8642        if !passed {
8643            self.state.status = RunStatus::Blocked;
8644            let spent = self.state.gate_fixes.len();
8645            self.state.event(
8646                "gate",
8647                if spent == 0 {
8648                    "gate failed; not merging".to_owned()
8649                } else {
8650                    format!("gate failed after {spent} gate-fix round(s); not merging")
8651                },
8652            );
8653        }
8654        self.state.save()?;
8655        Ok(())
8656    }
8657
8658    /// Run `verify.pre_gate` in the winner's worktree, then fold whatever it
8659    /// changed into one commit. Runs before `verify.e2e` in the review loop
8660    /// and again before the gate commands, always on the winner and never on
8661    /// a candidate awaiting judging.
8662    ///
8663    /// Before e2e as well as before the gate because command evidence belongs
8664    /// to a SHA ([`verify_current_head`]): a commit made only at the gate is a
8665    /// commit e2e never saw, and the suite ran again for a formatter's diff -
8666    /// 5 of the 22 gated runs on this repository in November 2026. The gate's
8667    /// own call then finds nothing left to change. The commands must be
8668    /// idempotent; one that is not makes a commit per call.
8669    ///
8670    /// Never fails the run: a non-zero exit or timeout is a warning and a
8671    /// recorded outcome, and the gate remains the single arbiter. Nothing
8672    /// configured means nothing happens - no event, no commit. `commit_all`
8673    /// commits any leftover change under the neutral identity and returns
8674    /// `false` when the tree is clean, so no empty commit is ever made.
8675    async fn run_pre_gate(state: &mut RunState, winner: &Candidate) {
8676        let commands = state.config.verify.pre_gate.clone();
8677        if commands.is_empty() {
8678            return;
8679        }
8680        let shell = state.config.shell();
8681        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
8682        let (outcomes, _) = run_commands(
8683            state,
8684            "pre_gate",
8685            "pre_gate",
8686            0,
8687            &shell,
8688            &commands,
8689            &winner.worktree,
8690            timeout,
8691        )
8692        .await;
8693        for o in &outcomes {
8694            if !o.ok() {
8695                tracing::warn!(
8696                    "pre_gate `{}` failed ({:?}); the gate decides",
8697                    o.command,
8698                    o.code
8699                );
8700            }
8701            state.event(
8702                "pre_gate",
8703                format!(
8704                    "`{}` -> {}",
8705                    o.command,
8706                    if o.ok() {
8707                        "pass".to_owned()
8708                    } else {
8709                        format!(
8710                            "FAIL ({:?})\n{}",
8711                            o.code,
8712                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
8713                        )
8714                    }
8715                ),
8716            );
8717        }
8718        state.pre_gate = outcomes;
8719        match git::commit_all(&winner.worktree, "magi: pre_gate (mechanical fixes)").await {
8720            Ok(true) => match git::rev_parse(&winner.worktree, "HEAD").await {
8721                Ok(head) => {
8722                    state.event("pre_gate", format!("committed mechanical fixes ({head})"));
8723                    state.pre_gate_commit = Some(head);
8724                }
8725                Err(e) => tracing::warn!("pre_gate committed but HEAD unreadable: {e:#}"),
8726            },
8727            Ok(false) => {}
8728            Err(e) => tracing::warn!("pre_gate could not commit its changes: {e:#}"),
8729        }
8730        if let Err(e) = state.save() {
8731            tracing::warn!("could not persist the pre_gate record: {e:#}");
8732        }
8733    }
8734
8735    /// Run `verify.gate` once against the winner's current tree, logging one
8736    /// event per command. Empty when nothing is configured.
8737    async fn run_gate(&mut self, winner: &Candidate) -> Result<Vec<CommandOutcome>> {
8738        let wait = self.repository_wait();
8739        run_landing_gate(&mut self.state, winner, &wait).await
8740    }
8741
8742    /// One bounded fix round for a failing gate.
8743    ///
8744    /// The fixer is told the failure came from the gate itself, not from a
8745    /// reviewer, and is shown the failed commands, their exit codes and a tail
8746    /// of their output - whatever `[verify].gate` holds, nothing here knows
8747    /// what those commands run. Only a normal non-zero exit that printed
8748    /// something earns a round (see [`gate_fixable`]): a timeout, a missing
8749    /// command or a full disk says nothing about the code, and a fixer sent
8750    /// after it can only appease the machine. The round is judged by what git
8751    /// says moved, never by the fixer's own report, and `verify.e2e` runs
8752    /// again before the gate does, so a fix cannot trade a green gate for a
8753    /// red e2e unnoticed.
8754    async fn gate_fix_round(
8755        &mut self,
8756        winner: &Candidate,
8757        outcomes: &[CommandOutcome],
8758    ) -> Result<GateFix> {
8759        let cap = if self.state.repair_grants.last().is_some_and(|g| {
8760            g.phase == crate::repair_budget::Phase::Fixing
8761                && g.receipt.request.kind == crate::repair_budget::Kind::Gate
8762        }) {
8763            self.state.gate_fixes.len().saturating_add(1)
8764        } else {
8765            self.state.config.graph.gate_fix_rounds
8766        };
8767        let spent = self.state.gate_fixes.len();
8768        if spent >= cap {
8769            if cap > 0 {
8770                self.state.event(
8771                    "gate",
8772                    format!("{spent} gate-fix round(s) spent and the gate still fails"),
8773                );
8774            }
8775            return Ok(GateFix::Stop);
8776        }
8777        if !gate_fixable(outcomes) {
8778            self.state.event(
8779                "gate",
8780                "gate failure is not an ordinary non-zero exit with output (timeout, missing \
8781                 command or similar); not spending a fix round on it",
8782            );
8783            return Ok(GateFix::Stop);
8784        }
8785        let min_free = self.state.config.disk.min_free_bytes;
8786        if min_free > 0 {
8787            match crate::disk::free_bytes(&winner.worktree) {
8788                Ok(free) if crate::disk::enough_space(free, min_free) => {}
8789                Ok(free) => {
8790                    self.state.event(
8791                        "gate",
8792                        format!(
8793                            "only {free} bytes free ({min_free} required by `[disk] \
8794                             min_free_bytes`); not spending a fix round on a failure the disk \
8795                             may explain"
8796                        ),
8797                    );
8798                    return Ok(GateFix::Stop);
8799                }
8800                Err(e) => {
8801                    self.state.event(
8802                        "gate",
8803                        format!("free disk space could not be measured ({e:#}); no fix round"),
8804                    );
8805                    return Ok(GateFix::Stop);
8806                }
8807            }
8808        }
8809
8810        let attempt = spent + 1;
8811        let failed: Vec<CommandOutcome> = outcomes.iter().filter(|o| !o.ok()).cloned().collect();
8812        let base = self.landing_base();
8813        let fix_prompt = prompt::gate_fix_in(
8814            &self.state.instruction,
8815            &failed,
8816            attempt,
8817            cap,
8818            &self.state.config.graph.language,
8819            &self.state.config.graph.github_language,
8820        );
8821        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
8822        let sessions = self.state.config.graph.sessions;
8823        let artifacts = self.merge_repair_artifacts();
8824        self.state.event(
8825            "gate",
8826            format!("gate failed; gate-fix round {attempt} of {cap}"),
8827        );
8828        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
8829        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
8830        // Persist before invoking the fixer: it may commit and then be
8831        // interrupted before its result (or the following e2e) is saved.
8832        self.state.gate_repair_e2e = Some(crate::run::GateRepairE2e {
8833            head: before.clone(),
8834            passed: false,
8835            outcomes: Vec::new(),
8836        });
8837        self.state.save()?;
8838        let (_, seat, out) = self
8839            .ask_fixer(winner, "gate-fix", None, |spec, seat| SeatJob {
8840                prompt: fix_prompt.clone(),
8841                spec,
8842                seat,
8843                cwd: winner.worktree.clone(),
8844                timeout,
8845                allow_write: true,
8846                sessions,
8847                artifacts: artifacts.clone(),
8848                stem: format!("gate-fix-{attempt}"),
8849                handover: None,
8850            })
8851            .await;
8852        // The fixer was never asked: no round is spent (nothing is recorded)
8853        // and a later reentry asks the same agent again.
8854        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
8855            return Ok(GateFix::Defer);
8856        }
8857        let mut record = GateFixRecord {
8858            agent: seat.agent.clone(),
8859            failed,
8860            notes: String::new(),
8861            committed: false,
8862            error: None,
8863        };
8864        match out {
8865            AgentOutcome::Ok(o) => {
8866                // A missing report is not a failed fix: the round is judged
8867                // by the tree below, and the report only carries prose.
8868                if let Ok(report) = verdict::extract_json::<FixReport>(&o.text) {
8869                    record.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
8870                }
8871            }
8872            AgentOutcome::Dropped(_) => {
8873                record.error = Some("the CLI dropped the stream".to_owned());
8874            }
8875            AgentOutcome::Quota(o) => {
8876                self.state.quota.push(QuotaLoss::from_report(
8877                    seat.key.clone(),
8878                    "gate-fix",
8879                    o.quota.as_ref(),
8880                ));
8881                record.error = Some("rate limited (quota); fixer could not run".to_owned());
8882            }
8883            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => record.error = Some(e),
8884        }
8885        self.state.seats.insert(seat.key.clone(), seat);
8886        let coordination = self.coordinate(&winner.worktree).await?;
8887        if let Ok(r) = git::rescue_commit(
8888            &winner.worktree,
8889            &format!("magi: gate fix {attempt} (uncommitted work)"),
8890        )
8891        .await
8892        {
8893            self.state.note_withheld("gate-fix", &r.withheld);
8894        }
8895        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
8896        record.committed = after != before;
8897        let changed = git::diff(&winner.worktree, &base, "HEAD").await? != patch;
8898        let note = record.error.clone();
8899        self.state.gate_fixes.push(record);
8900        self.state.save()?;
8901        if !changed {
8902            self.state.event(
8903                "gate",
8904                match note {
8905                    Some(why) => format!("gate-fix round {attempt}: fixer failed ({why})"),
8906                    None => format!("gate-fix round {attempt}: the tree did not change"),
8907                },
8908            );
8909            return Ok(GateFix::Stop);
8910        }
8911        self.state.event(
8912            "gate",
8913            format!("gate-fix round {attempt}: tree changed vs base; re-running verify.e2e"),
8914        );
8915
8916        drop(coordination);
8917        let wait = self.repository_wait();
8918        check_gate_repair_e2e(&mut self.state, winner, &wait).await
8919    }
8920
8921    // ---------------------------------------------------------------- merge
8922
8923    /// One read-only rewrite by the summary's author; a text the gate still
8924    /// withholds goes to the owner (see `github_text`) and the fixed fallback
8925    /// applies on their word or on silence. `None` means the run is parked on
8926    /// that question and nothing may be pushed or opened yet.
8927    async fn guarded_pr_message(
8928        &mut self,
8929        winner: &Candidate,
8930        facts: Option<&BranchFacts>,
8931        posting: bool,
8932    ) -> Result<Option<PrMessage>> {
8933        let final_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
8934        let head = match final_head.as_deref() {
8935            Some(h) => crate::pr_outcome::FinalHead::At(h),
8936            None => crate::pr_outcome::FinalHead::Unknown,
8937        };
8938        // Only a pull request that is about to be posted pays for a summary.
8939        let summarized = if posting {
8940            Some(self.summarize_change(winner, final_head.as_deref()).await)
8941        } else {
8942            None
8943        };
8944        // A busy shared resource is not a permanent cause: publishing an
8945        // "unavailable" description would stick (a later head move never
8946        // edits the body). Stop before anything is pushed or opened; the
8947        // run is `Blocked` and a resume asks the summary again.
8948        if self.state.resource_block.is_some() {
8949            self.state.event(
8950                "pr-summary",
8951                "a shared resource was busy; nothing was published, resume to summarize again",
8952            );
8953            return Ok(None);
8954        }
8955        if posting && git::rev_parse(&winner.worktree, "HEAD").await.ok() != final_head {
8956            anyhow::bail!(
8957                "the final commit moved during public description generation; retry before publishing"
8958            );
8959        }
8960        let note = match (&summarized, &self.state.change_summary) {
8961            (Some(Ok(())), Some(c)) => ChangeNote::Summary(c),
8962            (Some(Err(why)), _) => ChangeNote::Unavailable(why),
8963            (Some(Ok(())), None) => ChangeNote::Unavailable("no summary was recorded"),
8964            (None, _) => ChangeNote::NotAsked,
8965        };
8966        let mut pr = pr_message_raw(&self.state, winner.label, facts, head, note);
8967        if !posting {
8968            let identity = crate::scrub::Identity::current();
8969            return Ok(Some(PrMessage {
8970                title: crate::scrub::scrub(&pr.title, &identity),
8971                body: crate::scrub::scrub(&pr.body, &identity),
8972            }));
8973        }
8974        // This very text was already rejected and asked about: no second
8975        // judge call, rewrite or question, just carry the record on.
8976        let raw_fp = crate::github_text::fingerprint(&pr.title, &pr.body);
8977        if let Some(known) = self
8978            .state
8979            .github_text
8980            .clone()
8981            .filter(|g| g.fingerprint == raw_fp)
8982        {
8983            return self.settle_withheld(winner, &pr, known).await;
8984        }
8985        let mut decision = self.judge_pr_language(&winner.worktree, &pr).await;
8986        let mut violations =
8987            crate::github_text::check_for(&self.state.config.graph, &pr.title, &pr.body, decision);
8988        let identity = crate::scrub::Identity::current();
8989        if (crate::scrub::scrub(&pr.title, &identity) != pr.title
8990            || crate::scrub::scrub(&pr.body, &identity) != pr.body)
8991            && !violations.contains(&crate::github_text::Violation::SensitiveData)
8992        {
8993            violations.push(crate::github_text::Violation::SensitiveData);
8994        }
8995        // A rewrite cannot fix sensitive data (e.g. a quoted original task), so
8996        // only a language violation starts one; sensitive data alone goes
8997        // straight to the owner, with the redacted text as the fallback.
8998        let has_language = violations
8999            .iter()
9000            .any(|v| *v != crate::github_text::Violation::SensitiveData);
9001        if self.state.config.graph.github_text_guard && !violations.is_empty() {
9002            self.state.event(
9003                "github-text",
9004                if has_language {
9005                    format!("description rejected: {violations:?}; requesting one rewrite")
9006                } else {
9007                    format!("description rejected: {violations:?}; asking the owner")
9008                },
9009            );
9010            let mut rewritten = false;
9011            let mut rejected_rewrite = None;
9012            if has_language && let Some(text) = self.rewrite_pr_text(winner, &pr, &violations).await
9013            {
9014                let output = text;
9015                if let Some(title) = summary_title(&output) {
9016                    // Judge the redacted candidate that will actually be posted.
9017                    // Sensitive data alone must not discard a useful rewrite.
9018                    let raw_body = summary_without_title(&output);
9019                    let clean_title = crate::scrub::scrub(&title, &identity);
9020                    let mut body = crate::scrub::scrub(&raw_body, &identity);
9021                    let redacted = clean_title != title || body != raw_body;
9022                    let title = clean_title;
9023                    let complete = crate::pr_outcome::covers_required_findings(&self.state, &body);
9024                    if !complete {
9025                        self.state.event(
9026                            "github-text",
9027                            "description rewrite omitted required findings",
9028                        );
9029                    }
9030                    if !body.trim().is_empty() {
9031                        body.push_str("\n\n");
9032                        body.push_str(&public_pr_evidence(&self.state, head));
9033                    }
9034                    let marker = format!("magi:run/{}", self.state.id);
9035                    if !body.trim().is_empty() && !body.contains(&marker) {
9036                        body.push_str(&format!("\n\n{marker}"));
9037                    }
9038                    let rewrite = PrMessage {
9039                        title: title.clone(),
9040                        body: body.clone(),
9041                    };
9042                    let redecision = self.judge_pr_language(&winner.worktree, &rewrite).await;
9043                    let mut failed = crate::github_text::check_for(
9044                        &self.state.config.graph,
9045                        &title,
9046                        &body,
9047                        redecision,
9048                    );
9049                    if (!crate::github_text::shareable(&title)
9050                        || !crate::github_text::shareable(&body))
9051                        && !failed.contains(&crate::github_text::Violation::SensitiveData)
9052                    {
9053                        failed.push(crate::github_text::Violation::SensitiveData);
9054                    }
9055                    if complete
9056                        && !title.trim().is_empty()
9057                        && !body.trim().is_empty()
9058                        && !failed.is_empty()
9059                    {
9060                        rejected_rewrite = Some(crate::run::GithubTextRewrite {
9061                            title: title.clone(),
9062                            body: body.clone(),
9063                            failed: failed
9064                                .iter()
9065                                .map(|v| crate::github_text::category(*v).to_owned())
9066                                .collect(),
9067                        });
9068                    }
9069                    if complete
9070                        && !title.trim().is_empty()
9071                        && !raw_body.trim().is_empty()
9072                        && failed.is_empty()
9073                    {
9074                        decision = redecision;
9075                        pr = PrMessage { title, body };
9076                        rewritten = true;
9077                        self.state
9078                            .event("github-text", "description rewrite passed");
9079                        if redacted {
9080                            self.state.event(
9081                                "github-text",
9082                                "sensitive data removed from description rewrite",
9083                            );
9084                        }
9085                    }
9086                }
9087            }
9088            if !rewritten {
9089                self.state.event(
9090                    "github-text",
9091                    "description rewrite unavailable or rejected; asking the owner",
9092                );
9093                if let Some(w) =
9094                    crate::github_text::Withheld::from_check(&violations, &pr.title, &pr.body)
9095                {
9096                    // A different text than the one asked about before: that
9097                    // question no longer describes anything.
9098                    self.retire_github_text_question("the withheld text changed");
9099                    let record = crate::run::GithubTextAsk {
9100                        rewrite: rejected_rewrite,
9101                        fingerprint: raw_fp,
9102                        title: w.title,
9103                        body: w.body,
9104                        categories: w.categories.iter().map(|c| (*c).to_owned()).collect(),
9105                        question: None,
9106                        asks: 0,
9107                        resolved: false,
9108                        chosen_title: None,
9109                        choice: None,
9110                        publication: None,
9111                    };
9112                    return self.settle_withheld(winner, &pr, record).await;
9113                }
9114            }
9115        }
9116        let (title, body) =
9117            crate::github_text::prepare_with(&mut self.state, &pr.title, &pr.body, decision);
9118        Ok(Some(PrMessage { title, body }))
9119    }
9120
9121    /// Describe the whole change from its final diff in either run mode.
9122    ///
9123    /// The summary is tied to the final commit and to the merge base of the
9124    /// resolved remote base; a record for any other pair is dropped and the
9125    /// agent asked again, so a description never outlives the diff it was
9126    /// written from. The seat is read-only and the prompt tells it to read the
9127    /// diff and the code around it. `[roles] synthesizer` selects the agents
9128    /// (unset: the default pick), each asked at most once, advancing on an
9129    /// error, quota, unusable answer or a reply with no `TITLE:` line. `Err`
9130    /// carries the reason it is unavailable; nothing is invented then.
9131    async fn summarize_change(
9132        &mut self,
9133        winner: &Candidate,
9134        head: Option<&str>,
9135    ) -> std::result::Result<(), String> {
9136        let Some(head) = head else {
9137            return Err("the final commit could not be read".to_owned());
9138        };
9139        let remote = self.state.config.merge.remote.clone();
9140        let tracking = format!("{remote}/{}", self.state.base_branch);
9141        if !git::rev_exists(&winner.worktree, &tracking).await {
9142            return Err(format!("the remote base `{tracking}` could not be read"));
9143        }
9144        let base = match git::merge_base(&winner.worktree, &tracking, head).await {
9145            Ok(b) if !b.is_empty() => b,
9146            _ => return Err("the merge base with the remote base could not be read".to_owned()),
9147        };
9148        let evidence = crate::pr_outcome::summary_evidence(
9149            &self.state,
9150            crate::pr_outcome::FinalHead::At(head),
9151        );
9152        let fingerprint = crate::pr_outcome::summary_fingerprint(&self.state, &evidence);
9153        if self
9154            .state
9155            .change_summary
9156            .as_ref()
9157            .is_some_and(|c| c.head == head && c.base == base && c.evidence == fingerprint)
9158        {
9159            return Ok(());
9160        }
9161        if self.state.change_summary.take().is_some() {
9162            self.state.event(
9163                "pr-summary",
9164                "the final diff or evidence changed; the earlier change summary was discarded",
9165            );
9166        }
9167        // Save the source snapshot even if no generation agent is available.
9168        if let Err(e) = write_artifact(
9169            &self.state,
9170            &format!("public-description-{fingerprint}.md"),
9171            &format!("Final diff: {base}..{head}\n\n{evidence}"),
9172        ) {
9173            tracing::warn!("could not save public description evidence: {e:#}");
9174        }
9175        let chain = match agent::pick_chain(
9176            &self.state.config.agents,
9177            self.state.config.roles.synthesizer.as_ref(),
9178            &agent::installed,
9179            "synthesizer",
9180        ) {
9181            Ok(chain) => chain,
9182            Err(e) => {
9183                tracing::warn!("no agent for the change summary: {e:#}");
9184                self.state.event("pr-summary", "no summary agent available");
9185                return Err("no agent was available to summarize it".to_owned());
9186            }
9187        };
9188        let subjects = git::subjects(&winner.worktree, &base, head)
9189            .await
9190            .unwrap_or_default();
9191        let stat = git::diff_stat(&winner.worktree, &base, head)
9192            .await
9193            .unwrap_or_default();
9194        let stat: String = stat.chars().take(6_000).collect();
9195        let mut prompt = crate::prompt::change_summary_in(
9196            &base,
9197            head,
9198            &subjects,
9199            stat.trim(),
9200            &self.state.config.graph.github_language,
9201        );
9202        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."));
9203        let sessions = self.state.config.graph.sessions;
9204        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
9205        let prompts = self.state.config.prompts.clone();
9206        let cache = self.state.config.cache_dir();
9207        let run = self.state.id.clone();
9208        for (i, spec) in chain.into_iter().enumerate() {
9209            let seat = crate::fixer::seat_for(&mut self.state, "change-summary", &spec.id);
9210            let github_spec = match agent::for_github_text(
9211                &spec,
9212                &self.state.config.graph.github_language,
9213                &winner.worktree,
9214            ) {
9215                Ok(spec) => spec,
9216                Err(e) => {
9217                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9218                    continue;
9219                }
9220            };
9221            let job = SeatJob {
9222                spec: github_spec,
9223                seat,
9224                cwd: winner.worktree.clone(),
9225                prompt: prompt.clone(),
9226                timeout,
9227                allow_write: false,
9228                sessions,
9229                artifacts: agent::artifacts_dir(&self.state.dir()),
9230                stem: if i == 0 {
9231                    "change-summary".to_owned()
9232                } else {
9233                    format!("change-summary-{}", spec.id)
9234                },
9235                handover: None,
9236            };
9237            let ctx = WaveCtx {
9238                run: &run,
9239                node: "pr-summary",
9240                prompts: &prompts,
9241                cache: cache.as_deref(),
9242                round: None,
9243                carry_seats: false,
9244                pauses: Some((&self.pause, &self.interrupt)),
9245            };
9246            let (seat, outcome) =
9247                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9248            self.state.seats.insert(seat.key.clone(), seat);
9249            let text = match outcome {
9250                AgentOutcome::Ok(o) if !agent::output_advances(&o) => o.text,
9251                AgentOutcome::ResourceBlocked(why) => {
9252                    // No agent was asked: the run stops resumably before
9253                    // anything is published (see `guarded_pr_message`).
9254                    if self.state.resource_block.is_none() {
9255                        self.state.resource_block = Some(crate::run::ResourceBlock {
9256                            cause: crate::run::ResourceBlockCause::Other,
9257                            node: "pr-summary".to_owned(),
9258                            kind: "shared resource".to_owned(),
9259                            detail: why,
9260                            at: Timestamp::now(),
9261                        });
9262                    }
9263                    return Err("a shared resource was busy".to_owned());
9264                }
9265                _ => continue,
9266            };
9267            let blind = &self.state.config.blind;
9268            let Some(title) = summary_title(&text) else {
9269                continue;
9270            };
9271            let body: String = summary_without_title(&text)
9272                .lines()
9273                .filter(|l| !l.contains("magi:run/"))
9274                .collect::<Vec<_>>()
9275                .join("\n");
9276            let body = blind::sanitize_prose(body.trim(), blind);
9277            let title = blind::sanitize_prose(&title, blind);
9278            if body.trim().is_empty() || title.trim().is_empty() {
9279                continue;
9280            }
9281            if !crate::pr_outcome::covers_required_findings(&self.state, &body) {
9282                continue;
9283            }
9284            // The branch must still be the one the agent was shown.
9285            if git::rev_parse(&winner.worktree, "HEAD")
9286                .await
9287                .ok()
9288                .as_deref()
9289                != Some(head)
9290            {
9291                return Err("the branch moved while the summary was written".to_owned());
9292            }
9293            if git::merge_base(&winner.worktree, &tracking, head)
9294                .await
9295                .ok()
9296                .as_deref()
9297                != Some(base.as_str())
9298                || crate::pr_outcome::summary_evidence(
9299                    &self.state,
9300                    crate::pr_outcome::FinalHead::At(head),
9301                ) != evidence
9302            {
9303                return Err("the summary evidence changed while it was written".to_owned());
9304            }
9305            self.state.change_summary = Some(crate::run::ChangeSummary {
9306                head: head.to_owned(),
9307                base,
9308                evidence: fingerprint,
9309                title,
9310                body,
9311            });
9312            self.state.event(
9313                "pr-summary",
9314                format!("change summary written by {} for the final diff", spec.id),
9315            );
9316            if let Err(e) = self.state.save() {
9317                tracing::warn!("could not save the change summary: {e:#}");
9318            }
9319            return Ok(());
9320        }
9321        self.state
9322            .event("pr-summary", "no agent produced a change summary");
9323        Err("the summarizing agents were unavailable or gave no usable answer".to_owned())
9324    }
9325
9326    /// One read-only rewrite request for a withheld description. The
9327    /// implementer's own conversation is tried first when it exists and can be
9328    /// resumed; then the `[roles] language_judge` chain (or the default pick)
9329    /// writes it in a separate conversation, skipping the implementer's agent.
9330    /// The prompt carries the whole text, so no agent needs any memory. Each
9331    /// agent is asked at most once and the chain advances on an error, quota,
9332    /// unusable answer or a reply with no `TITLE:` line: a resumed implementer
9333    /// that has run out of quota must not end the rewrite. Nothing is recorded
9334    /// as a handover.
9335    async fn rewrite_pr_text(
9336        &mut self,
9337        winner: &Candidate,
9338        pr: &PrMessage,
9339        violations: &[crate::github_text::Violation],
9340    ) -> Option<String> {
9341        let prompt = format!(
9342            "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{}",
9343            pr.title, pr.body
9344        );
9345        let sessions = self.state.config.graph.sessions;
9346        let timeout_full = Duration::from_secs(self.state.config.graph.timeout_implement);
9347        // (spec, the resumed implementer's seat). A fallback seat is created
9348        // only when its turn comes, so an unused fallback leaves no record.
9349        let mut attempts: Vec<(AgentSpec, Option<SeatState>)> = Vec::new();
9350        let key = format!("impl-{}", winner.label);
9351        if let Some(spec) = self
9352            .state
9353            .config
9354            .agents
9355            .iter()
9356            .find(|a| a.id == winner.agent)
9357            .cloned()
9358            && let Some(existing) = self.state.seats.get(&key)
9359            && existing.agent == spec.id
9360            && agent::has_session(spec.kind, existing, sessions)
9361        {
9362            attempts.push((spec, Some(existing.clone())));
9363        }
9364        match agent::pick_chain(
9365            &self.state.config.agents,
9366            self.state.config.roles.language_judge.as_ref(),
9367            &agent::installed,
9368            "language_judge",
9369        ) {
9370            Ok(chain) => {
9371                for spec in chain {
9372                    if attempts.iter().any(|(tried, _)| tried.id == spec.id) {
9373                        continue;
9374                    }
9375                    attempts.push((spec, None));
9376                }
9377            }
9378            Err(e) if attempts.is_empty() => {
9379                tracing::warn!("no agent for the description rewrite: {e:#}");
9380                self.state
9381                    .event("github-text", "no rewrite agent available");
9382                return None;
9383            }
9384            Err(e) => tracing::warn!("no fallback agent for the description rewrite: {e:#}"),
9385        }
9386        let prompts = self.state.config.prompts.clone();
9387        let cache = self.state.config.cache_dir();
9388        let run = self.state.id.clone();
9389        for (i, (spec, resumed_seat)) in attempts.into_iter().enumerate() {
9390            let resumed = resumed_seat.is_some();
9391            let seat = resumed_seat.unwrap_or_else(|| {
9392                crate::fixer::seat_for(&mut self.state, "github-text-rewrite", &spec.id)
9393            });
9394            let github_spec = match agent::for_github_text(
9395                &spec,
9396                &self.state.config.graph.github_language,
9397                &winner.worktree,
9398            ) {
9399                Ok(spec) => spec,
9400                Err(e) => {
9401                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9402                    continue;
9403                }
9404            };
9405            let job = SeatJob {
9406                spec: github_spec,
9407                seat,
9408                cwd: winner.worktree.clone(),
9409                prompt: prompt.clone(),
9410                timeout: retry_budget(timeout_full, resumed),
9411                allow_write: false,
9412                sessions,
9413                artifacts: agent::artifacts_dir(&self.state.dir()),
9414                stem: if i == 0 {
9415                    "github-text-rewrite".to_owned()
9416                } else {
9417                    format!("github-text-rewrite-{}", spec.id)
9418                },
9419                handover: None,
9420            };
9421            let ctx = WaveCtx {
9422                run: &run,
9423                node: "github-text",
9424                prompts: &prompts,
9425                cache: cache.as_deref(),
9426                round: None,
9427                carry_seats: false,
9428                pauses: Some((&self.pause, &self.interrupt)),
9429            };
9430            let (seat, outcome) =
9431                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9432            self.state.seats.insert(seat.key.clone(), seat);
9433            match outcome {
9434                AgentOutcome::Ok(o)
9435                    if !agent::output_advances(&o) && summary_title(&o.text).is_some() =>
9436                {
9437                    return Some(o.text);
9438                }
9439                AgentOutcome::ResourceBlocked(_) => return None,
9440                _ => {}
9441            }
9442        }
9443        None
9444    }
9445
9446    /// Abandon the standing posting-gate question, if any.
9447    fn retire_github_text_question(&mut self, why: &str) {
9448        let Some(id) = self
9449            .state
9450            .github_text
9451            .as_ref()
9452            .and_then(|g| g.question.clone())
9453        else {
9454            return;
9455        };
9456        let _ = ask::Questions::open().update(&id, |q| {
9457            q.abandon(why);
9458            Ok(())
9459        });
9460    }
9461
9462    /// Carry a withheld text to its end: file the question, park while it is
9463    /// open, and on an answer, silence or timeout pick the text to post. The
9464    /// decision is saved before it is used, so it applies once.
9465    async fn settle_withheld(
9466        &mut self,
9467        winner: &Candidate,
9468        pr: &PrMessage,
9469        mut g: crate::run::GithubTextAsk,
9470    ) -> Result<Option<PrMessage>> {
9471        use crate::github_text as gt;
9472        let store = ask::Questions::open();
9473        let timeout = self.state.config.graph.answer_timeout;
9474        if !g.resolved {
9475            let mut standing = g
9476                .question
9477                .as_ref()
9478                .and_then(|id| store.list_for_effects().into_iter().find(|q| &q.id == id));
9479            if let Some(q) = standing.as_ref()
9480                && q.status.open()
9481                && !store.held_reply(&q.id)
9482                && gt::expired(q, timeout)
9483            {
9484                let why = format!("no answer within {}s of asking", timeout.max(1));
9485                standing = store
9486                    .update(&q.id, |q| {
9487                        q.abandon(&why);
9488                        Ok(())
9489                    })
9490                    .ok()
9491                    .map(|(q, ())| q);
9492            }
9493            let mut ask_again: Option<Option<Vec<String>>> = None;
9494            match standing {
9495                // Recorded but never written (a stop between the two saves),
9496                // or removed: ask again without spending the retry.
9497                None if g.asks <= 1 => {
9498                    g.asks = 0;
9499                    ask_again = Some(None);
9500                }
9501                None => {
9502                    g.resolved = true;
9503                    g.chosen_title = None;
9504                    g.choice = Some(GithubTextChoice::Fallback);
9505                }
9506                Some(q) if q.status.open() => {
9507                    self.park_on_github_text(&g)?;
9508                    return Ok(None);
9509                }
9510                Some(q) => match gt::read_reply(&q) {
9511                    gt::Reply::Fallback => {
9512                        g.resolved = true;
9513                        g.chosen_title = None;
9514                        g.choice = Some(GithubTextChoice::Fallback);
9515                    }
9516                    gt::Reply::Original => {
9517                        g.resolved = true;
9518                        g.chosen_title = None;
9519                        g.choice = Some(GithubTextChoice::Original);
9520                    }
9521                    gt::Reply::Rewrite => {
9522                        g.resolved = true;
9523                        g.chosen_title = None;
9524                        g.choice = Some(if g.rewrite.is_some() {
9525                            GithubTextChoice::Rewrite
9526                        } else {
9527                            GithubTextChoice::Fallback
9528                        });
9529                    }
9530                    gt::Reply::Title(text) => {
9531                        let first = text
9532                            .lines()
9533                            .map(str::trim)
9534                            .find(|l| !l.is_empty())
9535                            .unwrap_or("");
9536                        let decision = if first.is_empty() {
9537                            None
9538                        } else {
9539                            let candidate = PrMessage {
9540                                title: first.to_owned(),
9541                                body: String::new(),
9542                            };
9543                            self.judge_pr_language(&winner.worktree, &candidate).await
9544                        };
9545                        match gt::vet_title(
9546                            &text,
9547                            decision,
9548                            self.state.config.graph.github_english(),
9549                        ) {
9550                            Ok(title) => {
9551                                g.resolved = true;
9552                                g.chosen_title = Some(title);
9553                                g.choice = Some(GithubTextChoice::MyTitle);
9554                            }
9555                            Err(cats) if g.asks < 2 => {
9556                                ask_again = Some(Some(
9557                                    cats.into_iter().map(str::to_owned).collect::<Vec<_>>(),
9558                                ))
9559                            }
9560                            Err(_) => {
9561                                g.resolved = true;
9562                                g.chosen_title = None;
9563                                g.choice = Some(GithubTextChoice::Fallback);
9564                            }
9565                        }
9566                    }
9567                },
9568            }
9569            if let Some(rejected) = ask_again {
9570                // A retry (after a rejected replacement title) is still about
9571                // the original text: the same ORIGINAL / FALLBACK comparison.
9572                let w = gt::Withheld {
9573                    title: g.title,
9574                    body: g.body,
9575                    categories: g.categories.clone(),
9576                };
9577                // Named by the original text's fingerprint alone, so a resume
9578                // rewrites the same file and the detail stays identical.
9579                let artifact = match crate::run::write_artifact(
9580                    &self.state,
9581                    &gt::artifact_name(&gt::fingerprint(&pr.title, &pr.body)),
9582                    &gt::artifact_text(&w, &pr.title, &pr.body, &self.state.id, g.rewrite.as_ref()),
9583                ) {
9584                    Ok(p) => Some(p),
9585                    Err(e) => {
9586                        tracing::warn!("could not write the withheld-text artifact: {e:#}");
9587                        None
9588                    }
9589                };
9590                let (detail, comparison) = gt::question_content(
9591                    &w,
9592                    &pr.title,
9593                    &pr.body,
9594                    &self.state.id,
9595                    rejected.as_deref(),
9596                    artifact.as_deref(),
9597                    g.rewrite.as_ref(),
9598                );
9599                let mut q = ask::Question::new(
9600                    self.state.id.clone(),
9601                    gt::ASK_NODE.to_owned(),
9602                    gt::ASK_SEAT.to_owned(),
9603                    gt::question_summary(&self.state.config.graph.language, &w),
9604                    detail,
9605                    gt::question_choices(&w, g.rewrite.as_ref()),
9606                );
9607                q.posting_comparison = Some(comparison);
9608                q.answer_timeout = timeout;
9609                // Recorded before it is written: a stop in between leaves a
9610                // record naming a question the resume then files again.
9611                g.question = Some(q.id.clone());
9612                g.asks += 1;
9613                self.state.github_text = Some(g.clone());
9614                self.state.event(
9615                    "github-text",
9616                    format!("asking the owner about the withheld text ({})", q.short()),
9617                );
9618                self.state.save()?;
9619                store
9620                    .put_executable(&mut q)
9621                    .context("file the posting-gate question")?;
9622                if let Err(e) = ask::notify(&self.state.config.notify, &q).await {
9623                    tracing::warn!(
9624                        "could not notify about posting-gate question {}: {e:#}",
9625                        q.short()
9626                    );
9627                }
9628                self.park_on_github_text(&g)?;
9629                return Ok(None);
9630            }
9631        }
9632        let resolved = g.chosen_title.clone();
9633        let original = g.choice == Some(GithubTextChoice::Original);
9634        // Field names only: the event log never records the text.
9635        self.state.event(
9636            "github-text",
9637            if original {
9638                format!(
9639                    "posting the original text for: {}",
9640                    match (g.title, g.body) {
9641                        (true, true) => "title, description",
9642                        (true, false) => "title",
9643                        _ => "description",
9644                    }
9645                )
9646            } else if g.choice == Some(GithubTextChoice::Rewrite) && g.rewrite.is_some() {
9647                "posting the saved rewrite title and description".to_owned()
9648            } else if resolved.is_some() {
9649                "posting the owner's replacement title".to_owned()
9650            } else {
9651                "posting the neutral text for the withheld fields".to_owned()
9652            },
9653        );
9654        self.state.github_text = Some(g.clone());
9655        self.state.save()?;
9656        if g.choice == Some(GithubTextChoice::Rewrite)
9657            && let Some(r) = g.rewrite.as_ref()
9658        {
9659            return Ok(Some(PrMessage {
9660                title: r.title.clone(),
9661                body: r.body.clone(),
9662            }));
9663        }
9664        let w = gt::Withheld {
9665            title: g.title,
9666            body: g.body,
9667            categories: g.categories.clone(),
9668        };
9669        let (mut title, body) = gt::fallback_text(&w, &pr.title, &pr.body, &self.state.id);
9670        if let Some(t) = resolved {
9671            title = t;
9672        }
9673        // Every withheld field is now neutral or vetted English.
9674        let english = gt::LanguageDecision {
9675            title_english: true,
9676            body_english: true,
9677            body_complete: true,
9678        };
9679        let (mut title, mut body) = gt::prepare_with(&mut self.state, &title, &body, Some(english));
9680        if original {
9681            // The owner's explicit choice overrides the gate for the fields it
9682            // was made for; the others keep what the gate produced.
9683            if g.title {
9684                title = pr.title.clone();
9685            }
9686            if g.body {
9687                body = pr.body.clone();
9688            }
9689        }
9690        Ok(Some(PrMessage { title, body }))
9691    }
9692
9693    fn park_on_github_text(&mut self, g: &crate::run::GithubTextAsk) -> Result<()> {
9694        self.state.github_text = Some(g.clone());
9695        self.state.end_pass_parked(ParkCause::Question);
9696        self.state.parked = true;
9697        self.state.event(
9698            "github-text",
9699            "parked awaiting the owner's word on the withheld pull request text - resumes once answered",
9700        );
9701        self.state.save()
9702    }
9703
9704    /// Ask `[roles] language_judge` about this text and record which source
9705    /// decided; the text itself is never recorded.
9706    async fn judge_pr_language(
9707        &mut self,
9708        cwd: &Path,
9709        pr: &PrMessage,
9710    ) -> Option<crate::github_text::LanguageDecision> {
9711        self.state.config.roles.language_judge.as_ref()?;
9712        if !self.state.config.graph.language_gate() {
9713            return None;
9714        }
9715        let decision =
9716            crate::github_text::judge_language(&self.state.config, cwd, &pr.title, &pr.body).await;
9717        self.state.event(
9718            "github-text",
9719            if decision.is_some() {
9720                "language decided by the language judge"
9721            } else {
9722                "language judge unavailable; using built-in heuristics"
9723            },
9724        );
9725        decision
9726    }
9727
9728    fn merge(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
9729        Box::pin(self.merge_inner())
9730    }
9731
9732    async fn merge_inner(&mut self) -> Result<()> {
9733        if self.resource_halt()? || self.hold_base_sync().await? {
9734            return Ok(());
9735        }
9736        // Same reasoning as `gate`: ask the review and gate records directly
9737        // rather than `status`, which a solo-candidate `judge`/`deliberate`
9738        // skip can rewrite on reentry to something that no longer says
9739        // `Blocked`. `review_conclusion` is the same derivation `gate` uses,
9740        // so a hand-off (open findings, green verification) reaches merge
9741        // exactly like a genuinely clean round does.
9742        //
9743        // A run resumed mid-`land` never reaches here at all: `execute`
9744        // recognises `RunStatus::Landing` before it even calls `prep`, and
9745        // routes straight to `run_land` instead. That has to happen a level
9746        // up from this function, not with a check in here, because
9747        // `review_loop`'s own status recomputation (see its doc) runs
9748        // *before* `merge` on every reentry and would otherwise overwrite
9749        // the `Landing` marker with `Gating` before this node ever saw it.
9750        if self
9751            .state
9752            .base_sync
9753            .as_ref()
9754            .is_some_and(|s| s.conflict.is_some())
9755            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
9756                != Some(RunStatus::Gating)
9757            // `gate_ran == false` is not "passed" - `gate` leaves it false
9758            // both before it has ever run and when its last attempt was
9759            // resource-blocked (see `Runner::gate`'s own doc), and neither is
9760            // permission to merge on nothing but the review record. Only a
9761            // gate that actually ran may proceed; an intentional local
9762            // review can also finish with verification explicitly not configured.
9763            // `RunState::gate_status` computes that distinction.
9764            || !self.state.gate_allows_progress()
9765        {
9766            return Ok(());
9767        }
9768        // This node's own record, not `status`: `status == Ready` is not
9769        // unique to the harmless `MergeMode::None` path this line was
9770        // written for. `land` (below) sets it too, when a `MergeMode::Pr`
9771        // run's PR was closed without merging — and on that run `mode` is
9772        // still `Pr`, so a reentry that fell through here would push and
9773        // open a second pull request. `self.state.merge` is set exactly once
9774        // this node (or `land`) has already produced a verdict, under every
9775        // mode, which is what "already done" actually means here.
9776        if self.state.merge.is_some() && !self.state.pr_publication_pending {
9777            return Ok(());
9778        }
9779        let Some(winner) = self.state.winner().cloned() else {
9780            return Ok(());
9781        };
9782        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
9783        if self.state.gate_head.as_deref() != Some(head.as_str()) {
9784            self.state.status = RunStatus::Blocked;
9785            self.state.event(
9786                "gate",
9787                "winner changed after gate; fresh verification required",
9788            );
9789            self.state.save()?;
9790            return Ok(());
9791        }
9792        let wait = self.repository_wait();
9793        if !verify_current_head(&mut self.state, &winner, &wait).await? {
9794            return Ok(());
9795        }
9796        let repo = self.state.repo.clone();
9797        let base = self.state.base_branch.clone();
9798        let mode = self.state.config.merge.mode;
9799        let style = self.state.config.merge.style;
9800        let facts = if is_review_run(&self.state) {
9801            refresh_reviewed_commits(&mut self.state, &winner.branch).await;
9802            let start = review_base(
9803                &repo,
9804                &self.state.config.merge.remote,
9805                &base,
9806                &self.state.base_commit,
9807                &winner.branch,
9808            )
9809            .await;
9810            branch_facts(&repo, &start, &winner.branch).await
9811        } else {
9812            None
9813        };
9814        // `None` when the base could not be freshly read: then an adopted
9815        // pull request's title is left alone.
9816        let leaked = if is_review_run(&self.state) {
9817            leaked_subjects(&self.state, &winner.branch).await
9818        } else {
9819            Some(Vec::new())
9820        };
9821        // `None`: parked on the owner's word about a withheld title or body.
9822        // Nothing has been pushed or opened, and `merge` stays unrecorded so
9823        // the resume arrives here again.
9824        let Some(pr) = self
9825            .guarded_pr_message(&winner, facts.as_ref(), mode == MergeMode::Pr)
9826            .await?
9827        else {
9828            return Ok(());
9829        };
9830        let message = pr.commit_message();
9831
9832        let delivery_head = git::rev_parse(&winner.worktree, "HEAD").await?;
9833        if !crate::foreign_checkout::write_back(&mut self.state, &delivery_head).await? {
9834            return Ok(());
9835        }
9836        let outcome = match mode {
9837            MergeMode::None => MergeOutcome {
9838                mode,
9839                ok: true,
9840                detail: manual_merge_command(style, &repo, &winner.branch, &message),
9841                empty: false,
9842            },
9843            MergeMode::Pr | MergeMode::Local
9844                if merge_is_empty(&repo, &self.state, &winner.branch, mode).await =>
9845            {
9846                MergeOutcome {
9847                    mode,
9848                    ok: false,
9849                    detail: empty_candidate_detail(&self.state, &base),
9850                    empty: true,
9851                }
9852            }
9853            MergeMode::Local => {
9854                let on = git::current_branch(&repo).await?;
9855                if on.as_deref() != Some(base.as_str()) {
9856                    MergeOutcome {
9857                        mode,
9858                        ok: false,
9859                        detail: format!(
9860                            "{} has {} checked out, not the base branch {base}",
9861                            repo.display(),
9862                            on.unwrap_or_else(|| "a detached HEAD".to_owned())
9863                        ),
9864                        empty: false,
9865                    }
9866                } else if !git::is_clean(&repo).await? {
9867                    MergeOutcome {
9868                        mode,
9869                        ok: false,
9870                        detail: format!("{} is dirty; refusing to merge", repo.display()),
9871                        empty: false,
9872                    }
9873                } else {
9874                    let out = match style {
9875                        MergeStyle::Merge => {
9876                            git::merge_no_ff(&repo, &winner.branch, &message).await?
9877                        }
9878                        MergeStyle::Squash => {
9879                            git::merge_squash(&repo, &winner.branch, &message).await?
9880                        }
9881                        MergeStyle::Rebase => git::merge_ff_only(&repo, &winner.branch).await?,
9882                    };
9883                    MergeOutcome {
9884                        mode,
9885                        ok: out.ok(),
9886                        detail: if out.ok() { out.stdout } else { out.stderr },
9887                        empty: false,
9888                    }
9889                }
9890            }
9891            MergeMode::Pr if self.state.task_pr_branch().is_some() => {
9892                self.state.pr_publication_pending = true;
9893                self.state.save()?;
9894                let out =
9895                    crate::pr_head::publish(&mut self.state, &winner, &pr.title, &pr.body).await;
9896                self.state.pr_publication_pending = out.is_err();
9897                MergeOutcome {
9898                    mode,
9899                    ok: out.is_ok(),
9900                    detail: match out {
9901                        Ok(url) => url,
9902                        Err(e) => format!("{e:#}"),
9903                    },
9904                    empty: false,
9905                }
9906            }
9907            MergeMode::Pr => {
9908                let remote = self.state.config.merge.remote.clone();
9909                let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
9910                let pushed = if self.state.foreign_checkout.is_some() {
9911                    let refspec = format!("{delivery_head}:refs/heads/{public}");
9912                    git::git_raw(&winner.worktree, &["push", &remote, &refspec]).await?
9913                } else {
9914                    git::push(&winner.worktree, &remote, &winner.branch).await?
9915                };
9916                if !pushed.ok() {
9917                    MergeOutcome {
9918                        mode,
9919                        ok: false,
9920                        detail: pushed.stderr,
9921                        empty: false,
9922                    }
9923                } else {
9924                    if self.state.foreign_checkout.is_some() {
9925                        self.state.pr_pushed_head = Some(delivery_head.clone());
9926                    }
9927                    // A retry or resume of a run whose branch already has an
9928                    // open pull request adopts it rather than failing on a
9929                    // duplicate. Only this winner branch into this base:
9930                    // `branch_for` derives the name from the run id, so a
9931                    // different run's pull request never matches.
9932                    let found = land::find_open_pr(&winner.worktree, &public, &base).await;
9933                    let out = match pr_merge_plan(found) {
9934                        PrPlan::Create => {
9935                            gh_pr_create(&winner.worktree, &base, &public, &pr.title, &pr.body)
9936                                .await
9937                        }
9938                        PrPlan::Adopt { url, title } => {
9939                            self.state
9940                                .event("merge", format!("Pr: adopted open pull request {url}"));
9941                            if self.state.explicit_github_text_selection() {
9942                                // An explicit publication selection applies the prepared
9943                                // payload; acceptance alone is not publication proof.
9944                                land::set_pr_text_verbatim(
9945                                    &winner.worktree,
9946                                    &url,
9947                                    &pr.title,
9948                                    &pr.body,
9949                                )
9950                                .await
9951                                .map(|()| url)
9952                            } else {
9953                                if title != pr.title
9954                                    && (!is_review_run(&self.state)
9955                                        || leaked
9956                                            .as_deref()
9957                                            .is_some_and(|l| should_retitle(&title, &pr.title, l)))
9958                                    && let Err(e) =
9959                                        if self.state.github_text.as_ref().is_some_and(|g| {
9960                                            g.resolved
9961                                                && g.title
9962                                                && g.choice == Some(GithubTextChoice::Original)
9963                                        }) {
9964                                            // The owner chose to post this title unmodified.
9965                                            land::set_pr_title_verbatim(
9966                                                &winner.worktree,
9967                                                &url,
9968                                                &pr.title,
9969                                            )
9970                                            .await
9971                                        } else {
9972                                            land::set_pr_title(
9973                                                &mut self.state,
9974                                                &winner.worktree,
9975                                                &url,
9976                                                &pr.title,
9977                                            )
9978                                            .await
9979                                        }
9980                                {
9981                                    tracing::warn!("could not refresh title of {url}: {e:#}");
9982                                    self.state
9983                                        .event("merge", format!("Pr: title refresh failed: {e:#}"));
9984                                }
9985                                Ok(url)
9986                            }
9987                        }
9988                        PrPlan::Stop(why) => Err(anyhow::anyhow!(why)),
9989                    };
9990                    match out {
9991                        Ok(url) => MergeOutcome {
9992                            mode,
9993                            ok: true,
9994                            detail: url,
9995                            empty: false,
9996                        },
9997                        Err(e) => MergeOutcome {
9998                            mode,
9999                            ok: false,
10000                            detail: e.to_string(),
10001                            empty: false,
10002                        },
10003                    }
10004                }
10005            }
10006        };
10007
10008        self.state.status = match (mode, outcome.ok) {
10009            (MergeMode::None, _) => RunStatus::Ready,
10010            (_, true) if outcome.empty => RunStatus::Ready,
10011            (MergeMode::Pr, true) => RunStatus::Ready,
10012            (_, true) => RunStatus::Merged,
10013            (_, false) => RunStatus::Blocked,
10014        };
10015        self.state.event(
10016            "merge",
10017            format!(
10018                "{:?}: {}",
10019                mode,
10020                outcome.detail.lines().next().unwrap_or("")
10021            ),
10022        );
10023        if mode == MergeMode::Pr && outcome.ok && !outcome.empty {
10024            self.state.record_github_text_publication(&outcome.detail);
10025        }
10026        self.state.merge = Some(outcome);
10027        self.state.save()?;
10028
10029        // The PR is open and the run would historically stop here, leaving the
10030        // operator to watch checks, feed review comments back to a fixer, and
10031        // merge. That was done by hand six times in one session before this
10032        // existed. Opt-in, because merging is the one irreversible thing magi
10033        // can do to a repository.
10034        if self.state.config.graph.land
10035            && mode == MergeMode::Pr
10036            && self.state.merge.as_ref().is_some_and(|m| m.ok && !m.empty)
10037        {
10038            self.run_land().await?;
10039        }
10040        // `run_land` may have left `status` at `Landing` - still waiting on
10041        // CI or the owner's approval, not actually settled - so this has to
10042        // read whatever `status` ended up as here, not the `Merged` this
10043        // function set a few lines up.
10044        self.settle_questions();
10045        Ok(())
10046    }
10047
10048    /// Enter `land`.
10049    ///
10050    /// Shared between a fresh run's first pass through [`Runner::merge`] and
10051    /// a resumed run's re-entry. `land::land` itself is what serialises the
10052    /// two git-mutating moments inside the loop — the rebase push and
10053    /// `gh pr merge` — per repository (see its own doc); nothing here needs
10054    /// to hold a lock across the whole call, and doing so would serialise
10055    /// this run's CI wait against a *different* run's land-approval resume
10056    /// in the same repository, which is exactly the "must not wait on
10057    /// another task" property the daemon's slot-freeing exists to give.
10058    fn run_land(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
10059        Box::pin(self.run_land_inner())
10060    }
10061
10062    async fn run_land_inner(&mut self) -> Result<()> {
10063        crate::pr_head::ensure_owner(&self.state)?;
10064        let url = self
10065            .state
10066            .pr
10067            .as_ref()
10068            .map(|pr| pr.url.clone())
10069            .or_else(|| self.state.merge.as_ref().map(|m| m.detail.clone()))
10070            .unwrap_or_default();
10071        let url = url.lines().next().unwrap_or("").trim().to_owned();
10072        if !url.starts_with("http") {
10073            return Ok(());
10074        }
10075        // A land failure is not a lost run: the work is on a branch and the
10076        // pull request is open, which is exactly where a human takes over.
10077        loop {
10078            match land::land(&mut self.state, &url).await {
10079                Ok(_)
10080                    if self
10081                        .state
10082                        .merge_repairs
10083                        .last()
10084                        .is_some_and(|r| r.phase == crate::run::MergeRepairPhase::Requested) =>
10085                {
10086                    if self.repair_merge_review().await? {
10087                        continue;
10088                    }
10089                }
10090                Ok(_) if self.state.resource_block.is_some() => {
10091                    return self.stop_for_resource();
10092                }
10093                Ok(pr) if self.state.parked => {
10094                    // `land` already saved the parked marker; nothing here
10095                    // overrides `status` back to a terminal value while an
10096                    // approval is still outstanding.
10097                    let _ = pr;
10098                }
10099                Ok(_) if self.state.merge_decision.as_ref().is_some_and(|d| d.closed) => {
10100                    self.state.status = RunStatus::Superseded;
10101                    self.state.save()?;
10102                }
10103                Ok(pr) => {
10104                    self.state.status = match pr.state {
10105                        land::PrLifecycle::Merged => RunStatus::Merged,
10106                        _ => RunStatus::Blocked,
10107                    };
10108                    // Downstream of a confirmed merge only - see
10109                    // `bump::should_release_bump`'s own doc for why this one
10110                    // check covers all three of `land`'s success paths.
10111                    // Best-effort: the run already landed, so a failure here
10112                    // (the decision call, `gh`, `cargo`) is recorded and never
10113                    // turns a landed run into a failed one.
10114                    if bump::should_release_bump(self.state.status)
10115                        && let Err(e) = bump::after_merge(&mut self.state, &pr.url).await
10116                    {
10117                        // The event is the run's own record. Not-eligible cases
10118                        // (disabled, no `Cargo.toml`, ...) return `Ok`, so an
10119                        // `Err` is a bump that was tried and failed:
10120                        // `after_merge` itself raises the operator notice for
10121                        // that, whether or not a release PR exists yet.
10122                        self.state
10123                            .event("bump", format!("release bump skipped: {e:#}"));
10124                    }
10125                    // Independent of the bump, and best-effort in the same way:
10126                    // findings the merge left open become follow-up tasks.
10127                    if self.state.status == RunStatus::Merged {
10128                        crate::followup::after_merge(&mut self.state, &pr.url).await;
10129                    }
10130                    self.state.save()?;
10131                }
10132                Err(e) => {
10133                    if e.is::<crate::repo_lock::ResourceBlocked>() {
10134                        return Err(e);
10135                    }
10136                    self.state.status = RunStatus::Blocked;
10137                    self.state.event("land", format!("gave up: {e}"));
10138                    self.state.save()?;
10139                }
10140            }
10141            break;
10142        }
10143        Ok(())
10144    }
10145
10146    /// One repair cycle stays under the existing driver/task claim. An
10147    /// interrupted fixer is rolled back and held rather than run twice.
10148    async fn repair_merge_review(&mut self) -> Result<bool> {
10149        use crate::run::MergeRepairPhase as Phase;
10150        crate::pr_head::ensure_owner(&self.state)?;
10151        let i = self.state.merge_repairs.len() - 1;
10152        let request = self.state.merge_repairs[i].clone();
10153        if request.phase == Phase::Fixing {
10154            let restored = match self.state.winner().cloned() {
10155                Some(winner) => self.graft_restore(&winner.worktree, &request.head).await,
10156                None => Err(anyhow::anyhow!("repair has no winning branch")),
10157            };
10158            let why = match restored {
10159                Ok(()) => "repair was interrupted during the fixer and rolled back; inspect its artifacts and the PR head, then run an explicit review".to_owned(),
10160                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => return Err(e),
10161                Err(e) => format!("repair was interrupted; rollback failed: {e:#}; restore the reviewed branch before running an explicit review"),
10162            };
10163            self.hold_merge_repair(i, why)?;
10164            return Ok(false);
10165        }
10166        // A completed repair gate is a publication checkpoint. On reentry,
10167        // reject external changes before the ordinary gate path can replace
10168        // that evidence by verifying a new head. Requested repairs still
10169        // start their own review generation below.
10170        if request.phase == Phase::Reviewing && self.state.gate_ran {
10171            let winner = self
10172                .state
10173                .winner()
10174                .context("repair has no winning branch")?;
10175            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
10176            if self.state.gate_head.as_deref() != Some(head.as_str())
10177                || !git::is_clean(&winner.worktree).await?
10178            {
10179                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())?;
10180                return Ok(false);
10181            }
10182        }
10183        let failure = if i >= self.state.config.graph.land_rounds
10184            || self.state.config.graph.review_rounds == 0
10185        {
10186            Some("repair generation budget exhausted or review disabled; increase the configured budget and request a new review explicitly".to_owned())
10187        } else {
10188            None
10189        };
10190        if let Some(why) = failure {
10191            self.hold_merge_repair(i, why)?;
10192            return Ok(false);
10193        }
10194        if request.phase == Phase::Requested {
10195            let pr = match land::repair_preflight(&self.state, &request.pr, &request.head).await {
10196                Ok(pr) => pr,
10197                Err(e) => {
10198                    self.hold_merge_repair(i, format!("cannot resume repair: {e:#}; restore the reviewed PR branch and run an explicit review"))?;
10199                    return Ok(false);
10200                }
10201            };
10202            self.state.merge_repairs[i].phase = Phase::Fixing;
10203            self.state.land_approval = None;
10204            self.state.land_armed_head = None;
10205            self.state.save()?;
10206            // Serialize the exact records, including finding ids/details,
10207            // reconsideration reasons, final votes and verification output.
10208            let evidence = serde_json::to_string_pretty(&request)?;
10209            let reason = format!(
10210                "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}"
10211            );
10212            let budget = self.state.config.graph.land_rounds;
10213            let result = land::fix_round(&mut self.state, &pr, i + 1, budget, &reason, "").await;
10214            match result {
10215                Ok(land::Fixed::Committed { .. } | land::Fixed::Declined) => {}
10216                Ok(land::Fixed::Deferred) => {
10217                    // An unavailable fixer did not spend this repair request.
10218                    // Restore partial fallback work before retrying it, as for
10219                    // an interrupted repair, without closing the request.
10220                    let worktree = self
10221                        .state
10222                        .winner()
10223                        .context("repair has no winning branch")?
10224                        .worktree
10225                        .clone();
10226                    self.graft_restore(&worktree, &request.head).await?;
10227                    self.state.merge_repairs[i].phase = Phase::Requested;
10228                    self.stop_for_resource()?;
10229                    return Ok(false);
10230                }
10231                Ok(land::Fixed::Failed(why)) => {
10232                    self.hold_merge_repair(
10233                        i,
10234                        format!(
10235                            "repair failed: {why}; inspect the branch and run an explicit review"
10236                        ),
10237                    )?;
10238                    return Ok(false);
10239                }
10240                Err(e) => {
10241                    self.hold_merge_repair(
10242                        i,
10243                        format!(
10244                            "repair failed: {e:#}; inspect the branch and run an explicit review"
10245                        ),
10246                    )?;
10247                    return Ok(false);
10248                }
10249            }
10250            // Even no change gets a real new reviewer wave. The previous
10251            // evidence remains in the request; a former clean/concluded round
10252            // cannot short-circuit the new review or gate.
10253            self.begin_merge_repair_review(i)?;
10254        }
10255        self.review_loop().await?;
10256        self.gate().await?;
10257        if self.resource_halt()? || self.state.parked {
10258            return Ok(false);
10259        }
10260        if review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
10261            != Some(RunStatus::Gating)
10262            || !self.state.gate_allows_progress()
10263        {
10264            self.hold_merge_repair(i, "updated review or gate did not pass; inspect the new results and resume review explicitly".to_owned())?;
10265            return Ok(false);
10266        }
10267        // Review and gate may have added commits after the initial repair.
10268        // Publish exactly their final head to the existing PR, with a lease.
10269        let winner = self
10270            .state
10271            .winner()
10272            .cloned()
10273            .context("repair has no winning branch")?;
10274        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
10275        if self.state.gate_head.as_deref() != Some(after.as_str())
10276            || !git::is_clean(&winner.worktree).await?
10277        {
10278            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())?;
10279            return Ok(false);
10280        }
10281        let expected = self
10282            .state
10283            .pr_pushed_head
10284            .as_deref()
10285            .unwrap_or(&request.head)
10286            .to_owned();
10287        let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
10288        // Push the checked commit itself: a local ref moving after the check
10289        // must not change which commit the forge receives.
10290        if !crate::foreign_checkout::write_back(&mut self.state, &after).await? {
10291            return Ok(false);
10292        }
10293        let lease = format!("--force-with-lease=refs/heads/{public}:{expected}");
10294        let refspec = format!("{after}:refs/heads/{public}");
10295        let push = git::git_raw(
10296            &winner.worktree,
10297            &["push", &lease, &self.state.config.merge.remote, &refspec],
10298        )
10299        .await;
10300        match push {
10301            Ok(out) if out.ok() => self.state.pr_pushed_head = Some(after),
10302            Ok(out) => {
10303                self.hold_merge_repair(i, format!("publishing reviewed repair failed: {}; inspect the PR head and resume review explicitly", out.stderr))?;
10304                return Ok(false);
10305            }
10306            Err(e) => {
10307                self.hold_merge_repair(i, format!("publishing reviewed repair failed: {e:#}; inspect the PR head and resume review explicitly"))?;
10308                return Ok(false);
10309            }
10310        }
10311        self.state.merge_repairs[i].phase = Phase::Complete;
10312        self.state.status = RunStatus::Landing;
10313        self.state.event(
10314            "repair",
10315            "new review and gate completed; fresh owner merge decision required",
10316        );
10317        self.state.save()?;
10318        Ok(true)
10319    }
10320
10321    fn merge_repair_artifacts(&self) -> PathBuf {
10322        let artifacts = agent::artifacts_dir(&self.state.dir());
10323        match self
10324            .state
10325            .merge_repairs
10326            .last()
10327            .filter(|r| r.phase == crate::run::MergeRepairPhase::Reviewing)
10328        {
10329            Some(r) => artifacts.join(format!("merge-repair-{}", r.question)),
10330            None => artifacts,
10331        }
10332    }
10333
10334    fn begin_merge_repair_review(&mut self, index: usize) -> Result<()> {
10335        if let Some(e2e) = self.state.head_e2e.take() {
10336            self.state
10337                .verification_history
10338                .push(crate::run::VerificationEvidence {
10339                    superseded_by: None,
10340                    archived_at: Some(Timestamp::now()),
10341                    fixes_spent: Some(self.state.gate_fixes.len()),
10342                    gate_head: None,
10343                    gate_ran: false,
10344                    gate: Vec::new(),
10345                    e2e: Some(e2e),
10346                });
10347        }
10348        self.state.reviews.clear();
10349        self.state.gate.clear();
10350        self.state.gate_ran = false;
10351        self.state.gate_head = None;
10352        self.state.gate_fixes.clear();
10353        self.state.gate_repair_e2e = None;
10354        self.state.pre_gate.clear();
10355        self.state.pre_gate_commit = None;
10356        self.state.contested_handoff = None;
10357        self.state.land_reruns = None;
10358        self.state.land_approval = None;
10359        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Reviewing;
10360        self.state.status = RunStatus::Reviewing;
10361        self.state.save()
10362    }
10363
10364    fn hold_merge_repair(&mut self, index: usize, why: String) -> Result<()> {
10365        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Failed;
10366        self.state.merge_repairs[index].failure = Some(why.clone());
10367        self.state.status = RunStatus::Blocked;
10368        self.state.event("repair", why);
10369        self.state.save()
10370    }
10371
10372    // -------------------------------------------------------------- helpers
10373
10374    /// Fetch or create a seat, keeping its conversation across nodes.
10375    fn seat(&mut self, key: &str, agent: &str) -> SeatState {
10376        if let Some(existing) = self.state.seats.get(key)
10377            && existing.agent == agent
10378        {
10379            return existing.clone();
10380        }
10381        // A seat that changes agent mints its session id from the agent too,
10382        // like a handover: the old agent's uuid is already taken by the CLI.
10383        let fresh = if self.state.seats.contains_key(key) {
10384            handover_seat(key, agent, self.state.next_seat_seed())
10385        } else {
10386            SeatState::new(key, agent, self.state.seed)
10387        };
10388        self.state.seats.insert(key.to_owned(), fresh.clone());
10389        fresh
10390    }
10391
10392    /// The agent now holding seat `key`: `spec`, unless a handover moved the
10393    /// seat to another roster agent, in which case that agent. Nodes that
10394    /// continue a seat's conversation (deliberation, the votes, a reviewer's
10395    /// reconsideration) must keep talking to whoever answered it, not slip
10396    /// back to the agent that failed it.
10397    fn occupant(&self, key: &str, spec: AgentSpec) -> AgentSpec {
10398        match self.state.seats.get(key) {
10399            Some(s) if s.agent != spec.id => {
10400                self.state.config.agent(&s.agent).cloned().unwrap_or(spec)
10401            }
10402            _ => spec,
10403        }
10404    }
10405
10406    /// A candidate rendered for judging, with the leak policy applied.
10407    fn view(&self, c: &Candidate) -> CandidateView {
10408        let raw = crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
10409            .unwrap_or_default();
10410        let (patch, _) = blind::sanitize_patch(
10411            &format!("candidate {} patch", c.label),
10412            &raw,
10413            &self.state.config.blind,
10414        );
10415        CandidateView {
10416            label: c.label,
10417            branch: c.branch.clone(),
10418            summary: c.summary.clone(),
10419            stat: c.stat.clone(),
10420            patch,
10421        }
10422    }
10423
10424    /// The full candidate set as prompt text, for seats with no live session.
10425    fn candidate_block(&self, candidates: &[Candidate], base_short: &str) -> String {
10426        let views: Vec<CandidateView> = candidates.iter().map(|c| self.view(c)).collect();
10427        prompt::judge(
10428            "(see above)",
10429            &views,
10430            self.roles.judges.len(),
10431            base_short,
10432            "en",
10433        )
10434    }
10435
10436    /// The final-vote prompt with everything a seat that has no session of its
10437    /// own needs: the candidates, the seat's own ranking and reasons, and the
10438    /// anonymised deliberation it took part in (only when there was one, so a
10439    /// handed-over seat never sees more than the seat it replaces did). The
10440    /// `Final vote` heading stays first.
10441    fn vote_prompt_full(
10442        &self,
10443        j: usize,
10444        labels: &[char],
10445        language: &str,
10446        candidates: &[Candidate],
10447        base_short: &str,
10448    ) -> String {
10449        let mut text = format!(
10450            "{}\n\n# The task the candidates were given\n\n{}\n\n# Candidates\n\n{}",
10451            prompt::final_vote(labels, language),
10452            self.state.instruction,
10453            self.candidate_block(candidates, base_short)
10454        );
10455        if let Some(own) = self
10456            .state
10457            .judgements
10458            .get(j)
10459            .filter(|r| !r.ranking.is_empty())
10460        {
10461            let reasons = own
10462                .reasons
10463                .iter()
10464                .map(|(k, v)| format!("- {k}: {v}"))
10465                .collect::<Vec<_>>()
10466                .join("\n");
10467            text.push_str(&format!(
10468                "\n\n# Your own earlier ranking\n\nYou ranked {}{}{reasons}\n",
10469                own.ranking.iter().collect::<String>(),
10470                if reasons.is_empty() {
10471                    ""
10472                } else {
10473                    ", because:\n"
10474                }
10475            ));
10476        }
10477        if !self.state.deliberation.is_empty() {
10478            text.push_str("\n# What was argued before this vote\n");
10479            for t in self.transcript(&[], j) {
10480                text.push_str(&format!(
10481                    "\n## {}{}\n\n{}\n",
10482                    t.who,
10483                    if t.is_self { " (you)" } else { "" },
10484                    t.body.trim()
10485                ));
10486            }
10487        }
10488        text
10489    }
10490
10491    /// Anonymised transcript for judge `self_idx`.
10492    ///
10493    /// The initial rankings are always the opening statements. Seeding them
10494    /// only when no turn had been taken yet meant every judge after the first
10495    /// argued against a single voice instead of against the actual split — the
10496    /// disagreement is the information, so it is always on the table.
10497    fn transcript(&self, current: &[DeliberationTurn], self_idx: usize) -> Vec<Turn> {
10498        let mut turns = Vec::new();
10499        for j in &self.state.judgements {
10500            if j.ranking.is_empty() {
10501                continue;
10502            }
10503            let reasons = j
10504                .reasons
10505                .iter()
10506                .map(|(k, v)| format!("- {k}: {v}"))
10507                .collect::<Vec<_>>()
10508                .join("\n");
10509            turns.push(Turn {
10510                who: format!("Judge {} (opening ranking)", j.judge),
10511                is_self: j.judge == self_idx + 1,
10512                body: format!(
10513                    "Ranked {}{}{reasons}",
10514                    j.ranking.iter().collect::<String>(),
10515                    if reasons.is_empty() {
10516                        ""
10517                    } else {
10518                        ", because:\n"
10519                    }
10520                ),
10521            });
10522        }
10523        for t in self
10524            .state
10525            .deliberation
10526            .iter()
10527            .flat_map(|r| r.turns.iter())
10528            .chain(current)
10529        {
10530            turns.push(Turn {
10531                who: format!("Judge {}", t.judge),
10532                is_self: t.judge == self_idx + 1,
10533                body: t.body.clone(),
10534            });
10535        }
10536        turns
10537    }
10538}
10539
10540/// Does this seat still hold the context a follow-up prompt would rely on?
10541fn has_context(spec: &AgentSpec, seat: &SeatState, sessions: bool) -> bool {
10542    agent::has_session(spec.kind, seat, sessions)
10543}
10544
10545/// The next entry in `roster` after `start`, never wrapping back to the
10546/// front, whose id is not in `tried` yet.
10547///
10548/// Starts one past `start` rather than at the front of `roster`: `start` is
10549/// the seat's own original position, and a seat whose candidate slot already
10550/// sits on the roster's second entry must fall through to the third next, not
10551/// restart at the first — which is very likely a different candidate's own
10552/// agent already. Never wraps back past `start`, for the same reason: an
10553/// entry earlier in the roster than the seat's own position is almost
10554/// certainly some *other* candidate slot's own agent, and once the tail of
10555/// the roster is exhausted there are no more untried agents for *this* seat
10556/// to fall through to — the caller's fallback chain ends there, exactly as
10557/// "no further untried agents remain in the list for that seat" asks for.
10558///
10559/// Matched by [`AgentSpec::id`], never the whole spec: a roster that names
10560/// the same id twice (an operator's `roles.implementers` typo, or a
10561/// `[[agents]]` list reused across roles) must not let
10562/// [`Runner::resume_seat_handovers`] retry that id forever — one forward pass
10563/// over `roster` either finds an untried id or runs out, so this always
10564/// terminates regardless of duplicates.
10565fn next_untried_in_roster<'a>(
10566    roster: &'a [AgentSpec],
10567    start: usize,
10568    tried: &BTreeSet<String>,
10569) -> Option<&'a AgentSpec> {
10570    roster
10571        .get(start + 1..)?
10572        .iter()
10573        .find(|s| !tried.contains(&s.id))
10574}
10575
10576/// The successor for a seat, shared by all four seat kinds (implement, judge,
10577/// review, advise). `others` holds the ids that *currently* occupy the other
10578/// seats of the same wave (after any earlier handover, as [`Runner::occupant`]
10579/// sees them), so roster entries beyond the seat count act as spares: a failed
10580/// seat goes to an agent no other seat holds whenever the roster permits.
10581///
10582/// `carried` is `Some` only for the review loop's carried failure history.
10583/// Order: (1) forward from `start`, never wrapping, untried, not a carried
10584/// failure, not another seat's occupant; (2) with `carried`, a rescue over the
10585/// whole roster: untried and not another seat's occupant; (3) the plain walk
10586/// ([`next_untried_in_roster`] / [`next_for_seat`]) that ignores `others`.
10587/// Step 3 is deliberate: a duplicate agent on two seats is a worse panel but
10588/// a better outcome than an empty seat, and it keeps the answer to "is there
10589/// a successor at all" exactly what it was before occupants were considered,
10590/// so no handover rule (`should_hand_over`, nudges, the tried-once bound)
10591/// moves. The rescue excludes occupants too, on the same reasoning: retrying a
10592/// carried failure is a cheaper bet than doubling an agent on the panel, and
10593/// if it fails again `tried` bounds it and step 3 takes over. Seats failing in
10594/// the same round are handled one at a time, so a seat later in the batch
10595/// sees an earlier one's new occupant but not yet its own freed agent.
10596fn pick_successor<'a>(
10597    roster: &'a [AgentSpec],
10598    start: usize,
10599    tried: &BTreeSet<String>,
10600    carried: Option<&BTreeSet<String>>,
10601    others: &BTreeSet<String>,
10602) -> Option<&'a AgentSpec> {
10603    let free = |s: &&AgentSpec| !tried.contains(&s.id) && !others.contains(&s.id);
10604    roster
10605        .get(start + 1..)
10606        .and_then(|tail| {
10607            tail.iter()
10608                .filter(free)
10609                .find(|s| carried.is_none_or(|c| !c.contains(&s.id)))
10610        })
10611        .or_else(|| {
10612            carried
10613                .is_some()
10614                .then(|| roster.iter().find(free))
10615                .flatten()
10616        })
10617        .or_else(|| match carried {
10618            Some(c) => next_for_seat(roster, start, tried, c),
10619            None => next_untried_in_roster(roster, start, tried),
10620        })
10621}
10622
10623/// The next agent for a seat that carries its failure history across rounds
10624/// (the review loop). `round_tried` is this round's own bound and starts
10625/// empty every round; `carried_failed` only decides priority.
10626///
10627/// First: an id walking forward from `start`, never wrapping, that is neither
10628/// tried this round nor failed in an earlier one. Only when that is exhausted
10629/// does it rescue: the first roster id (in roster order, so this one *does*
10630/// look before `start`) not yet tried this round, which is by then a carried
10631/// failure. Each id is rescued at most once per round, so it cannot loop.
10632fn next_for_seat<'a>(
10633    roster: &'a [AgentSpec],
10634    start: usize,
10635    round_tried: &BTreeSet<String>,
10636    carried_failed: &BTreeSet<String>,
10637) -> Option<&'a AgentSpec> {
10638    roster
10639        .get(start + 1..)?
10640        .iter()
10641        .find(|s| !round_tried.contains(&s.id) && !carried_failed.contains(&s.id))
10642        .or_else(|| roster.iter().find(|s| !round_tried.contains(&s.id)))
10643}
10644
10645/// Where a reviewer seat starts a round: the agent that last answered it when
10646/// it is still on the roster and not marked failed, else the spec's own agent
10647/// unless it failed, else the next roster agent that has not failed, else the
10648/// spec's own agent again (the whole roster failed). Ids no longer on the
10649/// roster are ignored. An empty roster has no handover, so the spec stands.
10650fn pick_start_spec(roster: &[AgentSpec], spec: AgentSpec, hist: Option<&SeatHistory>) -> AgentSpec {
10651    let Some(h) = hist.filter(|_| !roster.is_empty()) else {
10652        return spec;
10653    };
10654    let ok = |id: &str| !h.failed.contains(id);
10655    if let Some(last) = h.last_ok.as_deref()
10656        && ok(last)
10657        && let Some(s) = roster.iter().find(|s| s.id == last)
10658    {
10659        return s.clone();
10660    }
10661    if ok(&spec.id) {
10662        return spec;
10663    }
10664    let from = roster.iter().position(|s| s.id == spec.id).unwrap_or(0);
10665    roster
10666        .get(from + 1..)
10667        .into_iter()
10668        .flatten()
10669        .chain(roster.iter())
10670        .find(|s| ok(&s.id))
10671        .cloned()
10672        .unwrap_or(spec)
10673}
10674
10675/// A fresh seat for the agent taking over `key`. Mixes the agent id into the
10676/// seed so a CLI that mints its session id up front (`--session-id`) never
10677/// reuses the uuid the previous agent already opened under the same seat key.
10678pub(crate) fn handover_seat(key: &str, agent: &str, run_seed: u64) -> SeatState {
10679    SeatState::new(key, agent, run_seed ^ crate::rng::fnv1a(agent))
10680}
10681
10682/// What an agent's turn timed out as, in [`AgentOutcome::Failed`]. One const
10683/// so the classifier below and the code that builds the message cannot drift.
10684const TIMED_OUT: &str = "timed out";
10685
10686impl FailClass {
10687    /// `None` for an answer; otherwise how the turn failed.
10688    fn of(out: &AgentOutcome) -> Option<Self> {
10689        match out {
10690            AgentOutcome::Ok(_) => None,
10691            AgentOutcome::Quota(_) => Some(Self::Quota),
10692            AgentOutcome::Dropped(_) => Some(Self::Other("dropped".to_owned())),
10693            AgentOutcome::Failed(e) if e == TIMED_OUT => Some(Self::Timeout),
10694            AgentOutcome::Failed(e) => Some(Self::Other(failure_signature(e))),
10695            // Not a failure of the agent. Callers check for it first; `None`
10696            // here means "no class to hand over on".
10697            AgentOutcome::ResourceBlocked(_) => None,
10698        }
10699    }
10700
10701    /// The word in a handover's artifact stem (`impl-A-quota-beta`).
10702    fn stem_word(&self) -> &'static str {
10703        match self {
10704            Self::Quota => "quota",
10705            _ => "handover",
10706        }
10707    }
10708}
10709
10710/// The message's first line with its variable parts removed — digit runs and
10711/// path-like tokens — so "exit code 2" and "exit code 7" read
10712/// as one kind of failure.
10713fn failure_signature(msg: &str) -> String {
10714    let mut line = msg.lines().next().unwrap_or("").trim().to_lowercase();
10715    // `SeatHistory::last_fail` persists these signatures across resumes. Keep
10716    // the historical machine key while the process diagnosis uses readable prose.
10717    if let Some(code) = line
10718        .strip_prefix("process exited with no usable output (exit code ")
10719        .and_then(|s| s.strip_suffix(')'))
10720        .and_then(|s| s.parse::<i32>().ok())
10721    {
10722        line = format!("exited with some({code}) and no usable output");
10723    } else if matches!(
10724        line.as_str(),
10725        "process exited with no usable output (no exit code reported)"
10726            | "process exited with no usable output (exit code unavailable)"
10727    ) {
10728        line = "exited with none and no usable output".to_owned();
10729    }
10730    let mut out = Vec::new();
10731    for word in line.split_whitespace() {
10732        if word.contains('/') || word.contains('\\') {
10733            out.push("<path>".to_owned());
10734            continue;
10735        }
10736        let mut w = String::new();
10737        let mut in_digits = false;
10738        for c in word.chars() {
10739            if c.is_ascii_digit() {
10740                if !in_digits {
10741                    w.push('#');
10742                }
10743                in_digits = true;
10744            } else {
10745                in_digits = false;
10746                w.push(c);
10747            }
10748        }
10749        out.push(w);
10750    }
10751    out.join(" ").chars().take(120).collect()
10752}
10753
10754/// Whether a seat that just failed with `cur` may go to the next roster agent.
10755/// A quota or a timeout always may. Any other failure may not when the agent
10756/// before it failed the same way: an error the prompt causes would otherwise
10757/// walk the whole roster. `prev` is the class of the immediately preceding
10758/// agent's failure, so a quota or timeout in between breaks the run of
10759/// identical failures by itself.
10760fn should_hand_over(prev: Option<&FailClass>, cur: &FailClass) -> bool {
10761    match cur {
10762        FailClass::Quota | FailClass::Timeout => true,
10763        FailClass::Other(_) => prev != Some(cur),
10764    }
10765}
10766
10767/// A short human reason for a failed outcome, for the handover record.
10768fn fail_reason(out: &AgentOutcome) -> String {
10769    match out {
10770        AgentOutcome::Ok(_) => String::new(),
10771        AgentOutcome::Quota(_) => "rate limited (quota)".to_owned(),
10772        AgentOutcome::Dropped(o) => format!(
10773            "the CLI dropped the stream ({})",
10774            o.dropped
10775                .as_ref()
10776                .map(|d| d.why.as_str())
10777                .unwrap_or("it ended without delivering its answer")
10778        ),
10779        AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
10780            e.lines().next().unwrap_or("").chars().take(160).collect()
10781        }
10782    }
10783}
10784
10785/// Note one handover in the run: the structured record and, in the timeline,
10786/// the sentence a person reads. A quota keeps the wording it always had.
10787pub(crate) fn record_handover(
10788    state: &mut RunState,
10789    node: &str,
10790    seat: &str,
10791    from: &str,
10792    to: &str,
10793    class: &FailClass,
10794    reason: &str,
10795) {
10796    let message = if *class == FailClass::Quota {
10797        format!("{seat}: rate limited (quota) on {from}; retrying with {to}")
10798    } else {
10799        format!("{seat}: handed over {from} -> {to} ({reason})")
10800    };
10801    state.event(node, message);
10802    state.handovers.push(Handover {
10803        at: Timestamp::now(),
10804        node: node.to_owned(),
10805        seat: seat.to_owned(),
10806        from: from.to_owned(),
10807        to: to.to_owned(),
10808        reason: reason.to_owned(),
10809    });
10810}
10811
10812/// Did this reply report running a command whose own CLI never confirmed an
10813/// exit status?
10814///
10815/// An [`agent::CommandEvidence`] only ever exists when the CLI reported the
10816/// command *finished* (see that type's own doc), so this can only be `true`
10817/// for a command whose completion event carried no readable exit code — not
10818/// for one that simply is not mentioned at all. That is the one signal this
10819/// crate can read, from the same record `state.jobs` renders, about a reply
10820/// standing next to work its own CLI cannot vouch for finishing; it is
10821/// deliberately not a check on the exit code's *value* (a fixer legitimately
10822/// runs a command that fails mid-iteration before it succeeds) and not a
10823/// guess at a command still running in the background (which emits no event
10824/// at all, and so leaves no evidence here to find).
10825fn has_unconfirmed_command(commands: &[agent::CommandEvidence]) -> bool {
10826    commands.iter().any(|c| c.exit_code.is_none())
10827}
10828
10829/// Whether a `NO CHANGE NEEDED` marker in an implementer's reply should be
10830/// trusted as a verified no-op — the adoption guard's own text-level half.
10831///
10832/// `usable` is the caller's `AgentOutput::usable()` (a clean CLI exit, not
10833/// timed out): a marker only earns the benefit of the doubt from a turn the
10834/// CLI itself vouches for finishing properly, the same house style
10835/// `resume_unconfirmed_commands` and `continue_fix_report` already hold a
10836/// *fix* report to for `commands`. A candidate that timed out, exited
10837/// non-zero, or left a command unconfirmed is read as the ordinary loss it
10838/// is, whatever prose it wrote — this returns `None` before it ever looks at
10839/// `text`. The remaining guards (the tree really is empty, the evidence is
10840/// non-empty) are the caller's: this only reads what the reply *claimed*.
10841fn verified_noop_claim(
10842    usable: bool,
10843    commands: &[agent::CommandEvidence],
10844    text: &str,
10845) -> Option<String> {
10846    (usable && !has_unconfirmed_command(commands))
10847        .then(|| verdict::verified_noop(text))
10848        .flatten()
10849}
10850
10851fn short(commit: &str) -> String {
10852    commit.chars().take(7).collect()
10853}
10854
10855fn make_executable(path: &Path) -> Result<()> {
10856    #[cfg(unix)]
10857    {
10858        use std::os::unix::fs::PermissionsExt as _;
10859        let mut perms = std::fs::metadata(path)?.permissions();
10860        perms.set_mode(0o755);
10861        std::fs::set_permissions(path, perms)?;
10862    }
10863    #[cfg(not(unix))]
10864    {
10865        let _ = path;
10866    }
10867    Ok(())
10868}
10869
10870/// What every seat in one batch shares: where the answers are attributed, the
10871/// prompt overlay they inherit, and the build cache they are told to use.
10872///
10873/// A struct rather than four more parameters: `wave` also needs the run's
10874/// state (to record who is answering right now) and the attempt number, and
10875/// eight positional arguments is both unreadable and a clippy error.
10876struct WaveCtx<'a> {
10877    /// Exported as `MAGI_RUN`, so a task an agent files names the run that
10878    /// paid for it.
10879    run: &'a str,
10880    /// Exported as `MAGI_NODE`, and the key the prompt overlay is chosen by.
10881    node: &'a str,
10882    prompts: &'a Prompts,
10883    /// The shared `CARGO_TARGET_DIR`, when the config declares one.
10884    cache: Option<&'a Path>,
10885    /// The review round this wave belongs to, for `"review"`/`"fix"` — see
10886    /// `JobRecord::round`. `None` for every other node.
10887    round: Option<usize>,
10888    /// Carry each seat's failed-agent history across waves (the review loop
10889    /// only): start-of-round priority and handover choice read
10890    /// [`RunState::seat_history`], and every answer or failure writes it.
10891    carry_seats: bool,
10892    /// The run's park / interrupt requests, so a wait for a shared resource
10893    /// can be abandoned the moment the operator asks to park.
10894    pauses: Option<(&'a Pause, &'a Pause)>,
10895}
10896
10897/// Shared scheduling policy for operations and spawned seat invocations.
10898fn repository_wait(
10899    state: &RunState,
10900    pauses: Option<(&Pause, &Pause)>,
10901) -> crate::repo_lock::WaitPolicy {
10902    let pauses = pauses.map(|(a, b)| (a.clone(), b.clone()));
10903    let inherited = crate::repo_lock::WaitPolicy::current();
10904    crate::repo_lock::WaitPolicy::new(
10905        Duration::from_secs(state.config.graph.timeout_resource_wait),
10906        move || {
10907            inherited.cancelled()
10908                || pauses
10909                    .as_ref()
10910                    .is_some_and(|(a, b)| a.parked() || b.parked())
10911        },
10912    )
10913}
10914
10915fn record_repository_block(state: &mut RunState, error: &anyhow::Error) {
10916    if let Some(timeout) = error.downcast_ref::<agent::IsolatedSeatWait>() {
10917        state.event("resource", timeout.0.description());
10918        state.resource_block = Some(timeout.0.clone());
10919        return;
10920    }
10921    if error.is::<crate::repo_lock::ResourceBlocked>() {
10922        state.resource_block = Some(crate::run::ResourceBlock {
10923            cause: crate::run::ResourceBlockCause::Other,
10924            node: "repository".into(),
10925            kind: if error.is::<crate::build_target::AdmissionDiskWait>() {
10926                "disk admission"
10927            } else if error.to_string().contains("disk pressure") {
10928                "disk pressure"
10929            } else if error.to_string().contains("disk admission") {
10930                "disk admission"
10931            } else if error.to_string().contains(crate::incremental::BLOCKED) {
10932                "incremental cache admission"
10933            } else {
10934                "repository coordination"
10935            }
10936            .into(),
10937            detail: format!("{error:#}"),
10938            at: Timestamp::now(),
10939        });
10940        state.event("resource", error.to_string());
10941    }
10942}
10943
10944async fn coordinate_operation(
10945    state: &mut RunState,
10946    cwd: &Path,
10947    wait: &crate::repo_lock::WaitPolicy,
10948) -> Result<Option<crate::repo_lock::SeatLease>> {
10949    let result =
10950        crate::repo_lock::SeatLease::operation_with(cwd, state.config.coordination.as_ref(), wait)
10951            .await;
10952    if let Err(e) = &result {
10953        record_repository_block(state, e);
10954    }
10955    result
10956}
10957
10958/// Run one job, honouring the parallelism budget.
10959async fn run_one(
10960    job: SeatJob,
10961    sem: Arc<Semaphore>,
10962    ctx: &WaveCtx<'_>,
10963    state: &mut RunState,
10964    attempt: usize,
10965) -> (SeatState, AgentOutcome) {
10966    let (_, seat, out) = wave(vec![job], sem, ctx, state, attempt)
10967        .await
10968        .pop()
10969        .expect("one job in, one result out");
10970    (seat, out)
10971}
10972
10973/// Run every job concurrently, capped by the semaphore, preserving order.
10974///
10975/// Every seat in the batch is recorded into [`RunState::active`] before the
10976/// wave starts and cleared as each answer lands, so the run's own record says
10977/// who is still being waited on rather than only who finished.
10978async fn wave(
10979    jobs: Vec<SeatJob>,
10980    sem: Arc<Semaphore>,
10981    ctx: &WaveCtx<'_>,
10982    state: &mut RunState,
10983    attempt: usize,
10984) -> Vec<(usize, SeatState, AgentOutcome)> {
10985    let WaveCtx {
10986        run,
10987        node,
10988        prompts,
10989        cache,
10990        round,
10991        carry_seats: _,
10992        pauses,
10993    } = *ctx;
10994    let cache = cache.filter(|_| !crate::build_target::isolated(&state.config));
10995    for job in &jobs {
10996        state.seat_started(node, &job.seat.key, job.timeout, attempt);
10997    }
10998    if let Err(e) = state.save() {
10999        // A failed persist of "who is answering right now" must not abort the
11000        // wave: the seats are already being asked, and the alternative is
11001        // losing the answers to save a status line nobody may even be
11002        // watching.
11003        tracing::warn!("could not persist in-progress seats: {e:#}");
11004    }
11005    // Shared-mode waves keep their existing single lease. Isolated writers
11006    // acquire their own checkout's target at seat admission.
11007    let jobs_had_a_writer = jobs.iter().any(|j| j.allow_write);
11008    // The wait for the lease has its own bound, `timeout_resource_wait`; it is
11009    // never borrowed from a job's agent budget (and never charged to it either,
11010    // see below). The agent's clock starts in `agent::invoke`, at spawn.
11011    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
11012    let cache_guard = if let Some(cache_dir) = cache {
11013        if jobs_had_a_writer {
11014            let owner = crate::cache::Owner::here(run, node, "*", Path::new("(wave)"), "");
11015            let cancel = move || pauses.is_some_and(|(a, b)| a.parked() || b.parked());
11016            match acquire_cache_lease(
11017                state,
11018                cache_dir,
11019                &owner,
11020                resource_limit,
11021                node,
11022                node,
11023                &cancel,
11024            )
11025            .await
11026            {
11027                Ok(Some(g)) => Some(g),
11028                // Parking: leave without spawning anything. The run parks at
11029                // the next boundary and the seats are asked afresh on resume.
11030                Ok(None) => {
11031                    if let Some(block) = &mut state.resource_block {
11032                        block.cause = crate::run::ResourceBlockCause::Cancelled {
11033                            park: pauses.and_then(|(a, b)| b.cause().or_else(|| a.cause())),
11034                        };
11035                    }
11036                    return block_wave(
11037                        jobs,
11038                        state,
11039                        node,
11040                        attempt,
11041                        "parked while waiting for the shared build cache",
11042                    );
11043                }
11044                // An unreadable lease is not contention: keep the old
11045                // fallback (no shared cache for this wave's seats).
11046                Err(e) if e.downcast_ref::<CacheCheckError>().is_some() => None,
11047                Err(e) => {
11048                    // Writing seats may not build into a cache this run does
11049                    // not hold, and an agent that cannot be given one is not
11050                    // asked at all: the run stops resumably instead.
11051                    let why = format!("{e:#}");
11052                    state.event(
11053                        "resource",
11054                        format!("{node}: no agent was started - {why}; resume to ask the same agents again"),
11055                    );
11056                    return block_wave(jobs, state, node, attempt, &why);
11057                }
11058            }
11059        } else {
11060            None
11061        }
11062    } else {
11063        None
11064    };
11065    // Every job keeps its whole budget: the wait above was not the agent's.
11066    // Restart the seats' clocks so "started" means "being spawned now".
11067    state.seats_spawning(node, attempt);
11068    if let Err(e) = state.save() {
11069        tracing::warn!("could not persist the start of a wave: {e:#}");
11070    }
11071    // Queueing behind this wave's own seats for a parallelism slot is normal
11072    // (each of them is bounded by its own agent timeout); only a wait beyond
11073    // all of them plus the resource limit means the slots never came back.
11074    let slot_limit = resource_limit
11075        + jobs
11076            .iter()
11077            .map(|j| j.timeout)
11078            .max()
11079            .unwrap_or_default()
11080            .saturating_mul(jobs.len() as u32);
11081    let mut set = tokio::task::JoinSet::new();
11082    // Seats announce themselves here the moment they hold a parallelism
11083    // permit, i.e. just before their CLI is spawned.
11084    let (spawned_tx, mut spawned_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
11085    let overlay = prompts.overlay(node);
11086    let repository_wait = repository_wait(state, pauses);
11087    for (i, mut job) in jobs.into_iter().enumerate() {
11088        job.prompt = prompt::with_overlay(job.prompt, overlay.clone());
11089        if cache.is_some() {
11090            job.prompt.push('\n');
11091            job.prompt
11092                .push_str(&prompt::build_cache_note(node, job.allow_write));
11093        }
11094        let sem = Arc::clone(&sem);
11095        let run = run.to_owned();
11096        let node = node.to_owned();
11097        // Only implementers were told about the task's attachments, so only
11098        // their seats get the directory widened for reading.
11099        let attachments = if node == "implement" {
11100            state.attachments.clone()
11101        } else {
11102            Vec::new()
11103        };
11104        // A read-only seat is never handed `CARGO_TARGET_DIR` — see
11105        // `prompt::build_cache_note`'s doc for why setting it anyway is
11106        // exactly how a sandboxed reviewer's write refusal got reported as a
11107        // defect in the patch, not a property of its own seat. And a
11108        // write-allowed one is handed it only when the lease above was
11109        // actually acquired: a wave that could not get it (`cache_guard` is
11110        // `None`, see its own comment) must not send seats to build into a
11111        // directory this run does not hold - that is the exact concurrent,
11112        // unmanaged-write race this module exists to prevent, not something
11113        // "proceeding anyway" is allowed to reintroduce.
11114        let cache = cache
11115            .filter(|_| job.allow_write && cache_guard.is_some())
11116            .map(Path::to_path_buf);
11117        let spawned_tx = spawned_tx.clone();
11118        let repository_wait = repository_wait.clone();
11119        let coordination = state.config.coordination.clone();
11120        let fetched_base = state.fetched_base.clone();
11121        set.spawn(async move {
11122            // A wait for a parallelism slot is scheduling, not the agent: it
11123            // is bounded by its own limit and ends as a resource block, never
11124            // as a timeout of the agent that was not started.
11125            let _permit = match tokio::time::timeout(slot_limit, sem.acquire()).await {
11126                Ok(p) => p,
11127                Err(_) => {
11128                    return (
11129                        i,
11130                        job.seat,
11131                        AgentOutcome::ResourceBlocked(format!(
11132                            "no parallel slot became free within {}s",
11133                            slot_limit.as_secs()
11134                        )),
11135                        None,
11136                        false,
11137                    );
11138                }
11139            };
11140            spawned_tx.send(job.seat.key.clone()).ok();
11141            let mut seat = job.seat;
11142            let out = repository_wait
11143                .scope(agent::invoke(
11144                    &job.spec,
11145                    &mut seat,
11146                    &Invocation {
11147                        coordination: coordination.as_ref(),
11148                        fetched_base: fetched_base.as_ref(),
11149                        cwd: &job.cwd,
11150                        prompt: &job.prompt,
11151                        timeout: job.timeout,
11152                        allow_write: job.allow_write,
11153                        sessions: job.sessions,
11154                        artifacts: &job.artifacts,
11155                        stem: &job.stem,
11156                        run: &run,
11157                        node: &node,
11158                        cache_dir: cache.as_deref(),
11159                        attachments: &attachments,
11160                        writable: &[],
11161                    },
11162                ))
11163                .await;
11164            let cache_block = out
11165                .as_ref()
11166                .err()
11167                .and_then(|error| error.downcast_ref::<agent::IsolatedSeatWait>())
11168                .map(|timeout| timeout.0.clone());
11169            let interrupted = out
11170                .as_ref()
11171                .err()
11172                .is_some_and(|error| error.is::<agent::ExecutionInterrupted>());
11173            let out = match out {
11174                Ok(o) if o.quota_exhausted() => AgentOutcome::Quota(o),
11175                Ok(o) if o.usable() => AgentOutcome::Ok(o),
11176                // Billed work the CLI failed to hand over is not an ordinary
11177                // failure, but its text is the CLI's raw error JSON, not an
11178                // answer — `Dropped` keeps it out of `Ok` so a caller cannot
11179                // read it as one by forgetting to check. `usable()` is always
11180                // false here (dropped implies an empty response), so this has
11181                // to be checked before the catch-all `Failed` below or the
11182                // one shape this exists for is lost with the rest.
11183                Ok(o) if o.work_undelivered() => AgentOutcome::Dropped(o),
11184                Ok(o) if o.timed_out => AgentOutcome::Failed(TIMED_OUT.to_owned()),
11185                Ok(o) => AgentOutcome::Failed(format!(
11186                    "process exited with no usable output ({})",
11187                    crate::notices::exit_status(o.exit_code)
11188                )),
11189                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
11190                    AgentOutcome::ResourceBlocked(e.to_string())
11191                }
11192                Err(e) => AgentOutcome::Failed(e.to_string()),
11193            };
11194            (i, seat, out, cache_block, interrupted)
11195        });
11196    }
11197    drop(spawned_tx);
11198    let mut collected: Vec<Option<(usize, SeatState, AgentOutcome)>> = Vec::new();
11199    loop {
11200        let joined = tokio::select! {
11201            Some(key) = spawned_rx.recv() => {
11202                // The clock of this seat starts now, not when it queued.
11203                state.seat_spawned(&key);
11204                if let Err(e) = state.save() {
11205                    tracing::warn!("could not persist a seat's start: {e:#}");
11206                }
11207                continue;
11208            }
11209            joined = set.join_next() => joined,
11210        };
11211        let Some(joined) = joined else {
11212            break;
11213        };
11214        let (i, seat, out, cache_block, interrupted) = match joined {
11215            Ok(v) => v,
11216            // No seat to clear: a panicked task never reported which one it
11217            // was. The defensive sweep below this loop is what stops that
11218            // seat's `active` entry from surviving forever.
11219            Err(e) => {
11220                tracing::error!("agent task panicked: {e}");
11221                continue;
11222            }
11223        };
11224        state.seat_finished(&seat.key);
11225        if interrupted
11226            && node == "implement"
11227            && let Some(label) = state
11228                .candidates
11229                .iter()
11230                .find(|candidate| seat.key == format!("impl-{}", candidate.label))
11231                .map(|candidate| candidate.label)
11232        {
11233            state.candidate_preservation.insert(
11234                label,
11235                "interrupted implementation awaiting persistence".into(),
11236            );
11237            state.interrupted_implementations.insert(label);
11238        }
11239        if let Some(block) = cache_block
11240            && state.resource_block.is_none()
11241        {
11242            state.event("resource", block.description());
11243            state.resource_block = Some(block);
11244        }
11245        if let AgentOutcome::ResourceBlocked(why) = &out
11246            && state.resource_block.is_none()
11247        {
11248            state.resource_block = Some(crate::run::ResourceBlock {
11249                cause: crate::run::ResourceBlockCause::Other,
11250                node: node.to_owned(),
11251                kind: if why.contains("disk pressure") {
11252                    "disk pressure"
11253                } else if why.contains("disk admission") {
11254                    "disk admission"
11255                } else if why.contains(crate::incremental::BLOCKED) {
11256                    "incremental cache admission"
11257                } else if why.contains(crate::build_target::KIND) {
11258                    crate::build_target::KIND
11259                } else if why.contains("repository coordination") {
11260                    "repository coordination"
11261                } else {
11262                    "parallel slot"
11263                }
11264                .to_owned(),
11265                detail: why.clone(),
11266                at: Timestamp::now(),
11267            });
11268            let activity = if interrupted {
11269                "agent execution interrupted"
11270            } else {
11271                "no agent was started"
11272            };
11273            state.event("resource", format!("{node}: {activity} - {why}"));
11274        }
11275        record_jobs(state, node, round, &seat.key, &out);
11276        if let Err(e) = state.save() {
11277            tracing::warn!("could not persist a seat's completion: {e:#}");
11278        }
11279        if collected.len() <= i {
11280            collected.resize_with(i + 1, || None);
11281        }
11282        collected[i] = Some((i, seat, out));
11283    }
11284    // Belt-and-braces for the panic branch above: every seat this exact batch
11285    // started shares this `(node, attempt)` pair, and every seat that finished
11286    // normally already cleared itself, so anything left tagged with it here
11287    // can only be a panicked task's leftover. Cleared unconditionally rather
11288    // than left to read as still answering forever.
11289    if state
11290        .active
11291        .values()
11292        .any(|a| a.node == node && a.attempt == attempt)
11293    {
11294        state
11295            .active
11296            .retain(|_, a| !(a.node == node && a.attempt == attempt));
11297        if let Err(e) = state.save() {
11298            tracing::warn!("could not persist the end of a wave: {e:#}");
11299        }
11300    }
11301    // Whether or not the lease above was actually held, several worktrees
11302    // may just have built into the cache with nothing here able to name one
11303    // coherent (worktree, head) for it - see `cache::invalidate_identity`'s
11304    // own doc. Forgetting the old record costs the next `e2e`/`gate` one
11305    // clean it might not have strictly needed; trusting a stale match would
11306    // cost it a wrong answer.
11307    if let Some(cache_dir) = cache
11308        && jobs_had_a_writer
11309    {
11310        crate::cache::invalidate_identity(&crate::run::home(), cache_dir);
11311    }
11312    if let Some(guard) = cache_guard {
11313        guard.release();
11314    }
11315    collected.into_iter().flatten().collect()
11316}
11317
11318/// Fold one seat's [`agent::CommandEvidence`] (if its outcome carries any)
11319/// into the run's [`JobRecord`] log — every node, every seat, uniformly:
11320/// this is data collection, not the fix-specific completion contract in
11321/// [`Runner::continue_fix_report`], and applies regardless of which node
11322/// asked.
11323///
11324/// Only `AgentOutcome::Ok`/`Quota`/`Dropped` carry an [`AgentOutput`] to read
11325/// evidence from; `Failed` does not, and correctly contributes nothing — a
11326/// timeout or crash is not itself evidence about a command the seat may have
11327/// started.
11328fn record_jobs(
11329    state: &mut RunState,
11330    node: &str,
11331    round: Option<usize>,
11332    seat: &str,
11333    out: &AgentOutcome,
11334) {
11335    let commands: &[agent::CommandEvidence] = match out {
11336        AgentOutcome::Ok(o) | AgentOutcome::Quota(o) | AgentOutcome::Dropped(o) => &o.commands,
11337        AgentOutcome::Failed(_) | AgentOutcome::ResourceBlocked(_) => &[],
11338    };
11339    let checked_at = Timestamp::now();
11340    for c in commands {
11341        state.jobs.push(JobRecord {
11342            node: node.to_owned(),
11343            round,
11344            seat: seat.to_owned(),
11345            id: c.id.clone(),
11346            description: c.description.clone(),
11347            checked_at,
11348            status: match c.exit_code {
11349                Some(0) => JobStatus::Completed,
11350                Some(_) => JobStatus::Failed,
11351                None => JobStatus::Unknown,
11352            },
11353            exit_code: c.exit_code,
11354            result_summary: c.result_summary.clone(),
11355            source: c.source.clone(),
11356        });
11357    }
11358}
11359
11360/// Is a review round clean, given how many reviewer seats answered against
11361/// how many the round expected?
11362///
11363/// A seat that never answered (timeout, crash, unparsable output) is not a
11364/// seat that read the patch and found nothing — treating it as such is
11365/// exactly the bug this function exists to close. Under the default `block`
11366/// policy a missing seat can never be clean; `warn` still requires the seats
11367/// that *did* answer to have found nothing blocking and verification to be
11368/// green.
11369///
11370/// `quota_missing` narrows that `block` default for exactly one cause of
11371/// absence: a seat lost to its own rate limit this round. Re-reviewing hoping
11372/// a session limit lifts by the very next round buys nothing — the seat is
11373/// asked again with the same quota — so once every missing seat is accounted
11374/// for by a quota loss (and at least one seat *did* answer, so a decision has
11375/// something to rest on) the round is decided on the panel that could answer,
11376/// same as `warn` would. A panel that lost every seat to quota is not
11377/// decided here: `answered == 0` falls through to the existing `block`
11378/// fallback so a fully collapsed panel still waits rather than landing on no
11379/// review at all.
11380fn round_is_clean(
11381    blocking: usize,
11382    e2e_ok: bool,
11383    answered: usize,
11384    expected: usize,
11385    quota_missing: usize,
11386    policy: IncompleteReviewPolicy,
11387) -> bool {
11388    if blocking != 0 || !e2e_ok {
11389        return false;
11390    }
11391    if answered == expected || policy == IncompleteReviewPolicy::Warn {
11392        return true;
11393    }
11394    answered > 0 && expected - answered <= quota_missing
11395}
11396
11397/// The review loop's own conclusion, derived entirely from its persisted
11398/// round records and the round budget that produced them — never from
11399/// `status`, so a reentry (or `gate`/`merge` reading it independently)
11400/// recomputes the identical answer regardless of what an earlier node in the
11401/// same walk, or a previous walk, did to `status`.
11402///
11403/// `None` while more rounds remain to try, including when review never ran
11404/// at all (`review_rounds = 0`, or nothing yet recorded). Once a round has
11405/// gone clean, or the budget is spent, or the tree has stopped moving (see
11406/// [`STAGNANT_LIMIT`]), the answer is one of two things:
11407///
11408/// - An incomplete panel that raised nothing is missing input, not a
11409///   verified tree — never a hand-off candidate, whatever verification said
11410///   (see [`ReviewRound::incomplete`], `IncompleteReviewPolicy`).
11411/// - Otherwise, green e2e on the last round hands off (see
11412///   [`Runner::stop_reviewing`]); red e2e blocks.
11413///
11414/// A last round whose own verification is still `ResourceBlocked` — magi
11415/// itself never got a command to run, not evidence the patch is broken —
11416/// is neither: this returns `None` for it too, the same as "more rounds
11417/// remain", so a reentry retries the check (see `Runner::review_loop`'s own
11418/// handling of that shape) instead of this cheap recomputation guessing a
11419/// verdict a real attempt never produced.
11420pub(crate) fn review_conclusion(reviews: &[ReviewRound], max_rounds: usize) -> Option<RunStatus> {
11421    if max_rounds == 0
11422        || reviews.last().is_some_and(|r| {
11423            r.clean && matches!(r.e2e_status(), E2eStatus::Passed | E2eStatus::NotConfigured)
11424        })
11425    {
11426        return Some(RunStatus::Gating);
11427    }
11428    let last = reviews.last()?;
11429    let stagnant = reviews.iter().rev().take_while(|r| !r.progressed).count() >= STAGNANT_LIMIT;
11430    if reviews.len() < max_rounds && !stagnant {
11431        return None;
11432    }
11433    if last.incomplete() && last.blocking == 0 {
11434        return Some(RunStatus::Blocked);
11435    }
11436    if last.e2e_status() == E2eStatus::ResourceBlocked
11437        || (last.e2e_status() == E2eStatus::Deferred && last.blocking == 0 && last.fix.is_none())
11438    {
11439        return None;
11440    }
11441    Some(if last.e2e.iter().all(CommandOutcome::ok) {
11442        RunStatus::Gating
11443    } else {
11444        RunStatus::Blocked
11445    })
11446}
11447
11448/// How long a re-ask may take, given the budget the first attempt had.
11449///
11450/// A `nudged` retry is a request to restate an answer the seat has already
11451/// worked out: it carries no new work, so it does not deserve the original
11452/// budget. Measured on run 01c2, two judges restated their ranking in 41 and
11453/// 133 seconds while a third sat for over ten minutes on a resumed session
11454/// holding 410 KB of prior output - and because the retry had inherited the
11455/// full 1200s judge timeout, one stuck nudge nearly doubled the wall time of a
11456/// judging round whose other seats were long finished.
11457///
11458/// A quarter of the budget, with a floor so that a deliberately short timeout
11459/// does not collapse to nothing. A retry that re-sends the whole prompt
11460/// (because the seat kept no context) is the original job again, and keeps the
11461/// original budget.
11462pub(crate) fn retry_budget(full: Duration, nudged: bool) -> Duration {
11463    if nudged {
11464        (full / 4).max(Duration::from_secs(120)).min(full)
11465    } else {
11466        full
11467    }
11468}
11469
11470/// Run a wave and parse each reply, re-asking the seats whose reply was
11471/// unusable.
11472///
11473/// The re-ask is a nudge rather than the whole prompt again when the seat still
11474/// holds its conversation, which is the difference between a cheap retry and
11475/// paying for the entire candidate set twice.
11476///
11477/// A seat whose agent *fails* (rate limit, timeout, any other error) and has a
11478/// successor in `roster` is handed to it instead of being re-asked: the
11479/// handover is the retry. A seat with no successor left (a single-agent
11480/// roster, the roster's tail) is nudged as before, up to `retries` times. So
11481/// the asks to one seat in one node number at most
11482/// `roster.len().max(1) * (1 + retries)`; an agent that still has a successor
11483/// is asked once (a dropped stream is nudged first), and only the last agent
11484/// of the chain gets the `retries` same-agent nudges. Each roster agent is
11485/// tried at most once per seat, walking forward from the seat's own position and never wrapping
11486/// ([`next_untried_in_roster`]); a quota or timeout always hands over, any
11487/// other failure stops the chain when the previous agent failed the same way
11488/// ([`should_hand_over`]). The new agent takes a fresh [`SeatState`], so
11489/// [`has_context`] is false and the job's own full prompt and full budget are
11490/// sent. A seat whose chain ends on a quota records one [`QuotaLoss`] (the
11491/// intermediate ones are not losses) and is returned as a failure like any
11492/// other absent seat — the caller decides whether the panel still has a
11493/// quorum. An empty `roster` disables handover: failures are nudged as they
11494/// always were, and a quota is simply lost. A reply that fails to parse or
11495/// validate is the prompt's doing and is only ever nudged, never handed over.
11496///
11497/// The returned [`SeatState`] names the agent that answered (or tried last).
11498#[allow(clippy::too_many_arguments)]
11499async fn ask_json_wave<T>(
11500    jobs: Vec<SeatJob>,
11501    sem: Arc<Semaphore>,
11502    retries: usize,
11503    roster: &[AgentSpec],
11504    ctx: &WaveCtx<'_>,
11505    losses: &mut Vec<QuotaLoss>,
11506    state: &mut RunState,
11507    validate: &(dyn Fn(&T) -> Result<()> + Send + Sync),
11508) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
11509where
11510    T: serde::de::DeserializeOwned + Send + 'static,
11511{
11512    ask_wave_with(
11513        jobs,
11514        sem,
11515        retries,
11516        roster,
11517        ctx,
11518        losses,
11519        state,
11520        &|text: &str| {
11521            let v = verdict::extract_json::<T>(text)?;
11522            validate(&v)?;
11523            Ok(v)
11524        },
11525    )
11526    .await
11527}
11528
11529/// [`ask_json_wave`] with the reading of an answer supplied by the caller, so
11530/// a node whose answer is prose (deliberation) shares the same handover,
11531/// failure classification, quota bookkeeping and bounds instead of a copy.
11532///
11533/// A seat handed to another roster agent is sent the job's `handover` prompt
11534/// (when it has one) rather than `prompt`: the new agent has no session, so a
11535/// resume-style prompt would be incomplete. That holds for the handover ask
11536/// and for every nudge to that agent whose `has_context` is false.
11537#[allow(clippy::too_many_arguments)]
11538async fn ask_wave_with<T>(
11539    jobs: Vec<SeatJob>,
11540    sem: Arc<Semaphore>,
11541    retries: usize,
11542    roster: &[AgentSpec],
11543    ctx: &WaveCtx<'_>,
11544    losses: &mut Vec<QuotaLoss>,
11545    state: &mut RunState,
11546    parse: &(dyn Fn(&str) -> Result<T> + Send + Sync),
11547) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
11548where
11549    T: Send + 'static,
11550{
11551    let n = jobs.len();
11552    let originals: Vec<SeatJob> = jobs;
11553    let mut seats: Vec<SeatState> = originals.iter().map(|j| j.seat.clone()).collect();
11554    let mut done: Vec<Option<Result<(T, AgentOutput)>>> = (0..n).map(|_| None).collect();
11555    // Nudges each seat's *current* agent has taken — 0 for a first-ask
11556    // answer, N once it has gone through N nudges. Read back once this
11557    // returns, so a caller building a history record (`ReviewRecord`) can
11558    // tell "never answered" (`failed: Some(_)`, `attempts == 0`) apart from
11559    // "recovered after a nudge" (`failed: None`, `attempts > 0`) — see that
11560    // field's own doc.
11561    let mut nudges: Vec<usize> = vec![0; n];
11562    // The agent now occupying each seat, the ids it has already been through,
11563    // where in the roster the walk began, the class of the last failure, and
11564    // the stem word of a handover not yet asked (full prompt, full budget).
11565    let mut specs: Vec<AgentSpec> = originals.iter().map(|j| j.spec.clone()).collect();
11566    let mut tried: Vec<BTreeSet<String>> = specs
11567        .iter()
11568        .map(|s| BTreeSet::from([s.id.clone()]))
11569        .collect();
11570    let starts: Vec<usize> = specs
11571        .iter()
11572        .map(|s| roster.iter().position(|r| r.id == s.id).unwrap_or(0))
11573        .collect();
11574    let carry = ctx.carry_seats && !roster.is_empty();
11575    // Carried across rounds: ids that failed the seat earlier, and how the
11576    // last failure went (so a repeat of it is not handed over again).
11577    let carried: Vec<BTreeSet<String>> = originals
11578        .iter()
11579        .map(|j| {
11580            state
11581                .seat_history
11582                .get(&j.seat.key)
11583                .filter(|_| carry)
11584                .map(|h| h.failed.clone())
11585                .unwrap_or_default()
11586        })
11587        .collect();
11588    let mut prev: Vec<Option<FailClass>> = originals
11589        .iter()
11590        .map(|j| {
11591            state
11592                .seat_history
11593                .get(&j.seat.key)
11594                .filter(|_| carry)
11595                .and_then(|h| h.last_fail.clone())
11596        })
11597        .collect();
11598    let next_agent =
11599        |i: usize, tried: &BTreeSet<String>, specs: &[AgentSpec]| -> Option<AgentSpec> {
11600            let others: BTreeSet<String> = specs
11601                .iter()
11602                .enumerate()
11603                .filter(|(j, _)| *j != i)
11604                .map(|(_, s)| s.id.clone())
11605                .collect();
11606            pick_successor(
11607                roster,
11608                starts[i],
11609                tried,
11610                carry.then(|| &carried[i]),
11611                &others,
11612            )
11613            .cloned()
11614        };
11615    let mut fresh: Vec<Option<String>> = vec![None; n];
11616    let mut last_quota: Vec<Option<agent::Quota>> = vec![None; n];
11617    let mut pending: Vec<usize> = (0..n).collect();
11618
11619    // Per seat the work is bounded by `roster.len().max(1) * (1 + retries)`
11620    // asks: an agent with a successor is asked once and handed over, and only
11621    // a seat with no successor spends `retries` nudges on the same agent. This
11622    // only guarantees the loop's own termination whatever those say.
11623    let max_rounds = (retries + 1) * roster.len().max(1) + 1;
11624    for round in 0..max_rounds {
11625        if pending.is_empty() {
11626            break;
11627        }
11628        let mut batch = Vec::with_capacity(pending.len());
11629        let mut renudged: Vec<&str> = Vec::new();
11630        for &i in &pending {
11631            let src = &originals[i];
11632            // A seat now held by another agent than the job named has no
11633            // session of its own: it gets the full-context prompt whenever
11634            // it is asked in full (the handover ask, a nudge it cannot
11635            // resume).
11636            let full: &str = match &src.handover {
11637                Some(h) if specs[i].id != src.spec.id => h,
11638                _ => &src.prompt,
11639            };
11640            // The prompt and the budget are one decision: a nudge restates
11641            // finished work, a re-sent prompt redoes it.
11642            let (prompt, timeout, stem) = if let Some(word) = fresh[i].take() {
11643                (
11644                    full.to_owned(),
11645                    src.timeout,
11646                    format!("{}-{word}-{}", src.stem, specs[i].id),
11647                )
11648            } else if nudges[i] == 0 {
11649                (full.to_owned(), src.timeout, src.stem.clone())
11650            } else {
11651                renudged.push(src.seat.key.as_str());
11652                let why = done[i]
11653                    .as_ref()
11654                    .and_then(|r| r.as_ref().err().map(ToString::to_string))
11655                    .unwrap_or_else(|| "no parsable answer".to_owned());
11656                let nudge = prompt::nudge(&why);
11657                let nudged = has_context(&specs[i], &seats[i], src.sessions);
11658                let prompt = if nudged {
11659                    nudge
11660                } else {
11661                    format!("{full}\n\n---\n\n{nudge}")
11662                };
11663                (
11664                    prompt,
11665                    retry_budget(src.timeout, nudged),
11666                    format!("{}-retry{}", src.stem, nudges[i]),
11667                )
11668            };
11669            batch.push(SeatJob {
11670                spec: specs[i].clone(),
11671                seat: seats[i].clone(),
11672                cwd: src.cwd.clone(),
11673                prompt,
11674                timeout,
11675                allow_write: src.allow_write,
11676                sessions: src.sessions,
11677                artifacts: src.artifacts.clone(),
11678                stem,
11679                handover: None,
11680            });
11681        }
11682
11683        if !renudged.is_empty() {
11684            state.event(
11685                ctx.node,
11686                format!("retry {round}: re-asking {}", renudged.join(", ")),
11687            );
11688        }
11689        let results = wave(batch, Arc::clone(&sem), ctx, state, round).await;
11690        let mut still = Vec::new();
11691        for (&i, (_wi, seat, out)) in pending.iter().zip(results) {
11692            seats[i] = seat;
11693            // No agent was asked: nothing to hand over, nudge, remember or
11694            // charge. The caller sees `resource_block` and stops the node.
11695            if let AgentOutcome::ResourceBlocked(why) = &out {
11696                done[i] = Some(Err(anyhow::anyhow!("{why}")));
11697                continue;
11698            }
11699            let class = FailClass::of(&out);
11700            // A dropped stream is nudged first (the conversation is still
11701            // there to pick up); only a seat whose nudges are spent hands over.
11702            let nudge_first = matches!(out, AgentOutcome::Dropped(_))
11703                && nudges[i] < retries
11704                && !roster.is_empty();
11705            if let Some(cur) = class.clone().filter(|_| !roster.is_empty() && !nudge_first) {
11706                let next = should_hand_over(prev[i].as_ref(), &cur)
11707                    .then(|| next_agent(i, &tried[i], &specs))
11708                    .flatten();
11709                if carry {
11710                    let h = state
11711                        .seat_history
11712                        .entry(originals[i].seat.key.clone())
11713                        .or_default();
11714                    h.failed.insert(specs[i].id.clone());
11715                    h.last_fail = Some(cur.clone());
11716                    if h.last_ok.as_deref() == Some(specs[i].id.as_str()) {
11717                        h.last_ok = None;
11718                    }
11719                    // Saved before the next agent is asked, so a restart in
11720                    // between does not forget who failed.
11721                    if let Err(e) = state.save() {
11722                        tracing::warn!("could not persist a seat's failure history: {e:#}");
11723                    }
11724                }
11725                if let Some(next) = next {
11726                    record_handover(
11727                        state,
11728                        ctx.node,
11729                        &originals[i].seat.key,
11730                        &specs[i].id,
11731                        &next.id,
11732                        &cur,
11733                        &fail_reason(&out),
11734                    );
11735                    tried[i].insert(next.id.clone());
11736                    prev[i] = Some(cur.clone());
11737                    seats[i] =
11738                        handover_seat(&originals[i].seat.key, &next.id, state.next_seat_seed());
11739                    specs[i] = next;
11740                    fresh[i] = Some(cur.stem_word().to_owned());
11741                    nudges[i] = 0;
11742                    done[i] = Some(Err(anyhow::anyhow!(
11743                        "handed over after: {}",
11744                        fail_reason(&out)
11745                    )));
11746                    still.push(i);
11747                    continue;
11748                }
11749            }
11750            if carry
11751                && !nudge_first
11752                && let Some(cur) = class.clone()
11753            {
11754                // The chain ended here (no successor, or a repeated failure).
11755                let h = state
11756                    .seat_history
11757                    .entry(originals[i].seat.key.clone())
11758                    .or_default();
11759                h.failed.insert(specs[i].id.clone());
11760                h.last_fail = Some(cur);
11761            }
11762            let parsed = match out {
11763                AgentOutcome::Ok(o) => parse(&o.text).map(|v| (v, o)),
11764                AgentOutcome::Quota(o) => {
11765                    last_quota[i] = o.quota.clone();
11766                    Err(anyhow::anyhow!("rate limited (quota); not retrying now"))
11767                }
11768                // Not a parseable answer: the nudge loop re-asks it, which is
11769                // exactly what a dropped stream needs. Just don't hand its raw
11770                // error JSON to `extract_json`.
11771                AgentOutcome::Dropped(o) => {
11772                    let why = o
11773                        .dropped
11774                        .as_ref()
11775                        .map(|d| d.why.as_str())
11776                        .unwrap_or("the CLI ended the stream without delivering its answer");
11777                    Err(anyhow::anyhow!("the CLI dropped the stream ({why})"))
11778                }
11779                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
11780                    Err(anyhow::anyhow!(e))
11781                }
11782            };
11783            let quota = class == Some(FailClass::Quota);
11784            let failed = parsed.is_err();
11785            if !failed && matches!(ctx.node, "judge" | "vote") {
11786                // A validated answer restores this seat's quorum presence,
11787                // including on the normal path after an all-seat block.
11788                state
11789                    .quota
11790                    .retain(|loss| loss.seat != originals[i].seat.key);
11791            }
11792            done[i] = Some(parsed);
11793            if carry && !failed {
11794                let h = state
11795                    .seat_history
11796                    .entry(originals[i].seat.key.clone())
11797                    .or_default();
11798                h.failed.remove(&specs[i].id);
11799                h.last_ok = Some(specs[i].id.clone());
11800                h.last_fail = None;
11801            }
11802            // Do not re-ask a rate-limited seat (quota) — a retry is known to
11803            // fail the same way; and never re-ask a seat that already parsed.
11804            // A failed agent that still has a successor is not re-asked
11805            // either: the handover was its remedy and has just been refused
11806            // (the chain stops on a repeated failure class). A seat with no
11807            // successor left (a single-agent roster, the roster's tail, or an
11808            // empty roster) keeps the same-agent nudge, bounded by `retries`.
11809            let agent_failure = class.is_some()
11810                && !nudge_first
11811                && !roster.is_empty()
11812                && next_agent(i, &tried[i], &specs).is_some();
11813            if failed && !quota && !agent_failure && nudges[i] < retries {
11814                nudges[i] += 1;
11815                still.push(i);
11816            }
11817        }
11818        pending = still;
11819    }
11820
11821    // One loss per seat whose chain ended on a quota: the intermediate ones
11822    // were absorbed by a handover and are not losses.
11823    for (i, q) in last_quota.into_iter().enumerate() {
11824        if let Some(quota) = q {
11825            losses.push(QuotaLoss::from_report(
11826                originals[i].seat.key.clone(),
11827                ctx.node,
11828                Some(&quota),
11829            ));
11830        }
11831    }
11832
11833    // A stalled quorum already has its own recovery checkpoint. Refresh
11834    // its missing seats before deciding whether it can resume.
11835    if state.status != RunStatus::Stalled
11836        && ctx.node != "deliberate"
11837        && n > 0
11838        && losses.len() == n
11839        && done.iter().all(|r| r.as_ref().is_some_and(Result::is_err))
11840    {
11841        block_machine_outage(state, ctx.node, losses);
11842        state.quota.append(losses);
11843    }
11844
11845    seats
11846        .into_iter()
11847        .zip(done)
11848        .zip(nudges)
11849        .map(|((seat, res), attempts)| {
11850            (
11851                seat,
11852                res.unwrap_or_else(|| Err(anyhow::anyhow!("no attempt was made"))),
11853                attempts,
11854            )
11855        })
11856        .collect()
11857}
11858
11859/// A node with no available agent has no task verdict. Preserve the node
11860/// checkpoint and record why a subsequent explicit resume is needed.
11861pub(crate) fn block_machine_outage(state: &mut RunState, node: &str, losses: &[QuotaLoss]) {
11862    let mut auth: Vec<_> = losses
11863        .iter()
11864        .filter(|loss| loss.cause == agent::QuotaCause::Authentication)
11865        .map(|loss| loss.agent.clone())
11866        .collect();
11867    auth.sort();
11868    auth.dedup();
11869    let (kind, detail) = if auth.is_empty() {
11870        (
11871            "agent usage limit",
11872            "All seats reached their agent usage limits; resume after usage is available"
11873                .to_owned(),
11874        )
11875    } else {
11876        (
11877            "agent authentication",
11878            format!(
11879                "Agents {} cannot authenticate; re-authenticate these agents, then resume the held task",
11880                auth.join(", ")
11881            ),
11882        )
11883    };
11884    state.resource_block = Some(crate::run::ResourceBlock {
11885        node: node.to_owned(),
11886        kind: kind.to_owned(),
11887        cause: crate::run::ResourceBlockCause::Other,
11888        detail: detail.clone(),
11889        at: Timestamp::now(),
11890    });
11891    state.event(node, detail);
11892}
11893
11894/// Did the wave end without asking any agent (see [`block_wave`])?
11895fn wave_blocked(results: &[(usize, SeatState, AgentOutcome)]) -> bool {
11896    results
11897        .iter()
11898        .any(|(_, _, o)| matches!(o, AgentOutcome::ResourceBlocked(_)))
11899}
11900
11901/// Settle a wave that never spawned anything: every job answers
11902/// [`AgentOutcome::ResourceBlocked`], its seat leaves `active`, and nothing
11903/// else about the seat (session, history, quota) is touched.
11904fn block_wave(
11905    jobs: Vec<SeatJob>,
11906    state: &mut RunState,
11907    node: &str,
11908    attempt: usize,
11909    why: &str,
11910) -> Vec<(usize, SeatState, AgentOutcome)> {
11911    state.resource_wait = None;
11912    state
11913        .active
11914        .retain(|_, a| !(a.node == node && a.attempt == attempt));
11915    if let Err(e) = state.save() {
11916        tracing::warn!("could not persist a resource-blocked wave: {e:#}");
11917    }
11918    jobs.into_iter()
11919        .enumerate()
11920        .map(|(i, j)| (i, j.seat, AgentOutcome::ResourceBlocked(why.to_owned())))
11921        .collect()
11922}
11923
11924/// Acquire the shared build cache's lease, waiting out contention within
11925/// `budget` (never past it — see AGENTS.md's build-cache section on why an
11926/// unbounded wait is never acceptable).
11927///
11928/// A first, non-blocking check happens before ever waiting; if it finds the
11929/// lease busy, that fact is logged as a `verify` event *and* flushed with
11930/// [`RunState::save`] immediately — not only once the wait finally succeeds
11931/// or gives up — so a `magi show` run by a different process while this one
11932/// is still waiting reads a `run.json` that says so, rather than whatever it
11933/// looked like before the wait started. The same applies to the terminal
11934/// failure: logged and saved before this returns `Err`, so a caller that
11935/// could not get the lease at all still leaves a legible record of why.
11936async fn acquire_cache_lease(
11937    state: &mut RunState,
11938    cache_dir: &Path,
11939    owner: &crate::cache::Owner,
11940    budget: Duration,
11941    node: &str,
11942    context: &str,
11943    cancel: &(dyn Fn() -> bool + Sync),
11944) -> Result<Option<crate::cache::Guard>> {
11945    let home = crate::run::home();
11946    let kind = if crate::build_target::isolated(&state.config) {
11947        crate::build_target::KIND
11948    } else {
11949        "shared build cache"
11950    };
11951    let started = Instant::now();
11952    let busy = match crate::cache::try_acquire(&home, cache_dir, owner) {
11953        Ok(crate::cache::AcquireOutcome::Acquired(g)) => return Ok(Some(g)),
11954        Ok(crate::cache::AcquireOutcome::Busy(busy)) => busy,
11955        Err(e) => {
11956            state.event(
11957                "verify",
11958                format!(
11959                    "{context}: could not check the {kind} at {}: {e:#}",
11960                    cache_dir.display()
11961                ),
11962            );
11963            if let Err(e2) = state.save() {
11964                tracing::warn!("could not persist a cache-check failure: {e2:#}");
11965            }
11966            return Err(anyhow::Error::new(CacheCheckError(format!("{e:#}"))));
11967        }
11968    };
11969    state.event(
11970        "verify",
11971        format!(
11972            "{context}: waiting for the {kind} at {} ({})",
11973            cache_dir.display(),
11974            busy.describe()
11975        ),
11976    );
11977    // Seats of this node are waiting, not running: say so, so the countdown a
11978    // reader sees only ever measures an agent that has been spawned.
11979    state.resource_wait = Some(crate::run::ResourceWait {
11980        node: context.to_owned(),
11981        kind: kind.to_owned(),
11982        holder: format!("{}: {}", cache_dir.display(), busy.describe()),
11983        since: Timestamp::now(),
11984        limit_secs: budget.as_secs(),
11985    });
11986    if let Err(e) = state.save() {
11987        tracing::warn!("could not persist a cache wait: {e:#}");
11988    }
11989    let remaining = budget.saturating_sub(started.elapsed());
11990    let waited = crate::cache::wait_for_unless(
11991        &home,
11992        cache_dir,
11993        owner,
11994        remaining,
11995        Duration::from_secs(5),
11996        cancel,
11997    )
11998    .await;
11999    state.resource_wait = None;
12000    let cause = match &waited {
12001        Ok(Some(_)) => None,
12002        Ok(None) => Some(crate::run::ResourceBlockCause::Cancelled { park: None }),
12003        Err(error)
12004            if error.is::<crate::cache::WaitTimeout>() && kind == crate::build_target::KIND =>
12005        {
12006            Some(crate::run::ResourceBlockCause::IsolatedCacheTimeout {
12007                target: cache_dir.to_owned(),
12008                waited_secs: started.elapsed().as_secs(),
12009                limit_secs: budget.as_secs(),
12010            })
12011        }
12012        Err(error) if error.is::<crate::cache::WaitTimeout>() => {
12013            Some(crate::run::ResourceBlockCause::Timeout {
12014                waited_secs: started.elapsed().as_secs(),
12015                limit_secs: budget.as_secs(),
12016            })
12017        }
12018        Err(_) => Some(crate::run::ResourceBlockCause::Other),
12019    };
12020    if let Some(cause) = cause {
12021        let detail = match &waited {
12022            Ok(_) => "the wait for the build cache was cancelled".to_owned(),
12023            Err(error) => format!("{error:#}"),
12024        };
12025        state.resource_block = Some(crate::run::ResourceBlock {
12026            cause,
12027            node: node.to_owned(),
12028            kind: kind.into(),
12029            detail: format!("{}: {detail}", cache_dir.display()),
12030            at: Timestamp::now(),
12031        });
12032        state.event(
12033            "resource",
12034            state.resource_block.as_ref().unwrap().description(),
12035        );
12036    }
12037    if let Err(error) = state.save() {
12038        tracing::warn!("could not persist cache acquisition outcome: {error:#}");
12039    }
12040    waited
12041}
12042
12043/// The lease state could not be read at all (unreadable lease file, a
12044/// permission problem). Unlike a busy lease that outlasts its bound, nothing is
12045/// known to be contended, so a wave degrades to running without a shared cache
12046/// instead of stopping on a hold that [`crate::triage`] could never release.
12047#[derive(Debug)]
12048struct CacheCheckError(String);
12049
12050impl std::fmt::Display for CacheCheckError {
12051    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12052        f.write_str(&self.0)
12053    }
12054}
12055
12056impl std::error::Error for CacheCheckError {}
12057
12058/// Keep a specific acquisition outcome when the caller adds command evidence.
12059fn record_cache_error(state: &mut RunState, node: &str, error: &anyhow::Error) {
12060    let kind = if crate::build_target::isolated(&state.config) {
12061        crate::build_target::KIND
12062    } else {
12063        "shared build cache"
12064    };
12065    state
12066        .resource_block
12067        .get_or_insert_with(|| crate::run::ResourceBlock {
12068            cause: crate::run::ResourceBlockCause::Other,
12069            node: node.to_owned(),
12070            kind: kind.into(),
12071            detail: format!("{error:#}"),
12072            at: Timestamp::now(),
12073        });
12074    if let Err(error) = state.save() {
12075        tracing::warn!("could not persist cache resource block: {error:#}");
12076    }
12077}
12078
12079tokio::task_local! {
12080    static VERIFY_TARGET: PathBuf;
12081}
12082
12083/// Run `body` — a verify command batch — while holding the shared build
12084/// cache's lease, so this run's own full verification (`e2e`, `gate`) can
12085/// never interleave with another borrower's build against the same
12086/// `CARGO_TARGET_DIR`: a different run, a lingering reviewer past its
12087/// timeout, or a human's own `magi review`. See the `cache` module doc for
12088/// why this matters more than Cargo's own per-target locking covers — two
12089/// *different* worktrees building the same package name/version into one
12090/// cache directory is a staleness bug, not a lock contention one.
12091///
12092/// Cache acquisition has its own bound, `timeout_resource_wait`, just as
12093/// agent waves do. Repository scheduling also has its own bounded,
12094/// cancellable resource-wait policy. Contention must not consume the
12095/// verification budget: `body` receives the full `budget` after both leases
12096/// are acquired and the cache is fresh. Without a shared cache, only
12097/// repository coordination is acquired before handing over the full budget.
12098///
12099/// A lease that cannot be acquired within the resource wait is reported as a single
12100/// synthetic [`CommandOutcome`] (`code: None`) rather than silently skipping
12101/// verification — the same shape a spawn failure already takes in
12102/// [`run_commands`], so a caller need not special-case it.
12103#[allow(clippy::too_many_arguments)]
12104async fn with_cache_lease<'s, F, Fut>(
12105    state: &'s mut RunState,
12106    cache_dir: Option<&Path>,
12107    node: &str,
12108    seat: &str,
12109    worktree: &Path,
12110    head: &str,
12111    budget: Duration,
12112    context: &str,
12113    wait: &crate::repo_lock::WaitPolicy,
12114    body: F,
12115) -> Result<(Vec<CommandOutcome>, bool)>
12116where
12117    F: FnOnce(&'s mut RunState, Duration) -> Fut,
12118    Fut: std::future::Future<Output = (Vec<CommandOutcome>, bool, Vec<u32>)>,
12119{
12120    // Match editing waves: cache first, repository second. In particular,
12121    // pre_gate must never hold the repository while waiting for a wave's cache.
12122    let started = Instant::now();
12123    let home = crate::run::home();
12124    let isolated = crate::build_target::isolated(&state.config);
12125    let planned_target = if isolated {
12126        let plan = (|| -> Result<PathBuf> {
12127            crate::build_target::supports(&state.config)?;
12128            crate::build_target::resolve(&home, worktree)
12129        })();
12130        match plan {
12131            Ok(path) => Some(path),
12132            Err(error) => {
12133                record_cache_error(state, node, &error);
12134                return Ok((
12135                    vec![CommandOutcome {
12136                        command: "(planning isolated build cache)".into(),
12137                        code: None,
12138                        output_tail: format!("{error:#}"),
12139                        duration_ms: 0,
12140                        resource_blocked: true,
12141                    }],
12142                    false,
12143                ));
12144            }
12145        }
12146    } else {
12147        None
12148    };
12149    let cache_dir = planned_target.as_deref().or(cache_dir);
12150    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
12151    let guard = if let Some(cache_dir) = cache_dir {
12152        let owner = crate::cache::Owner::here(&state.id, node, seat, worktree, head);
12153        match acquire_cache_lease(
12154            state,
12155            cache_dir,
12156            &owner,
12157            resource_limit,
12158            node,
12159            context,
12160            &|| wait.cancelled(),
12161        )
12162        .await
12163        .and_then(|g| {
12164            g.ok_or_else(|| anyhow::anyhow!("the wait for the build cache was cancelled"))
12165        }) {
12166            Ok(g) => Some(g),
12167            Err(e) => {
12168                record_cache_error(state, node, &e);
12169                return Ok((
12170                    vec![CommandOutcome {
12171                        command: if isolated {
12172                            "(waiting for the isolated build cache)"
12173                        } else {
12174                            "(waiting for the shared build cache)"
12175                        }
12176                        .into(),
12177                        code: None,
12178                        output_tail: e.to_string(),
12179                        duration_ms: started.elapsed().as_millis() as u64,
12180                        resource_blocked: true,
12181                    }],
12182                    false,
12183                ));
12184            }
12185        }
12186    } else {
12187        None
12188    };
12189    let _coordination = coordinate_operation(state, worktree, wait).await?;
12190    if let Some(path) = &planned_target {
12191        state.event(node, format!("isolated build target: {}", path.display()));
12192    }
12193    if let Some(cache_dir) = cache_dir.filter(|_| !isolated) {
12194        let identity = crate::cache::Identity::new(worktree, head);
12195        let fresh = crate::cache::ensure_fresh(
12196            &home,
12197            cache_dir,
12198            &identity,
12199            &state.config.verify.cargo_manifests(),
12200        );
12201        if let Err(e) = fresh {
12202            record_cache_error(state, node, &e);
12203            state.event(
12204                "verify",
12205                format!(
12206                    "{context}: could not confirm the build cache matches {} at {}: {e:#}",
12207                    worktree.display(),
12208                    short(head)
12209                ),
12210            );
12211            if let Some(guard) = guard {
12212                guard.release();
12213            }
12214            return Ok((
12215                vec![CommandOutcome {
12216                    command: "(confirming the build cache is fresh)".into(),
12217                    code: None,
12218                    output_tail: e.to_string(),
12219                    duration_ms: started.elapsed().as_millis() as u64,
12220                    resource_blocked: true,
12221                }],
12222                false,
12223            ));
12224        }
12225    }
12226    let future = body(state, budget);
12227    let (outcomes, retried, timed_out_pids) = if let Some(target) = planned_target {
12228        VERIFY_TARGET.scope(target, future).await
12229    } else {
12230        future.await
12231    };
12232    if !timed_out_pids.is_empty() {
12233        wait_for_timed_out_children_to_die(&timed_out_pids).await;
12234    }
12235    // Drop repository coordination before releasing the cache, reversing the
12236    // acquisition order. A cancelled/error future also drops both guards.
12237    drop(_coordination);
12238    if let Some(guard) = guard {
12239        guard.release();
12240    }
12241    Ok((outcomes, retried))
12242}
12243
12244/// Poll `pids` — commands [`run_commands`] reports as still running when its
12245/// own timeout elapsed — until every one is confirmed gone, or
12246/// [`LEASE_RELEASE_MAX_WAIT`] passes, whichever comes first.
12247///
12248/// Real confirmation where confirmation is possible, not a substitute for
12249/// full process-tree observation: a grandchild the timed-out process spawned
12250/// and that survives independently of it is invisible to a pid check the
12251/// same way it always was, and continuing to observe and collect *that*
12252/// stays a different piece of work with its own owner. This only narrows a
12253/// fixed blind wait into an actual check of the pids this process does know
12254/// about.
12255async fn wait_for_timed_out_children_to_die(pids: &[u32]) {
12256    wait_for_pids_with(
12257        pids,
12258        crate::proc::pid_alive,
12259        LEASE_RELEASE_POLL,
12260        LEASE_RELEASE_MAX_WAIT,
12261    )
12262    .await;
12263}
12264
12265/// [`wait_for_timed_out_children_to_die`] with its liveness query, poll
12266/// interval and ceiling supplied by the caller, so the polling *logic* -
12267/// returns as soon as every pid reports dead, gives up at the ceiling
12268/// otherwise - is testable on millisecond durations without asking the real
12269/// OS about a pid at all.
12270async fn wait_for_pids_with<F: Fn(u32) -> bool>(
12271    pids: &[u32],
12272    alive: F,
12273    poll: Duration,
12274    max_wait: Duration,
12275) {
12276    let deadline = Instant::now() + max_wait;
12277    loop {
12278        if pids.iter().all(|&pid| !alive(pid)) {
12279            return;
12280        }
12281        if Instant::now() >= deadline {
12282            return;
12283        }
12284        tokio::time::sleep(poll).await;
12285    }
12286}
12287
12288/// Are any of `outcomes` [`CommandOutcome::resource_blocked`] - magi's own
12289/// admission that it could not even get a verify command to run, as opposed
12290/// to evidence the command actually produced? A caller that would otherwise
12291/// read a resource-blocked outcome as a red command must check this first:
12292/// see [`Runner::gate`], which retries rather than records `Blocked` when
12293/// this is true.
12294fn verify_inconclusive(outcomes: &[CommandOutcome]) -> bool {
12295    outcomes.iter().any(|o| o.resource_blocked)
12296}
12297
12298/// What [`Runner::gate_fix_round`] decided.
12299pub(crate) enum GateFix {
12300    /// The tree changed and `verify.e2e` is still green: run the gate again.
12301    Retry,
12302    /// No more rounds, nothing to fix, or the fix did not hold: the gate's
12303    /// last failure stands and the run ends blocked.
12304    Stop,
12305    /// `verify.e2e` could not run after the fix (magi's own contention):
12306    /// decide nothing now, a later reentry retries.
12307    Defer,
12308}
12309
12310/// Is every red command in `outcomes` an ordinary failure the code could
12311/// explain: it ran, exited non-zero, and said something?
12312///
12313/// A timeout, a spawn failure and a killed process all leave `code` `None`;
12314/// 126 / 127 are the POSIX shell's "cannot execute" / "not found". Output-free
12315/// exits carry nothing for a fixer to act on. Language-agnostic on purpose:
12316/// what the command is stays the gate's business.
12317pub(crate) fn gate_fixable(outcomes: &[CommandOutcome]) -> bool {
12318    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
12319    red.peek().is_some()
12320        && red.all(|o| {
12321            !o.resource_blocked
12322                && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
12323                && !o.output_tail.trim().is_empty()
12324        })
12325}
12326
12327/// Describe one verify command's outcome for the event log, distinguishing a
12328/// build/link failure — the toolchain never produced a binary to run — from
12329/// an actual test failure, since only the latter is a verdict on the patch.
12330fn e2e_outcome_label(o: &CommandOutcome) -> String {
12331    if o.ok() {
12332        return "pass".to_owned();
12333    }
12334    let reason = if o.build_failed() {
12335        format!("COULD NOT RUN ({:?}, build/link failure)", o.code)
12336    } else {
12337        format!("FAIL ({:?})", o.code)
12338    };
12339    format!(
12340        "{reason}\n{}",
12341        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
12342    )
12343}
12344
12345/// Does `outcomes` hold a failure worth one more run on the same commit?
12346///
12347/// Only an ordinary test result qualifies: every red command ran, exited
12348/// non-zero and said which way (not a build/link failure, a timeout or kill,
12349/// a spawn failure, the shell's own 126 / 127, or a resource block). Those are
12350/// evidence about the machine or the toolchain, never about a flaky test.
12351fn rerunnable_failure(outcomes: &[CommandOutcome]) -> bool {
12352    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
12353    red.peek().is_some()
12354        && !verify_inconclusive(outcomes)
12355        && red.all(|o| {
12356            !o.build_failed() && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
12357        })
12358}
12359
12360/// Said at the top of the output a fixer gets when the same command failed on
12361/// both attempts, so it reads as a reproduced failure and not a one-off.
12362const FAILED_TWICE: &str = "[this command failed twice on the same commit; the output below is \
12363                            the second attempt's]";
12364
12365/// Run `verify.e2e`, retrying once if the first attempt could not build or
12366/// link — a build/link failure is frequently a race against a shared
12367/// `CARGO_TARGET_DIR` (see AGENTS.md), not a verdict on the patch. Emits one
12368/// `verify` event per command, tagged with `context` (normally `"round N"`)
12369/// so the call sites that need this — the ordinary per-round leg in
12370/// `review_loop`, the deferred catch-up run `stop_reviewing` makes before it
12371/// will ever call a round green, `verify_current_head` and the gate-repair
12372/// check — read identically in the event log.
12373///
12374/// A failure that is a test result (see [`rerunnable_failure`]) is believed
12375/// only after the failed commands have run once more on the same commit, in
12376/// the same worktree and — because the caller holds it around this whole
12377/// function — under the same cache lease, with a full `timeout` of their own
12378/// (`[graph] rerun_failed_e2e`). A command that passes the second time is a
12379/// flake: the head is verified, the first failure is recorded and filed
12380/// (`crate::flake`, `RunState::verify_flakes`). A command that fails again
12381/// stands, carrying the second attempt's output. One verification is therefore
12382/// run at most three times: the build/link retry, then this one rerun.
12383/// `round` is the review round the verification belongs to, if any.
12384async fn run_e2e_with_retry(
12385    state: &mut RunState,
12386    shell: &[String],
12387    commands: &[String],
12388    worktree: &Path,
12389    timeout: Duration,
12390    context: &str,
12391    round: Option<usize>,
12392) -> (Vec<CommandOutcome>, bool, Vec<u32>) {
12393    let (mut e2e, mut timed_out_pids) = run_commands(
12394        state, "verify", "e2e", 0, shell, commands, worktree, timeout,
12395    )
12396    .await;
12397    for o in &e2e {
12398        state.event(
12399            "verify",
12400            format!("{context}: `{}` -> {}", o.command, e2e_outcome_label(o)),
12401        );
12402    }
12403    // A build/link failure is not a verdict on the patch — it is frequently a
12404    // race against a shared `CARGO_TARGET_DIR` (see AGENTS.md). Give verify
12405    // one retry before letting a red like that decide the round.
12406    let verify_retried = e2e.iter().any(CommandOutcome::build_failed);
12407    if verify_retried {
12408        state.event(
12409            "verify",
12410            format!(
12411                "{context}: verify could not build/link, not a test result — retrying once \
12412                 before concluding"
12413            ),
12414        );
12415        let retried = run_commands(
12416            state, "verify", "e2e", 1, shell, commands, worktree, timeout,
12417        )
12418        .await;
12419        e2e = retried.0;
12420        // Both attempts' timeouts matter, not just the last one: the first
12421        // attempt's descendants may still be alive alongside the retry's.
12422        timed_out_pids.extend(retried.1);
12423        for o in &e2e {
12424            state.event(
12425                "verify",
12426                format!(
12427                    "{context}: retry `{}` -> {}",
12428                    o.command,
12429                    e2e_outcome_label(o)
12430                ),
12431            );
12432        }
12433    }
12434    if state.config.graph.rerun_failed_e2e && rerunnable_failure(&e2e) {
12435        let failed: Vec<usize> = (0..e2e.len()).filter(|&i| !e2e[i].ok()).collect();
12436        let rerun_commands: Vec<String> = failed.iter().map(|&i| e2e[i].command.clone()).collect();
12437        let head = git::rev_parse(worktree, "HEAD").await.unwrap_or_default();
12438        state.event(
12439            "verify",
12440            format!(
12441                "{context}: {} failed with a test result — running it once more on the same \
12442                 commit {} before deciding",
12443                rerun_commands
12444                    .iter()
12445                    .map(|c| format!("`{c}`"))
12446                    .collect::<Vec<_>>()
12447                    .join(", "),
12448                short(&head)
12449            ),
12450        );
12451        let (second, pids) = run_commands(
12452            state,
12453            "verify",
12454            "e2e",
12455            1 + usize::from(verify_retried),
12456            shell,
12457            &rerun_commands,
12458            worktree,
12459            timeout,
12460        )
12461        .await;
12462        timed_out_pids.extend(pids);
12463        for o in &second {
12464            state.event(
12465                "verify",
12466                format!(
12467                    "{context}: rerun `{}` -> {}",
12468                    o.command,
12469                    e2e_outcome_label(o)
12470                ),
12471            );
12472        }
12473        let mut reproduced = false;
12474        for (slot, &i) in failed.iter().enumerate() {
12475            let Some(again) = second.get(slot) else {
12476                break;
12477            };
12478            let first = std::mem::replace(&mut e2e[i], again.clone());
12479            if again.ok() {
12480                let signature = crate::flake::signature(&first.output_tail, first.code);
12481                let flake = crate::run::VerifyFlake {
12482                    round,
12483                    context: context.to_owned(),
12484                    head: head.clone(),
12485                    command: first.command.clone(),
12486                    first_failure: summarize_verify(&first.output_tail, EVENT_OUTPUT_TAIL),
12487                    fingerprint: crate::flake::fingerprint(&state.repo, &signature),
12488                    at: Timestamp::now(),
12489                    task: None,
12490                    filed: false,
12491                    filing_error: None,
12492                };
12493                crate::flake::record(state, flake, &signature.label, &crate::queue::Queue::open());
12494            } else if !again.resource_blocked {
12495                reproduced = true;
12496                e2e[i].output_tail = format!("{FAILED_TWICE}\n{}", again.output_tail);
12497            }
12498        }
12499        if reproduced {
12500            state.event(
12501                "verify",
12502                format!("{context}: the failure reproduced on the second run — it stands"),
12503            );
12504        }
12505    }
12506    (e2e, verify_retried, timed_out_pids)
12507}
12508
12509/// Run configured shell commands in `cwd`, in order. The second element is
12510/// the pid of every command that hit `timeout` and was still running when
12511/// this stopped waiting on it (best-effort: `None` when the platform did not
12512/// hand one back) — see [`with_cache_lease`]'s use of it for why a caller
12513/// that releases a shared resource afterward needs to know.
12514///
12515/// Records `task` into [`RunState::active`] at every command boundary
12516/// (`RunState::task_command`) and clears it once the whole list has run
12517/// (`RunState::task_finished`) — a `verify.e2e` / `verify.gate` list can run
12518/// for minutes with no seat and no output of its own to show for it (see
12519/// `CommandOutcome`'s doc on why an empty `e2e`/`gate` alone cannot be told
12520/// apart from "not yet run" without this), and this is the only place that
12521/// knows which command is running right now and how many are left. Three
12522/// saves per command — start, not per second — matching the same "only at a
12523/// boundary" rule [`wave`] already follows for seats.
12524#[allow(clippy::too_many_arguments)]
12525async fn run_commands(
12526    state: &mut RunState,
12527    node: &str,
12528    task: &str,
12529    attempt: usize,
12530    shell: &[String],
12531    commands: &[String],
12532    cwd: &Path,
12533    timeout: Duration,
12534) -> (Vec<CommandOutcome>, Vec<u32>) {
12535    let isolated = crate::build_target::isolated(&state.config);
12536    if isolated && let Some(block) = &state.resource_block {
12537        return (
12538            vec![CommandOutcome {
12539                command: "(isolated build admission)".into(),
12540                code: None,
12541                output_tail: block.description(),
12542                duration_ms: 0,
12543                resource_blocked: true,
12544            }],
12545            Vec::new(),
12546        );
12547    }
12548    if commands.is_empty() {
12549        // Nothing to mark as running and nothing to clear — an empty list
12550        // means "not configured", and touching `active` (or the disk) over
12551        // that would be a write for every round of a repo with no
12552        // `verify.e2e` / `verify.gate` commands at all.
12553        return (Vec::new(), Vec::new());
12554    }
12555    let mut out = Vec::new();
12556    let mut timed_out_pids = Vec::new();
12557    let total = commands.len();
12558    for (idx, command) in commands.iter().enumerate() {
12559        state.task_command(task, node, attempt, command, idx + 1, total, timeout);
12560        if let Err(e) = state.save() {
12561            tracing::warn!("could not persist an in-progress {task} command: {e:#}");
12562        }
12563        let started = Instant::now();
12564        let mut cmd = tokio::process::Command::new(&shell[0]);
12565        cmd.quiet();
12566        // Verify the checkout as a standalone caller. Worker ownership and
12567        // pinned executable selection belong to this driver, not to tests or
12568        // tools it runs. Preserve home/seat context and Running's containment.
12569        for key in crate::worker::INVOCATION_ENV {
12570            cmd.env_remove(key);
12571        }
12572        cmd.args(&shell[1..])
12573            .current_dir(cwd)
12574            .stdin(std::process::Stdio::null())
12575            .stdout(std::process::Stdio::piped())
12576            .stderr(std::process::Stdio::piped())
12577            .kill_on_drop(true);
12578        let mut outputs = Vec::new();
12579        let mut cache = None;
12580        let home = crate::run::home();
12581        let head = if isolated {
12582            Some(git::rev_parse(cwd, "HEAD").await)
12583        } else {
12584            None
12585        };
12586        let protected = (|| -> Result<()> {
12587            crate::incremental::configure(&mut cmd, cwd)?;
12588            cache = if isolated {
12589                let target = VERIFY_TARGET
12590                    .try_with(Clone::clone)
12591                    .context("isolated verification has no target lease")?;
12592                cmd.arg(crate::build_target::command::normalize(command)?);
12593                crate::build_target::command::configure(&mut cmd, &target)?;
12594                Some(target)
12595            } else {
12596                crate::build_target::command::clear(&mut cmd)?;
12597                cmd.arg(command);
12598                state.config.cache_dir()
12599            };
12600            let mut paths = vec![cwd.to_owned()];
12601            if let Some(cache) = &cache {
12602                paths.push(cache.clone());
12603            }
12604            let admit = if isolated {
12605                crate::retention::OutputLease::admit_isolated
12606            } else {
12607                crate::retention::OutputLease::admit
12608            };
12609            outputs.extend(admit(&home, &paths, state.config.disk.min_free_bytes)?);
12610            if let Some(guard) = crate::retention::OutputLease::borrow(cwd)? {
12611                outputs.push(guard);
12612            }
12613            if let Some(cache) = &cache {
12614                outputs.push(crate::retention::OutputLease::cache(
12615                    &crate::run::home(),
12616                    cache,
12617                    false,
12618                )?);
12619                if let Some(head) = head {
12620                    crate::build_target::ensure_fresh(&home, cache, cwd, &head?, &state.config)?;
12621                    if task == "pre_gate" {
12622                        crate::cache::invalidate_identity(&home, cache);
12623                    }
12624                }
12625            }
12626            Ok(())
12627        })();
12628        if let Err(e) = protected {
12629            let detail = format!("execution admission unavailable: {e:#}");
12630            state.resource_block = Some(crate::run::ResourceBlock {
12631                cause: crate::run::ResourceBlockCause::Other,
12632                node: node.to_owned(),
12633                kind: if detail.contains("disk admission") {
12634                    "disk admission"
12635                } else {
12636                    "output ownership"
12637                }
12638                .to_owned(),
12639                detail: detail.clone(),
12640                at: Timestamp::now(),
12641            });
12642            out.push(CommandOutcome {
12643                command: command.clone(),
12644                code: None,
12645                output_tail: detail,
12646                duration_ms: 0,
12647                resource_blocked: true,
12648            });
12649            break;
12650        }
12651        let spawned = if isolated {
12652            crate::seat_process::Running::spawn_build(cmd, None, outputs)
12653        } else {
12654            crate::seat_process::Running::spawn(cmd, None, outputs)
12655        };
12656        let (code, body) = match spawned {
12657            Ok(mut running) => {
12658                let pid = running.child().id();
12659                let (stdout, out_reader) = agent::drain(running.child().stdout.take());
12660                let (stderr, err_reader) = agent::drain(running.child().stderr.take());
12661                let mut paths = vec![cwd.to_owned()];
12662                if let Some(cache) = cache {
12663                    paths.push(cache);
12664                }
12665                let mut pressure = None;
12666                let status = tokio::select! {
12667                    status = tokio::time::timeout(timeout, running.child().wait()) => Some(status),
12668                    reason = crate::retention::emergency(paths, state.config.disk.min_free_bytes, isolated) => {
12669                        pressure = Some(reason); None
12670                    }
12671                };
12672                let (code, failure) = match status {
12673                    Some(Ok(Ok(status))) => (
12674                        status.code(),
12675                        status
12676                            .code()
12677                            .is_none()
12678                            .then(|| format!("command terminated: {status}")),
12679                    ),
12680                    Some(Ok(Err(error))) => {
12681                        (None, Some(format!("failed waiting for command: {error}")))
12682                    }
12683                    Some(Err(_)) => {
12684                        // Leased cleanup confirms process-tree death itself.
12685                        // Unleased commands still need the caller's PID check
12686                        // after kill-on-drop, before releasing cache ownership.
12687                        if !running.coordinated()
12688                            && let Some(pid) = pid
12689                        {
12690                            timed_out_pids.push(pid);
12691                        }
12692                        (
12693                            None,
12694                            Some(format!("timed out after {}s", timeout.as_secs())),
12695                        )
12696                    }
12697                    None => (None, None),
12698                };
12699                running.finish().await;
12700                if let Some(reason) = pressure {
12701                    state.resource_block = Some(crate::run::ResourceBlock {
12702                        cause: crate::run::ResourceBlockCause::Other,
12703                        node: node.to_owned(),
12704                        kind: "disk pressure".to_owned(),
12705                        detail: reason.clone(),
12706                        at: Timestamp::now(),
12707                    });
12708                    out.push(CommandOutcome {
12709                        command: command.clone(),
12710                        code: None,
12711                        output_tail: reason,
12712                        duration_ms: started.elapsed().as_millis() as u64,
12713                        resource_blocked: true,
12714                    });
12715                    break;
12716                }
12717                let mut body = agent::collect(&stdout, out_reader, Duration::from_secs(2)).await;
12718                body.push_str(&agent::collect(&stderr, err_reader, Duration::from_secs(2)).await);
12719                if let Some(failure) = failure {
12720                    body.push('\n');
12721                    body.push_str(&failure);
12722                }
12723                (code, body)
12724            }
12725            Err(e) if isolated => {
12726                let e = anyhow::Error::new(e)
12727                    .context(format!("could not start managed build `{}`", shell[0]));
12728                record_cache_error(state, node, &e);
12729                out.push(CommandOutcome {
12730                    command: command.clone(),
12731                    code: None,
12732                    output_tail: format!("{e:#}"),
12733                    duration_ms: 0,
12734                    resource_blocked: true,
12735                });
12736                break;
12737            }
12738            Err(e) => (None, format!("failed to spawn `{}`: {e}", shell[0])),
12739        };
12740        let mut summary = summarize_verify(&body, crate::run::VERIFY_SUMMARY);
12741        if !body.is_empty() {
12742            // The full text is kept whatever the summary dropped. A fresh
12743            // name per command so a resume or retry never overwrites an
12744            // earlier run's output. A failed write changes no verdict.
12745            match crate::run::write_verification_artifact(state, task, &body) {
12746                Ok(name) if summary != body => {
12747                    summary = format!("[full output: artifacts/{name}]\n{summary}");
12748                }
12749                Ok(_) => {}
12750                Err(e) => {
12751                    let warning = format!("could not save the full {task} output: {e:#}");
12752                    tracing::warn!("{warning}");
12753                    state.event(node, warning);
12754                    if summary != body {
12755                        summary = format!("[full output could not be saved: {e:#}]\n{summary}");
12756                    }
12757                }
12758            }
12759        }
12760        let resource_blocked = code != Some(0) && body.contains(crate::incremental::BLOCKED);
12761        out.push(CommandOutcome {
12762            command: command.clone(),
12763            code,
12764            output_tail: summary,
12765            duration_ms: started.elapsed().as_millis() as u64,
12766            resource_blocked,
12767        });
12768        if resource_blocked {
12769            state.resource_block = Some(crate::run::ResourceBlock {
12770                cause: crate::run::ResourceBlockCause::Other,
12771                node: node.to_owned(),
12772                kind: "incremental cache admission".into(),
12773                detail: body,
12774                at: Timestamp::now(),
12775            });
12776            break;
12777        }
12778    }
12779    state.task_finished(task);
12780    if let Err(e) = state.save() {
12781        tracing::warn!("could not persist the end of {task}: {e:#}");
12782    }
12783    (out, timed_out_pids)
12784}
12785
12786/// The shell command line `mode = "none"` prints — in `magi show`'s `merge`
12787/// section (`report::run`) and in the `merge` event this node records — for
12788/// the operator to run by hand.
12789///
12790/// Built from [`MergeStyle`] rather than always `git merge --no-ff`: a base
12791/// branch whose ruleset forbids merge commits (GitHub's "must not contain
12792/// merge commits", or "require linear history") rejects the push a `--no-ff`
12793/// merge would produce, which is exactly the guidance this function replaces.
12794/// `message`'s first line becomes the squash commit's subject, matching the
12795/// note `report::run` prints alongside this command — see that function for
12796/// why an explicit subject is not optional there.
12797fn manual_merge_command(style: MergeStyle, repo: &Path, branch: &str, message: &str) -> String {
12798    let repo = repo.display();
12799    match style {
12800        MergeStyle::Merge => format!("git -C {repo} merge --no-ff {branch}"),
12801        MergeStyle::Squash => {
12802            // The subject sits inside double quotes, and a title an agent
12803            // wrote may carry the characters that break out of them.
12804            let subject = message
12805                .lines()
12806                .next()
12807                .unwrap_or(branch)
12808                .replace(['\\', '"', '$', '`'], "");
12809            format!(
12810                "git -C {repo} merge --squash {branch} && git -C {repo} commit -m \"{subject}\""
12811            )
12812        }
12813        MergeStyle::Rebase => format!("git -C {repo} merge --ff-only {branch}"),
12814    }
12815}
12816
12817/// GitHub's `createPullRequest` GraphQL mutation, which `gh pr create` calls
12818/// under the hood, rejects a `title` over 256 characters and the whole
12819/// command fails — no PR at all, for a run whose body was otherwise fine
12820/// (this is what happened to run 2963; see AGENTS.md). 240 leaves room below
12821/// that limit: titles are counted in `chars()` (Unicode scalars), which is not
12822/// always how GitHub counts. [`english_title`] keeps its trailing `...` inside
12823/// this bound. It is a margin, not a guarantee — a title packed
12824/// with multi-unit characters could still in principle land close to the
12825/// edge, but a real task title's occasional emoji or accented letter fits
12826/// comfortably inside it.
12827const PR_TITLE_MAX: usize = 240;
12828
12829/// A pull request title from the opening line of `text`, or `None` when that
12830/// line is not English (GitHub text is) or has no letters.
12831///
12832/// A line within `max` is kept as is. A longer one is cut at the end of its
12833/// first sentence when that falls inside `max`, else at a word boundary with a
12834/// plain `...` (ASCII, unlike the `…` `queue::title_from` appends, which would
12835/// make every merely-truncated title look non-English). The language check
12836/// runs on the kept text before any mark is added, so only what GitHub will
12837/// show is judged: an English opening followed by non-ASCII far past the cut
12838/// still passes.
12839fn english_title(text: &str, max: usize, ascii_only: bool) -> Option<String> {
12840    let line = queue::first_line(text)?;
12841    let chars: Vec<char> = line.chars().collect();
12842    let (kept, mark) = if chars.len() <= max {
12843        (line.to_owned(), "")
12844    } else if let Some(end) = sentence_end(&chars, max) {
12845        (chars[..end].iter().collect::<String>(), "")
12846    } else {
12847        let room = max.saturating_sub(3);
12848        // Cut at the last space inside the room; when the char just past the
12849        // room is a space the room already ends on a word.
12850        let cut = if chars[room].is_whitespace() {
12851            room
12852        } else {
12853            chars[..room]
12854                .iter()
12855                .rposition(|c| c.is_whitespace())
12856                .unwrap_or(room)
12857        };
12858        let head: String = chars[..cut].iter().collect();
12859        let head = head.trim_end_matches(|c: char| c.is_whitespace() || ",;:-".contains(c));
12860        (head.to_owned(), "...")
12861    };
12862    if kept.is_empty() {
12863        return None;
12864    }
12865    if ascii_only && (!kept.is_ascii() || !kept.chars().any(|c| c.is_ascii_alphabetic())) {
12866        return None;
12867    }
12868    if !ascii_only && !kept.chars().any(char::is_alphabetic) {
12869        return None;
12870    }
12871    Some(format!("{kept}{mark}"))
12872}
12873
12874/// The char length of the first sentence of `chars` when it ends within `max`
12875/// (the closing `.`/`!`/`?` dropped), skipping very short stubs and common
12876/// abbreviations so `e.g. foo` does not end a title early.
12877fn sentence_end(chars: &[char], max: usize) -> Option<usize> {
12878    const MIN: usize = 20;
12879    for i in MIN..max.min(chars.len()) {
12880        if !matches!(chars[i], '.' | '!' | '?') {
12881            continue;
12882        }
12883        let Some(&next) = chars.get(i + 1) else {
12884            continue;
12885        };
12886        if !next.is_whitespace() {
12887            continue;
12888        }
12889        let after = chars[i + 1..].iter().find(|c| !c.is_whitespace());
12890        if after.is_some_and(|c| c.is_ascii_lowercase()) {
12891            continue;
12892        }
12893        let word: String = chars[..i]
12894            .iter()
12895            .rev()
12896            .take_while(|c| !c.is_whitespace())
12897            .collect::<Vec<_>>()
12898            .into_iter()
12899            .rev()
12900            .collect();
12901        let word = word.to_ascii_lowercase();
12902        if matches!(word.as_str(), "e.g" | "i.e" | "etc" | "vs" | "cf") {
12903            continue;
12904        }
12905        let end = chars[..i]
12906            .iter()
12907            .rposition(|c| !c.is_whitespace())
12908            .map_or(i, |p| p + 1);
12909        return Some(end);
12910    }
12911    None
12912}
12913
12914/// What `merge = "pr"` (and the merge commit of the other modes) says about a
12915/// change: a title and a body describing what was *implemented*, not the task
12916/// that asked for it. A task reads as a request; a reader of the merged
12917/// history wants the change.
12918struct PrMessage {
12919    title: String,
12920    body: String,
12921}
12922
12923impl PrMessage {
12924    /// Title, blank line, body. The first line is the squash/merge commit
12925    /// subject (`manual_merge_command` takes it via `lines().next()`), so it
12926    /// has to stay one sensible line.
12927    fn commit_message(&self) -> String {
12928        format!("{}\n\n{}", self.title, self.body)
12929    }
12930}
12931
12932/// The text after a leading `TITLE:` (any case) on `line`.
12933fn title_marker(line: &str) -> Option<&str> {
12934    let line = line.trim();
12935    let head = line.get(..6)?;
12936    head.eq_ignore_ascii_case("title:")
12937        .then(|| line[6..].trim())
12938}
12939
12940/// The implementer's own one-line title: the `TITLE:` line the implement
12941/// prompt asks for at the top of its SUMMARY. Candidate commits are all
12942/// `magi: candidate X (uncommitted work)`, so a commit subject is never a
12943/// source, and a title that says as much is refused here too.
12944fn summary_title(summary: &str) -> Option<String> {
12945    let first = summary.lines().find(|l| !l.trim().is_empty())?;
12946    let raw = title_marker(first)?;
12947    if raw.is_empty() {
12948        return None;
12949    }
12950    let title = queue::title_from(raw, PR_TITLE_MAX);
12951    let lower = title.to_ascii_lowercase();
12952    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
12953        return None;
12954    }
12955    Some(title)
12956}
12957
12958/// How `open_review`'s instruction begins; see [`landing_title`].
12959const REVIEW_PROMPT_OPENING: &str = "Review the work already on branch";
12960
12961/// Marker `open_review` gives a candidate that nothing in the roster wrote.
12962pub(crate) const EXISTING_BRANCH: &str = "(existing branch)";
12963
12964/// Does this run review work that already existed, rather than implement a
12965/// task? Runs recorded before `reviewed_commits` existed carry only the
12966/// candidate marker.
12967pub(crate) fn is_review_run(state: &RunState) -> bool {
12968    state.reviewed_commits.is_some() || state.candidates.iter().any(|c| c.agent == EXISTING_BRANCH)
12969}
12970
12971/// The title of a review-only run: the subject of the oldest commit under
12972/// review. Later commits are usually fixups, and `instruction` is the review
12973/// prompt, which says nothing about the change. GitHub text is English, so a
12974/// non-ASCII or blank subject yields `None` and the caller's neutral title.
12975fn review_title(state: &RunState) -> Option<String> {
12976    english_subject(
12977        state.reviewed_commits.as_ref()?.first()?,
12978        state.config.graph.github_english(),
12979    )
12980}
12981
12982/// `raw` as a pull request title, or `None` when it is blank, not English
12983/// (GitHub text is), or one of magi's own candidate commit subjects.
12984fn english_subject(raw: &str, ascii_only: bool) -> Option<String> {
12985    let raw = raw.trim();
12986    if raw.is_empty() {
12987        return None;
12988    }
12989    if ascii_only && (!raw.is_ascii() || !raw.chars().any(|c| c.is_ascii_alphabetic())) {
12990        return None;
12991    }
12992    if !ascii_only && !raw.chars().any(char::is_alphabetic) {
12993        return None;
12994    }
12995    let title = queue::title_from(raw, PR_TITLE_MAX);
12996    let lower = title.to_ascii_lowercase();
12997    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
12998        return None;
12999    }
13000    Some(title)
13001}
13002
13003/// What a review-only run's branch says about itself, read at the moment the
13004/// pull request is opened.
13005#[derive(Debug, Clone, PartialEq, Eq)]
13006struct BranchFacts {
13007    /// `(subject, body)` of each commit, oldest first.
13008    commits: Vec<(String, String)>,
13009    /// Trimmed `git diff --stat`.
13010    stat: String,
13011}
13012
13013/// Longest diff stat shown: this many file lines plus the summary line.
13014const STAT_FILE_LINES: usize = 25;
13015/// Cap on the commit list, well inside GitHub's 65536-character body limit.
13016const COMMITS_MAX_CHARS: usize = 20_000;
13017
13018/// Read the commits and diff stat of `base..branch`. `None` when git cannot
13019/// say or finds nothing, so the caller falls back to what the run recorded.
13020async fn branch_facts(repo: &Path, base: &str, branch: &str) -> Option<BranchFacts> {
13021    let commits = git::commit_log(repo, base, branch).await.ok()?;
13022    if commits.is_empty() {
13023        return None;
13024    }
13025    let stat = git::diff_stat(repo, base, branch).await.unwrap_or_default();
13026    let lines: Vec<&str> = stat.lines().collect();
13027    let stat = if lines.len() > STAT_FILE_LINES + 1 {
13028        let omitted = lines.len() - 1 - STAT_FILE_LINES;
13029        let more = format!(" ... {omitted} more file(s)");
13030        let mut kept: Vec<&str> = lines[..STAT_FILE_LINES].to_vec();
13031        kept.push(&more);
13032        kept.push(lines[lines.len() - 1]);
13033        kept.join("\n")
13034    } else {
13035        lines.join("\n")
13036    };
13037    Some(BranchFacts { commits, stat })
13038}
13039
13040/// Defang what would break the surrounding markdown: a closing `</details>`
13041/// and a code fence.
13042fn markdown_safe(text: &str) -> String {
13043    text.replace("</details>", "&lt;/details&gt;")
13044        .replace("\x60\x60\x60", "~~~")
13045}
13046
13047fn neutral_title(state: &RunState, winner: char) -> String {
13048    format!(
13049        "chore: land candidate {} of run {}",
13050        winner.to_ascii_uppercase(),
13051        state.id
13052    )
13053}
13054
13055/// Reuse the graph's bounded fixer without starting another graph or driver.
13056/// Copy the working state back even on errors so spent rounds remain visible.
13057pub(crate) async fn repair_landing_gate(
13058    state: &mut RunState,
13059    winner: &Candidate,
13060    outcomes: &[CommandOutcome],
13061) -> Result<GateFix> {
13062    if state.gate_fixes.len() >= state.config.graph.gate_fix_rounds || !gate_fixable(outcomes) {
13063        return Ok(GateFix::Stop);
13064    }
13065    let mut runner = Runner {
13066        roles: state.config.resolve_roles()?,
13067        sem: Arc::new(Semaphore::new(state.config.graph.max_parallel.max(1))),
13068        state: state.clone(),
13069        pause: Pause::new(),
13070        interrupt: Pause::new(),
13071    };
13072    let result = runner.gate_fix_round(winner, outcomes).await;
13073    *state = runner.state;
13074    result
13075}
13076
13077/// Review judgment survives a clean rebase; command evidence belongs to a SHA.
13078/// A completed failure is terminal on that SHA. Resource waits remain retryable.
13079pub(crate) async fn verify_current_head(
13080    state: &mut RunState,
13081    winner: &Candidate,
13082    wait: &crate::repo_lock::WaitPolicy,
13083) -> Result<bool> {
13084    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13085    // Preserve the previous record before replacing it, including on crash recovery.
13086    if state.head_e2e.as_ref().is_some_and(|e| e.head != head) {
13087        state
13088            .verification_history
13089            .push(crate::run::VerificationEvidence {
13090                superseded_by: Some(head.clone()),
13091                archived_at: Some(Timestamp::now()),
13092                fixes_spent: Some(state.gate_fixes.len()),
13093                gate_head: None,
13094                gate_ran: false,
13095                gate: Vec::new(),
13096                e2e: state.head_e2e.take(),
13097            });
13098    }
13099    if let Some(e) = &state.head_e2e
13100        && e.head == head
13101    {
13102        if e.passed {
13103            return Ok(true);
13104        }
13105        if !e.outcomes.is_empty() && !verify_inconclusive(&e.outcomes) {
13106            state.status = RunStatus::Blocked;
13107            state.save()?;
13108            return Ok(false);
13109        }
13110    } else if state.reviews.last().is_some_and(|r| {
13111        r.verified_head.as_deref() == Some(head.as_str())
13112            && (r.e2e_status() == E2eStatus::Passed
13113                || (r.e2e_status() == E2eStatus::NotConfigured
13114                    && state.config.verify.e2e.is_empty()))
13115    }) || state
13116        .gate_repair_e2e
13117        .as_ref()
13118        .is_some_and(|e| e.head == head && e.passed)
13119    {
13120        return Ok(true);
13121    }
13122    if let Some(e) = &state.gate_repair_e2e
13123        && e.head == head
13124        && !e.passed
13125        && !e.outcomes.is_empty()
13126        && !verify_inconclusive(&e.outcomes)
13127    {
13128        state.status = RunStatus::Blocked;
13129        state.save()?;
13130        return Ok(false);
13131    }
13132    state.head_e2e = Some(crate::run::GateRepairE2e {
13133        head: head.clone(),
13134        passed: false,
13135        outcomes: Vec::new(),
13136    });
13137    state.save()?;
13138    let commands = state.config.verify.e2e.clone();
13139    let shell = state.config.shell();
13140    let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13141    let cache_dir = state.config.cache_dir();
13142    let outcomes = if commands.is_empty() {
13143        Vec::new()
13144    } else {
13145        let (outcomes, _) = with_cache_lease(
13146            state,
13147            cache_dir.as_deref(),
13148            "e2e",
13149            "e2e",
13150            &winner.worktree,
13151            &head,
13152            timeout,
13153            "current head e2e",
13154            wait,
13155            |state, budget| async move {
13156                run_e2e_with_retry(
13157                    state,
13158                    &shell,
13159                    &commands,
13160                    &winner.worktree,
13161                    budget,
13162                    "current head e2e",
13163                    None,
13164                )
13165                .await
13166            },
13167        )
13168        .await?;
13169        outcomes
13170    };
13171    let unresolved = verify_inconclusive(&outcomes);
13172    let passed = !unresolved
13173        && outcomes.iter().all(CommandOutcome::ok)
13174        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
13175    if !outcomes.is_empty() && !unresolved {
13176        state.record_base_progress(&head);
13177    }
13178    state.head_e2e = Some(crate::run::GateRepairE2e {
13179        head: head.clone(),
13180        passed,
13181        outcomes,
13182    });
13183    if !passed && !unresolved {
13184        state.status = RunStatus::Blocked;
13185        state.event(
13186            "e2e",
13187            format!("verify.e2e failed on head {head}; nothing published"),
13188        );
13189    }
13190    state.save()?;
13191    Ok(passed)
13192}
13193
13194/// Recheck a repair's e2e requirement across failures, resource deferrals and
13195/// process interruptions. A successful result only applies to its exact SHA.
13196pub(crate) async fn check_gate_repair_e2e(
13197    state: &mut RunState,
13198    winner: &Candidate,
13199    wait: &crate::repo_lock::WaitPolicy,
13200) -> Result<GateFix> {
13201    if state.gate_repair_e2e.is_none() && state.gate_fixes.is_empty() {
13202        return Ok(GateFix::Retry);
13203    }
13204    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13205    if state
13206        .gate_repair_e2e
13207        .as_ref()
13208        .is_some_and(|r| r.head == head && r.passed)
13209    {
13210        return Ok(GateFix::Retry);
13211    }
13212    state.gate_repair_e2e = Some(crate::run::GateRepairE2e {
13213        head: head.clone(),
13214        passed: false,
13215        outcomes: Vec::new(),
13216    });
13217    state.save()?;
13218    let commands = state.config.verify.e2e.clone();
13219    let outcomes = if commands.is_empty() {
13220        Vec::new()
13221    } else {
13222        let shell = state.config.shell();
13223        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13224        let cache_dir = state.config.cache_dir();
13225        let (outcomes, _) = with_cache_lease(
13226            state,
13227            cache_dir.as_deref(),
13228            "e2e",
13229            "e2e",
13230            &winner.worktree,
13231            &head,
13232            timeout,
13233            "gate repair e2e",
13234            wait,
13235            |state, budget| async move {
13236                run_e2e_with_retry(
13237                    state,
13238                    &shell,
13239                    &commands,
13240                    &winner.worktree,
13241                    budget,
13242                    "gate repair e2e",
13243                    None,
13244                )
13245                .await
13246            },
13247        )
13248        .await?;
13249        outcomes
13250    };
13251    let deferred = verify_inconclusive(&outcomes);
13252    let passed = outcomes.iter().all(CommandOutcome::ok)
13253        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
13254    state.gate_repair_e2e = Some(crate::run::GateRepairE2e {
13255        head,
13256        passed,
13257        outcomes,
13258    });
13259    state.save()?;
13260    if deferred {
13261        Ok(GateFix::Defer)
13262    } else if !passed {
13263        state.event(
13264            "gate",
13265            "verify.e2e failed after gate repair; nothing published",
13266        );
13267        Ok(GateFix::Stop)
13268    } else {
13269        Ok(GateFix::Retry)
13270    }
13271}
13272
13273/// Run the same configured gate for a landing head and a fresh graph.
13274pub(crate) async fn run_landing_gate(
13275    state: &mut RunState,
13276    winner: &Candidate,
13277    wait: &crate::repo_lock::WaitPolicy,
13278) -> Result<Vec<CommandOutcome>> {
13279    let shell = state.config.shell();
13280    let gate_commands = state.config.verify.gate.clone();
13281    let has_pre_gate = !state.config.verify.pre_gate.is_empty();
13282    let outcomes = if gate_commands.is_empty() && !has_pre_gate {
13283        state.gate_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
13284        Vec::new()
13285    } else {
13286        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13287        let cache_dir = state.config.cache_dir();
13288        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13289        let (outcomes, _) = with_cache_lease(
13290            state,
13291            cache_dir.as_deref(),
13292            "gate",
13293            "gate",
13294            &winner.worktree,
13295            &head,
13296            timeout,
13297            "final gate",
13298            wait,
13299            |state, budget| {
13300                let shell = shell.clone();
13301                let gate_commands = gate_commands.clone();
13302                let winner = winner.clone();
13303                async move {
13304                    Runner::run_pre_gate(state, &winner).await;
13305                    // Bind command evidence after mechanical fixes, before commands start.
13306                    state.gate_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
13307                    let (outcomes, timed_out_pids) = run_commands(
13308                        state,
13309                        "gate",
13310                        "gate",
13311                        0,
13312                        &shell,
13313                        &gate_commands,
13314                        &winner.worktree,
13315                        budget,
13316                    )
13317                    .await;
13318                    (outcomes, false, timed_out_pids)
13319                }
13320            },
13321        )
13322        .await?;
13323        outcomes
13324    };
13325    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
13326    if !verify_inconclusive(&outcomes) && state.gate_head.as_deref() != Some(current.as_str()) {
13327        let mut outcomes = outcomes;
13328        outcomes.push(CommandOutcome {
13329            command: "gate head stability".into(), code: None,
13330            output_tail: "winner changed during gate, or checked head is unknown; fresh verification required".into(),
13331            duration_ms: 0, resource_blocked: false,
13332        });
13333        return Ok(outcomes);
13334    }
13335    if outcomes.is_empty() {
13336        // Nothing configured to check — distinct from every other
13337        // silence in this run's event log, since an empty `gate` alone
13338        // no longer says whether the gate ran at all (see
13339        // `RunState::gate_ran`'s own doc).
13340        state.event("gate", "no gate commands configured; not tested");
13341    }
13342    for o in &outcomes {
13343        state.event(
13344            "gate",
13345            format!(
13346                "`{}` -> {}",
13347                o.command,
13348                if o.ok() {
13349                    "pass".to_owned()
13350                } else {
13351                    format!(
13352                        "FAIL ({:?})\n{}",
13353                        o.code,
13354                        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
13355                    )
13356                }
13357            ),
13358        );
13359    }
13360    Ok(outcomes)
13361}
13362
13363/// The pull request title to hand to `land::merge_subject`. A review-only run
13364/// opened by an earlier build titled its pull request with the review prompt;
13365/// that title is dropped (empty, so the fallback applies) rather than landed.
13366/// Any other title, including an operator's rename, passes through untouched,
13367/// and so does every title of a run that implements a task.
13368pub fn landing_title<'a>(state: &RunState, pr_title: &'a str) -> &'a str {
13369    if is_review_run(state) && pr_title.trim_start().starts_with(REVIEW_PROMPT_OPENING) {
13370        ""
13371    } else {
13372        pr_title
13373    }
13374}
13375
13376/// What the squash subject falls back to when the pull request title is empty
13377/// or candidate-shaped: for a review-only run the derived title, never the
13378/// review prompt held in `instruction`.
13379pub fn landing_subject_source(state: &RunState) -> String {
13380    if is_review_run(state) {
13381        let winner = state.candidates.first().map_or('A', |c| c.label);
13382        return review_title(state).unwrap_or_else(|| neutral_title(state, winner));
13383    }
13384    state.instruction.clone()
13385}
13386
13387/// `summary` without its `TITLE:` line, which the pull request title already
13388/// carries.
13389fn summary_without_title(summary: &str) -> String {
13390    let mut lines = summary.trim().lines().peekable();
13391    if lines.peek().is_some_and(|l| title_marker(l).is_some()) {
13392        lines.next();
13393    }
13394    lines.collect::<Vec<_>>().join("\n").trim().to_owned()
13395}
13396
13397/// The pull request title and body for the winning candidate.
13398///
13399/// Title: the implementer's `TITLE:` line ([`summary_title`]), falling back to
13400/// the task's own opening line via [`queue::title_from`] when there is none.
13401/// `state.instruction` can open with blank lines (`task_text` only rejects a
13402/// body that is blank *entirely*), which `title_from` skips.
13403///
13404/// Publishing uses an independent description generated from the final diff
13405/// and structured evidence. Internal summaries and reports remain local.
13406/// Non-publishing previews may display the original task and candidate summary.
13407/// The footer retains the run and candidate provenance.
13408#[cfg(test)]
13409fn pr_message(state: &RunState, winner: char) -> PrMessage {
13410    pr_message_with(state, winner, None)
13411}
13412
13413/// [`pr_message`] with what the branch of a review-only run says about itself.
13414/// `facts` is ignored for a run that implements a task.
13415#[cfg(test)]
13416fn pr_message_with(state: &RunState, winner: char, facts: Option<&BranchFacts>) -> PrMessage {
13417    let raw = pr_message_raw(
13418        state,
13419        winner,
13420        facts,
13421        crate::pr_outcome::FinalHead::Unreported,
13422        ChangeNote::NotAsked,
13423    );
13424    let id = crate::scrub::Identity::current();
13425    PrMessage {
13426        title: crate::scrub::scrub(&raw.title, &id),
13427        body: crate::scrub::scrub(&raw.body, &id),
13428    }
13429}
13430
13431/// What the public description may say about the change itself.
13432#[derive(Debug, Clone, Copy)]
13433enum ChangeNote<'a> {
13434    /// A local preview or non-publishing merge mode: no public generation needed.
13435    NotAsked,
13436    /// A summary written from the final diff.
13437    Summary(&'a crate::run::ChangeSummary),
13438    /// A summary was asked for and could not be produced; the text says why.
13439    Unavailable(&'a str),
13440}
13441
13442fn pr_message_raw(
13443    state: &RunState,
13444    winner: char,
13445    facts: Option<&BranchFacts>,
13446    head: crate::pr_outcome::FinalHead<'_>,
13447    change: ChangeNote<'_>,
13448) -> PrMessage {
13449    if !matches!(change, ChangeNote::NotAsked) {
13450        let (title, mut body) = match change {
13451            ChangeNote::Summary(c) => (
13452                c.title.clone(),
13453                format!("## Summary\n\n{}\n\n", c.body.trim()),
13454            ),
13455            ChangeNote::Unavailable(why) => (
13456                neutral_title(state, winner),
13457                format!(
13458                    "## 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"
13459                ),
13460            ),
13461            ChangeNote::NotAsked => unreachable!(),
13462        };
13463        body.push_str(&public_pr_evidence(state, head));
13464        body.push_str(&format!(
13465            "\n---\nmagi:run/{} magi:candidate-{}\n",
13466            state.id,
13467            winner.to_ascii_lowercase()
13468        ));
13469        return PrMessage { title, body };
13470    }
13471    pr_preview(state, winner, facts, head)
13472}
13473
13474/// Append public facts from the run records after every prose generation,
13475/// including posting-gate rewrites. The agent cannot drop this provenance.
13476fn public_pr_evidence(state: &RunState, head: crate::pr_outcome::FinalHead<'_>) -> String {
13477    let mut body = crate::pr_outcome::review_rounds(state);
13478    body.push_str(&crate::pr_outcome::final_verification(state, head));
13479    let open = state.last_round_findings();
13480    if !open.is_empty() {
13481        body.push_str("## Open review findings\n\n");
13482        for f in open {
13483            body.push_str(&format!("- `{}` [{:?}]\n", f.id, f.severity));
13484        }
13485        body.push('\n');
13486    }
13487    if let Some(c) = state.change_summary.as_ref()
13488        && head == crate::pr_outcome::FinalHead::At(&c.head)
13489    {
13490        body.push_str(&format!(
13491            "Evidence: final diff `{}`..`{}`; review and verification records from this run.\n",
13492            c.base, c.head
13493        ));
13494    }
13495    body
13496}
13497
13498/// Local-only preview of the operator's task and candidate summary.
13499fn pr_preview(
13500    state: &RunState,
13501    winner: char,
13502    facts: Option<&BranchFacts>,
13503    head: crate::pr_outcome::FinalHead<'_>,
13504) -> PrMessage {
13505    let summary = state
13506        .candidates
13507        .iter()
13508        .find(|c| c.label == winner)
13509        .map(|c| c.summary.as_str())
13510        .unwrap_or_default();
13511    // The fallback is the operator's own words and may not be English; GitHub
13512    // text always is, so a non-English task gets a neutral title instead.
13513    let review = is_review_run(state);
13514    let title = if review {
13515        facts
13516            .and_then(|f| {
13517                english_subject(&f.commits.first()?.0, state.config.graph.github_english())
13518            })
13519            .or_else(|| review_title(state))
13520            .or_else(|| {
13521                state
13522                    .candidates
13523                    .iter()
13524                    .find(|c| c.label == winner)
13525                    .filter(|c| !c.branch.starts_with("magi/"))
13526                    .and_then(|c| english_subject(&c.branch, state.config.graph.github_english()))
13527            })
13528            .unwrap_or_else(|| neutral_title(state, winner))
13529    } else {
13530        summary_title(summary).unwrap_or_else(|| {
13531            english_title(
13532                &state.instruction,
13533                PR_TITLE_MAX,
13534                state.config.graph.github_english(),
13535            )
13536            .unwrap_or_else(|| neutral_title(state, winner))
13537        })
13538    };
13539
13540    let mut body = String::new();
13541    let what = summary_without_title(summary);
13542    if !what.is_empty() {
13543        body.push_str("## Summary\n\n");
13544        body.push_str(&what);
13545        body.push_str("\n\n");
13546    }
13547
13548    // Review history uses structured facts across all rounds, never reports.
13549    body.push_str(&crate::pr_outcome::review_rounds(state));
13550    body.push_str(&crate::pr_outcome::final_verification(state, head));
13551    let fix = state.reviews.iter().rev().find_map(|r| r.fix.as_ref());
13552
13553    let open = state.open_findings();
13554    if !open.is_empty() {
13555        body.push_str("## Open review findings\n\n");
13556        for f in &open {
13557            body.push_str(&format!(
13558                "- `{}` [{:?}] {}\n",
13559                f.id, f.severity, "Context retained in local review records."
13560            ));
13561        }
13562        body.push('\n');
13563    }
13564
13565    if let Some(fix) = fix
13566        && !fix.rejected.is_empty()
13567    {
13568        body.push_str("## Declined by the fixer\n\n");
13569        for r in &fix.rejected {
13570            body.push_str(&format!(
13571                "- `{}`: {}\n",
13572                r.id, "Reason retained in local review records."
13573            ));
13574        }
13575        body.push('\n');
13576    }
13577
13578    if review {
13579        // The review prompt is not the task; list what the branch carries.
13580        body.push_str("## Commits under review\n\n");
13581        if let Some(facts) = facts {
13582            let mut left = COMMITS_MAX_CHARS;
13583            for (i, (subject, text)) in facts.commits.iter().enumerate() {
13584                let mut entry = format!("- {}\n", markdown_safe(subject));
13585                for l in markdown_safe(text).lines() {
13586                    entry.push_str(format!("  {l}\n").trim_end_matches(' '));
13587                }
13588                if left == 0 {
13589                    body.push_str(&format!(
13590                        "- ... {} more commit(s)\n",
13591                        facts.commits.len() - i
13592                    ));
13593                    break;
13594                }
13595                if entry.len() > left {
13596                    // Even the first commit is cut: one huge body must not
13597                    // push the whole description past GitHub's limit.
13598                    let mut end = left;
13599                    while !entry.is_char_boundary(end) {
13600                        end -= 1;
13601                    }
13602                    entry.truncate(end);
13603                    entry.push_str("\n  ... (truncated)\n");
13604                    left = 0;
13605                } else {
13606                    left -= entry.len();
13607                }
13608                body.push_str(&entry);
13609            }
13610            if !facts.stat.trim().is_empty() {
13611                body.push_str(&format!(
13612                    "\n## Diff stat\n\n```\n{}\n```\n",
13613                    markdown_safe(facts.stat.trim())
13614                ));
13615            }
13616        } else {
13617            match &state.reviewed_commits {
13618                Some(subjects) => {
13619                    for s in subjects {
13620                        body.push_str(&format!("- {}\n", s.trim()));
13621                    }
13622                }
13623                None => {
13624                    // An older run kept only the prompt, with the commit list
13625                    // after its first paragraph.
13626                    let rest = state.instruction.split_once("\n\n").map_or("", |(_, r)| r);
13627                    body.push_str(rest.trim());
13628                    body.push('\n');
13629                }
13630            }
13631        }
13632    } else {
13633        let task = state.instruction.trim();
13634        let task = if task.is_empty() {
13635            "(empty task)"
13636        } else {
13637            task
13638        };
13639        body.push_str(&format!(
13640            "<details>\n<summary>Original task</summary>\n\n{}\n\n</details>\n",
13641            task.replace("</details>", "&lt;/details&gt;")
13642        ));
13643    }
13644
13645    body.push_str(&format!(
13646        "\n---\nmagi:run/{} magi:candidate-{}\n",
13647        state.id,
13648        winner.to_ascii_lowercase()
13649    ));
13650
13651    PrMessage { title, body }
13652}
13653
13654/// Source imports have already been prepared from structured inputs. Legacy
13655/// inferred references must never instruct a seat to reconstruct those imports.
13656fn seeded_instruction(state: &RunState) -> String {
13657    let mut inputs = Vec::new();
13658    if let Some(start) = &state.sources.start_from {
13659        inputs.push(format!(
13660            "Start from `{}` at `{}` (including ancestry).",
13661            start.token, start.sha
13662        ));
13663    }
13664    for pick in &state.sources.pick_commits {
13665        inputs.push(format!(
13666            "Pick `{}` at `{}` (single commit).",
13667            pick.token, pick.sha
13668        ));
13669    }
13670    if inputs.is_empty() {
13671        state.instruction.clone()
13672    } else {
13673        format!(
13674            "{}\n\n# Explicit source inputs already prepared\n\n{}",
13675            state.instruction,
13676            inputs.join("\n")
13677        )
13678    }
13679}
13680
13681/// Does the winner have no commits ahead of the base it would land on?
13682/// Any failure to find out reads as "not empty": the merge then behaves as it
13683/// always did rather than refusing on a guess.
13684async fn merge_is_empty(repo: &Path, state: &RunState, branch: &str, mode: MergeMode) -> bool {
13685    let base = &state.base_branch;
13686    let mut against = base.clone();
13687    if mode == MergeMode::Pr {
13688        // A pull request lands on the remote's base, never the local branch
13689        // of the same name: if that cannot be read, "not empty" is the safe
13690        // answer.
13691        let remote = &state.config.merge.remote;
13692        let tracking = format!("{remote}/{base}");
13693        let fetched = git::fetch(repo, remote, base).await;
13694        if fetched.is_ok_and(|o| o.ok()) && git::rev_exists(repo, &tracking).await {
13695            against = tracking;
13696        } else {
13697            return false;
13698        }
13699    }
13700    matches!(git::commits_ahead(repo, &against, branch).await, Ok(0))
13701}
13702
13703/// Why nothing was opened for an empty winner, with what the task's own
13704/// references resolved to.
13705fn empty_candidate_detail(_state: &RunState, base: &str) -> String {
13706    let mut detail = format!(
13707        "empty candidate: the winning branch has 0 commits ahead of {base}, so there is \
13708         nothing to open a pull request for"
13709    );
13710    detail.push_str(
13711        "\nSource imports require explicit --start-from or --pick-commit options on a new task.",
13712    );
13713    detail
13714}
13715
13716/// What the `Pr` merge does once it knows whether the branch already has an
13717/// open pull request.
13718#[derive(Debug, PartialEq, Eq)]
13719enum PrPlan {
13720    Create,
13721    Adopt { url: String, title: String },
13722    Stop(String),
13723}
13724
13725/// Pure decision behind the `Pr` merge: none -> create, one -> adopt, many or
13726/// a failed lookup -> stop with the real reason. Never guesses.
13727fn pr_merge_plan(found: Result<land::OpenPr>) -> PrPlan {
13728    match found {
13729        Ok(land::OpenPr::None) => PrPlan::Create,
13730        Ok(land::OpenPr::One { url, title }) => PrPlan::Adopt { url, title },
13731        Ok(land::OpenPr::Many(urls)) => PrPlan::Stop(format!(
13732            "several open pull requests exist for this branch, not picking one: {}",
13733            urls.join(" ")
13734        )),
13735        Err(e) => PrPlan::Stop(format!("could not look up open pull requests: {e:#}")),
13736    }
13737}
13738
13739/// `gh pr create`, returning the PR url.
13740pub(crate) async fn gh_pr_create(
13741    cwd: &Path,
13742    base: &str,
13743    head: &str,
13744    title: &str,
13745    body: &str,
13746) -> Result<String> {
13747    let out = tokio::process::Command::new("gh")
13748        .args([
13749            "pr", "create", "--base", base, "--head", head, "--title", title, "--body", body,
13750        ])
13751        .current_dir(cwd)
13752        .quiet()
13753        .stdin(std::process::Stdio::null())
13754        .output()
13755        .await
13756        .context("spawn gh")?;
13757    if out.status.success() {
13758        Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
13759    } else {
13760        bail!("{}", String::from_utf8_lossy(&out.stderr).trim().to_owned())
13761    }
13762}
13763
13764/// Never force deletion of uncommitted work, including unknown legacy trees.
13765async fn remove_preserved_worktree(repo: &Path, path: &Path) -> Result<()> {
13766    match std::fs::symlink_metadata(path) {
13767        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
13768            // A previous cleanup may have removed the tree before a branch
13769            // deletion or state save failed. Unregister it if still present.
13770            git::worktree_remove_clean(repo, path).await?;
13771            return Ok(());
13772        }
13773        Err(e) => return Err(e.into()),
13774        Ok(_) => {}
13775    }
13776    if !git::is_clean(path).await? {
13777        bail!(
13778            "worktree has uncommitted work; refusing removal: {}",
13779            path.display()
13780        );
13781    }
13782    if !git::worktree_remove_clean(repo, path).await? {
13783        bail!("worktree removal refused: {}", path.display());
13784    }
13785    Ok(())
13786}
13787
13788/// Read seats return replies, not working-tree changes. Only registered,
13789/// detached seats directly inside this run's root may discard those changes.
13790async fn remove_read_seat_worktree(state: &mut RunState, path: &Path) -> Result<()> {
13791    if !crate::retention::read_seat(path) || !path.exists() {
13792        return remove_preserved_worktree(&state.repo, path).await;
13793    }
13794    let owned = std::fs::symlink_metadata(path)?.is_dir()
13795        && path.parent().map(Path::canonicalize).transpose()?
13796            == Some(state.worktree_root().canonicalize()?)
13797        && crate::retention::worktrees(state)
13798            .await?
13799            .contains(&path.canonicalize()?);
13800    let common = crate::repo_lock::common_dir(&state.repo).await?;
13801    if !owned
13802        || common.is_none()
13803        || crate::repo_lock::common_dir(path).await? != common
13804        || git::git_raw(path, &["symbolic-ref", "-q", "HEAD"])
13805            .await?
13806            .ok()
13807        || state.candidates.iter().any(|c| c.worktree == path)
13808    {
13809        return remove_preserved_worktree(&state.repo, path).await;
13810    }
13811    let changes = git::status_porcelain(path).await?;
13812    if !git::worktree_remove(&state.repo, path).await? {
13813        bail!(
13814            "read-only seat worktree removal refused: {}",
13815            path.display()
13816        );
13817    }
13818    if !changes.is_empty() {
13819        let paths = changes.lines().take(20).collect::<Vec<_>>().join("; ");
13820        let paths: String = paths.chars().take(1024).collect();
13821        state.event(
13822            "fold",
13823            format!(
13824                "discarded read-only seat {} changes ({} status entries; first 20, at most 1024 chars): {paths}",
13825                path.file_name().unwrap_or_default().to_string_lossy(),
13826                changes.lines().count()
13827            ),
13828        );
13829    }
13830    Ok(())
13831}
13832
13833fn fold_target(
13834    home: &Path,
13835    root: &Path,
13836    path: &Path,
13837    isolated: bool,
13838) -> Option<crate::build_target::FoldTarget> {
13839    if !isolated {
13840        return None;
13841    }
13842    match crate::build_target::FoldTarget::for_checkout(home, path, root) {
13843        Ok(target) => target,
13844        Err(error) => {
13845            tracing::warn!(checkout = %path.display(), %error, "isolated target binding not proved at fold");
13846            None
13847        }
13848    }
13849}
13850
13851fn reclaim_fold_target(home: &Path, target: Option<crate::build_target::FoldTarget>) {
13852    if let Some(target) = target
13853        && let Err(error) = target.reclaim_orphaned_target(home)
13854    {
13855        tracing::warn!(%error, "isolated target retained after fold");
13856    }
13857}
13858
13859/// Tear a run's worktrees and branches down.
13860///
13861/// `home` is where the updated `run.json` is saved (via
13862/// [`RunState::save_under`]), never the process-global [`crate::run::home`]:
13863/// a housekeeping pass already has its own honest `home` handed to it, and
13864/// falling through to the global here would write back through whichever
13865/// directory some other process or test pinned into that `OnceLock` first,
13866/// not the one the caller actually resolved its `runs` and `state` from.
13867pub async fn fold_run(state: &mut RunState, drop_winner: bool, home: &Path) -> Result<Vec<String>> {
13868    fold_run_with_policy(state, drop_winner, home, false).await
13869}
13870
13871/// Explicit CLI-only retention override; automatic callers use [`fold_run`].
13872pub async fn fold_run_overriding_recovery_retention(
13873    state: &mut RunState,
13874    drop_winner: bool,
13875    home: &Path,
13876) -> Result<Vec<String>> {
13877    fold_run_with_policy(state, drop_winner, home, true).await
13878}
13879
13880async fn fold_run_with_policy(
13881    state: &mut RunState,
13882    drop_winner: bool,
13883    home: &Path,
13884    override_recovery_retention: bool,
13885) -> Result<Vec<String>> {
13886    if let Some(reason) = crate::pr_recovery::source_retention_reason(home, state)
13887        && !override_recovery_retention
13888    {
13889        bail!("refusing fold: {reason}");
13890    }
13891    if !state.candidate_preservation.is_empty() || !state.interrupted_implementations.is_empty() {
13892        bail!("candidate preservation incomplete; refusing cleanup");
13893    }
13894    // Serialize ordinary folding with the same starts/resumes as target-only
13895    // eviction. Otherwise a second janitor could remove the whole worktree
13896    // around a live output borrower even though target eviction was fenced.
13897    std::fs::create_dir_all(home.join("runs").join(&state.id))?;
13898    let _owner = crate::pr_head::owner_lock(home, &state.id)?;
13899    // An override must use current durable ownership, not a pre-lock snapshot.
13900    if override_recovery_retention {
13901        *state = RunState::load_under(&state.id, home)?;
13902        anyhow::ensure!(
13903            state.status.done() && !state.status.resumable(),
13904            "recovery retention override requires a finished, non-resumable run"
13905        );
13906        let claimed = crate::daemon::is_working_on_other(home, &state.id, Timestamp::now())?;
13907        anyhow::ensure!(
13908            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
13909            "run is live or its ownership is unknown"
13910        );
13911        anyhow::ensure!(
13912            state.candidate_preservation.is_empty() && state.interrupted_implementations.is_empty(),
13913            "candidate preservation incomplete; refusing cleanup"
13914        );
13915    }
13916    let retention_reason = crate::pr_recovery::source_retention_reason(home, state);
13917    if let Some(reason) = &retention_reason
13918        && !override_recovery_retention
13919    {
13920        bail!("refusing fold: {reason}");
13921    }
13922    let _driver = crate::driver::maintenance(home, &state.id)?;
13923    let mut output_guards = Vec::new();
13924    for entry in std::fs::read_dir(state.worktree_root())
13925        .into_iter()
13926        .flatten()
13927        .flatten()
13928    {
13929        if entry.path().join(".git").is_file() {
13930            output_guards.push(crate::retention::OutputLease::take(&entry.path(), true)?);
13931        }
13932    }
13933    let repo = state.repo.clone();
13934    // CLI, Web and automatic cleanup all enter here, independently of
13935    // Runner::fold_losers. Protect deletion and shared config release too.
13936    let wait = repository_wait(state, None);
13937    let _coordination = match coordinate_operation(state, &repo, &wait).await {
13938        Ok(lease) => lease,
13939        Err(e) => {
13940            state.save_under(home)?;
13941            return Err(e);
13942        }
13943    };
13944    // Confirmed merges dispose of their owned sources after durable evidence
13945    // capture. Preflight every source before removing anything.
13946    let _source_outputs = if retention_reason.is_some()
13947        || (state.status == RunStatus::Merged && state.merge.as_ref().is_some_and(|merge| merge.ok))
13948    {
13949        verify_merged_fold_sources(state, drop_winner, home).await?
13950    } else {
13951        Vec::new()
13952    };
13953    if let Some(reason) = retention_reason {
13954        state.event(
13955            "fold",
13956            format!(
13957                "operator CLI --override-recovery-retention authorized deletion for run {}: bypassed {reason}",
13958                state.id
13959            ),
13960        );
13961        state.save_under(home)?;
13962    }
13963    let root = state.worktree_root();
13964    let winner = state.tally.as_ref().map(|t| t.winner);
13965    let mut removed = Vec::new();
13966    let isolated = crate::build_target::isolated(&state.config);
13967
13968    for i in 0..state.candidates.len() {
13969        let c = state.candidates[i].clone();
13970        let is_winner = Some(c.label) == winner;
13971        if is_winner && !drop_winner {
13972            continue;
13973        }
13974        let existed = c.worktree.exists();
13975        let target = fold_target(home, &root, &c.worktree, isolated);
13976        // A vanished directory can still have a Git registration that keeps
13977        // its branch checked out. Remove that registration before the branch.
13978        remove_preserved_worktree(&repo, &c.worktree).await?;
13979        reclaim_fold_target(home, target);
13980        if existed {
13981            removed.push(c.worktree.to_string_lossy().into_owned());
13982        }
13983        // A branch handed to a later run (and its pull request) is not this
13984        // run's to delete.
13985        let handed_over = state.released_branches.contains(&c.branch);
13986        if !handed_over && git::branch_exists(&repo, &c.branch).await? {
13987            if !git::branch_delete(&repo, &c.branch).await? {
13988                bail!("candidate branch removal refused");
13989            }
13990            removed.push(c.branch.clone());
13991        }
13992        state.candidates[i].folded = true;
13993    }
13994
13995    for name in std::fs::read_dir(&root).into_iter().flatten().flatten() {
13996        let path = name.path();
13997        let keep = !drop_winner
13998            && winner.is_some_and(|w| {
13999                path.file_name()
14000                    .is_some_and(|n| n == format!("cand-{w}").as_str())
14001            });
14002        if keep {
14003            continue;
14004        }
14005        let target = fold_target(home, &root, &path, isolated);
14006        remove_read_seat_worktree(state, &path).await?;
14007        reclaim_fold_target(home, target);
14008        removed.push(path.to_string_lossy().into_owned());
14009    }
14010
14011    // `root` (`wt/<...>/<short>/`) held nothing but this run's candidate and
14012    // judge worktrees, so once the loop above has cleared all of them out,
14013    // the parent is a bare directory nobody else was ever going to remove -
14014    // git only ever managed what was inside it. Left alone, one of these
14015    // accumulates per fully-folded run; the operator's own machine had 74.
14016    // `remove_if_empty` re-checks rather than assuming: a run whose winner
14017    // was kept (`!drop_winner`) leaves its directory behind on purpose, and
14018    // so does anything a run never claimed that happens to share the bay.
14019    remove_if_empty(&root);
14020
14021    if state.enabled_worktree_config && drop_winner {
14022        // A release, not a raw disable: some sibling run in this repository
14023        // may still hold its own reference (see `git::acquire_worktree_config`),
14024        // and only the last release actually turns the setting back off.
14025        git::release_worktree_config(&repo).await.ok();
14026        state.enabled_worktree_config = false;
14027    }
14028    state.save_under(home)?;
14029    Ok(removed)
14030}
14031
14032async fn verify_merged_fold_sources(
14033    state: &RunState,
14034    drop_winner: bool,
14035    home: &Path,
14036) -> Result<Vec<std::fs::File>> {
14037    let winner = state.tally.as_ref().map(|t| t.winner);
14038    let mut heads = BTreeSet::new();
14039    for candidate in &state.candidates {
14040        if Some(candidate.label) == winner && !drop_winner {
14041            continue;
14042        }
14043        anyhow::ensure!(
14044            candidate.worktree.parent() == Some(state.worktree_root().as_path()),
14045            "candidate recovery source is outside the inventoried run root: {}",
14046            candidate.worktree.display()
14047        );
14048        match std::fs::symlink_metadata(&candidate.worktree) {
14049            Ok(_) => {}
14050            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
14051            Err(error) => return Err(error.into()),
14052        }
14053        if !state.released_branches.contains(&candidate.branch)
14054            && git::branch_exists(&state.repo, &candidate.branch).await?
14055        {
14056            heads.insert(git::rev_parse(&state.repo, &candidate.branch).await?);
14057        }
14058    }
14059    let mut cargo_guards = Vec::new();
14060    let entries = match std::fs::read_dir(state.worktree_root()) {
14061        Ok(entries) => Some(entries),
14062        Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
14063        Err(error) => return Err(error.into()),
14064    };
14065    for entry in entries.into_iter().flatten() {
14066        let path = entry?.path();
14067        let metadata = std::fs::symlink_metadata(&path)?;
14068        anyhow::ensure!(
14069            metadata.is_dir() && !metadata.file_type().is_symlink(),
14070            "non-directory or symlink recovery source retained: {}",
14071            path.display()
14072        );
14073        if !drop_winner
14074            && winner.is_some_and(|w| {
14075                path.file_name()
14076                    .is_some_and(|name| name == format!("cand-{w}").as_str())
14077            })
14078        {
14079            continue;
14080        }
14081        anyhow::ensure!(
14082            path.join(".git").is_file(),
14083            "unregistered recovery source retained: {}",
14084            path.display()
14085        );
14086        anyhow::ensure!(
14087            git::git(
14088                &path,
14089                &[
14090                    "status",
14091                    "--porcelain",
14092                    "--untracked-files=all",
14093                    "--ignored",
14094                    "--",
14095                    ".",
14096                    ":(exclude)target"
14097                ]
14098            )
14099            .await?
14100            .is_empty(),
14101            "source changes or ignored recovery files retained: {}",
14102            path.display()
14103        );
14104        match std::fs::symlink_metadata(path.join("target")) {
14105            Ok(_) => {
14106                cargo_guards.extend(crate::retention::verify_residue(home, &state.id, &path).await?)
14107            }
14108            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
14109            Err(error) => return Err(error.into()),
14110        }
14111        for checkpoint in [
14112            "rebase-merge",
14113            "rebase-apply",
14114            "sequencer",
14115            "CHERRY_PICK_HEAD",
14116            "MERGE_HEAD",
14117            "REBASE_HEAD",
14118            "REVERT_HEAD",
14119            "BISECT_LOG",
14120            "AUTO_MERGE",
14121            "MERGE_MSG",
14122        ] {
14123            let location = git::git(
14124                &path,
14125                &[
14126                    "rev-parse",
14127                    "--path-format=absolute",
14128                    "--git-path",
14129                    checkpoint,
14130                ],
14131            )
14132            .await?;
14133            anyhow::ensure!(
14134                matches!(std::fs::symlink_metadata(location.trim()), Err(ref e)
14135                if e.kind() == std::io::ErrorKind::NotFound),
14136                "Git recovery checkpoint retained: {checkpoint}"
14137            );
14138        }
14139        heads.insert(git::rev_parse(&path, "HEAD").await?);
14140    }
14141    crate::fold_evidence::preserve(state, home, &heads).await?;
14142
14143    Ok(cargo_guards)
14144}
14145
14146/// Remove `dir` if it exists and has nothing in it.
14147///
14148/// Best-effort and silent by design: a directory that is not empty (a run
14149/// whose winner is still parked there, a stray file some other process left)
14150/// is exactly the case this must refuse, and a directory that is already gone
14151/// is not a failure worth reporting either. `std::fs::remove_dir` itself
14152/// already refuses a non-empty directory, so the emptiness check below is
14153/// belt, not suspenders - it is what keeps this from ever attempting the
14154/// removal in the case that matters, rather than trusting `remove_dir`'s
14155/// error path to have no side effects if it ever changed.
14156fn remove_if_empty(dir: &Path) {
14157    if dir.is_dir() && std::fs::read_dir(dir).is_ok_and(|mut entries| entries.next().is_none()) {
14158        std::fs::remove_dir(dir).ok();
14159    }
14160}
14161
14162/// Severity of the worst open finding in the last review round, for reporting.
14163pub fn worst_open(state: &RunState) -> Option<Severity> {
14164    state
14165        .reviews
14166        .last()?
14167        .reviews
14168        .iter()
14169        .flat_map(|r| r.findings.iter())
14170        .map(|f| f.severity)
14171        .max()
14172}
14173
14174/// `[worktree] setup` hides its products per worktree, which needs
14175/// `extensions.worktreeConfig`. Taken once per run and released with the run's
14176/// worktrees, like the hook's; every place that runs setup calls this first.
14177async fn ensure_setup_config(state: &mut RunState, repo: &Path) -> Result<()> {
14178    if !state.config.worktree.setup.is_empty() && !state.enabled_worktree_config {
14179        git::acquire_worktree_config(repo).await?;
14180        state.enabled_worktree_config = true;
14181    }
14182    Ok(())
14183}
14184
14185#[cfg(test)]
14186mod tests {
14187    #[tokio::test]
14188    async fn launcher_base_fetch_requires_remote_success() {
14189        let tmp = tempfile::tempdir().unwrap();
14190        let repo = tmp.path().join("repo");
14191        let remote = tmp.path().join("remote");
14192        std::fs::create_dir(&repo).unwrap();
14193        std::fs::create_dir(&remote).unwrap();
14194        git::git(&remote, &["init", "--bare", "-b", "main"])
14195            .await
14196            .unwrap();
14197        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
14198        git::git(
14199            &repo,
14200            &[
14201                "-c",
14202                "user.name=Fixture",
14203                "-c",
14204                "user.email=fixture@example.invalid",
14205                "commit",
14206                "--allow-empty",
14207                "-m",
14208                "fixture",
14209            ],
14210        )
14211        .await
14212        .unwrap();
14213        git::git(
14214            &repo,
14215            &["remote", "add", "origin", remote.to_str().unwrap()],
14216        )
14217        .await
14218        .unwrap();
14219        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
14220        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
14221        assert_eq!(
14222            resolve_base(&repo, "main", "origin", None)
14223                .await
14224                .unwrap()
14225                .commit,
14226            head
14227        );
14228        #[cfg(unix)]
14229        {
14230            let policy: crate::config::Coordination = toml::from_str(
14231                "contract_file='fixture.contract'\ncontract_token='fixture-v1'\nlock_file='fixture.lock'",
14232            ).unwrap();
14233            std::fs::write(repo.join(".git/fixture.contract"), "fixture-v1").unwrap();
14234            std::fs::remove_file(repo.join(".git/FETCH_HEAD")).unwrap();
14235            let held = crate::repo_lock::SeatLease::operation_with(
14236                &repo,
14237                Some(&policy),
14238                &crate::repo_lock::WaitPolicy::default(),
14239            )
14240            .await
14241            .unwrap();
14242            assert!(held.is_some());
14243            let fetch = resolve_base(&repo, "main", "origin", Some(&policy));
14244            tokio::pin!(fetch);
14245            assert!(
14246                tokio::time::timeout(Duration::from_millis(50), &mut fetch)
14247                    .await
14248                    .is_err()
14249            );
14250            assert!(
14251                !repo.join(".git/FETCH_HEAD").exists(),
14252                "no fetch before admission"
14253            );
14254            drop(held);
14255            let fetched = fetch.await.unwrap();
14256            assert_eq!(fetched.commit, head);
14257            assert_eq!(fetched.remote, "origin");
14258            assert_eq!(fetched.branch, "main");
14259        }
14260        // A surviving tracking ref is not successful fetch evidence.
14261        git::git(
14262            &repo,
14263            &[
14264                "remote",
14265                "set-url",
14266                "origin",
14267                tmp.path().join("missing").to_str().unwrap(),
14268            ],
14269        )
14270        .await
14271        .unwrap();
14272        let error = resolve_base(&repo, "main", "origin", None)
14273            .await
14274            .unwrap_err()
14275            .to_string();
14276        assert!(error.contains("cannot read origin/main"));
14277        assert!(error.contains("refusing to branch off"));
14278    }
14279
14280    #[test]
14281    fn should_retitle_only_replaces_magi_shaped_or_leaked_titles() {
14282        let leaked = vec!["chore(deps): update a crate".to_owned()];
14283        let own = "fix(daemon): apply a chosen action";
14284        assert!(should_retitle("", own, &leaked));
14285        assert!(should_retitle(
14286            &format!("{REVIEW_PROMPT_OPENING} `x`"),
14287            own,
14288            &leaked
14289        ));
14290        assert!(should_retitle(
14291            "chore: land candidate A of run 1",
14292            own,
14293            &leaked
14294        ));
14295        assert!(should_retitle(
14296            "magi: candidate A (uncommitted work)",
14297            own,
14298            &leaked
14299        ));
14300        assert!(should_retitle("chore(deps): update a crate", own, &leaked));
14301        assert!(!should_retitle("feat: renamed by hand", own, &leaked));
14302        assert!(!should_retitle("", "chore(deps): update a crate", &leaked));
14303    }
14304
14305    #[test]
14306    fn pr_merge_plan_creates_adopts_or_stops() {
14307        assert_eq!(pr_merge_plan(Ok(land::OpenPr::None)), PrPlan::Create);
14308        assert_eq!(
14309            pr_merge_plan(Ok(land::OpenPr::One {
14310                url: "u".into(),
14311                title: "t".into()
14312            })),
14313            PrPlan::Adopt {
14314                url: "u".into(),
14315                title: "t".into()
14316            }
14317        );
14318        let PrPlan::Stop(many) =
14319            pr_merge_plan(Ok(land::OpenPr::Many(vec!["a".into(), "b".into()])))
14320        else {
14321            panic!("many must stop");
14322        };
14323        assert!(many.contains('a') && many.contains('b'));
14324        let PrPlan::Stop(err) = pr_merge_plan(Err(anyhow::anyhow!("bad token"))) else {
14325            panic!("a failed lookup must stop");
14326        };
14327        assert!(err.contains("bad token"));
14328    }
14329
14330    use super::*;
14331    use crate::run::GateStatus;
14332    use std::collections::BTreeMap;
14333    use std::time::Duration;
14334
14335    fn conductor() -> AgentSpec {
14336        AgentSpec {
14337            id: "conductor".to_owned(),
14338            kind: crate::config::AgentKind::Command,
14339            model: None,
14340            command: vec!["true".to_owned()],
14341            extra_args: Vec::new(),
14342            env: BTreeMap::new(),
14343            prompt_delivery: None,
14344            max_turn_secs: None,
14345        }
14346    }
14347
14348    fn spec(id: &str) -> AgentSpec {
14349        AgentSpec {
14350            id: id.to_owned(),
14351            kind: crate::config::AgentKind::Command,
14352            model: None,
14353            command: vec!["true".to_owned()],
14354            extra_args: Vec::new(),
14355            env: BTreeMap::new(),
14356            prompt_delivery: None,
14357            max_turn_secs: None,
14358        }
14359    }
14360
14361    fn ids(xs: &[&str]) -> BTreeSet<String> {
14362        xs.iter().map(|s| (*s).to_owned()).collect()
14363    }
14364
14365    #[test]
14366    fn pick_successor_skips_an_agent_another_seat_holds() {
14367        // Seats a and b of roster [a, b, c]; a fails, b holds the other seat.
14368        let roster = [spec("a"), spec("b"), spec("c")];
14369        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
14370        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
14371    }
14372
14373    #[test]
14374    fn pick_successor_respects_the_occupant_after_an_earlier_handover() {
14375        // The other seat started on c but was handed to d; c is free again.
14376        let roster = [spec("a"), spec("b"), spec("c"), spec("d")];
14377        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
14378        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
14379        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b", "c"]));
14380        assert_eq!(next.map(|s| s.id.as_str()), Some("d"));
14381    }
14382
14383    #[test]
14384    fn pick_successor_falls_back_to_a_duplicate_when_no_distinct_agent_remains() {
14385        let roster = [spec("a"), spec("b")];
14386        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
14387        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14388        let carried = ids(&["b"]);
14389        let next = pick_successor(&roster, 0, &ids(&["a"]), Some(&carried), &ids(&["b"]));
14390        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14391    }
14392
14393    #[test]
14394    fn pick_successor_returns_none_without_any_untried_successor() {
14395        let roster = [spec("a"), spec("b")];
14396        assert!(pick_successor(&roster, 1, &ids(&["b"]), None, &ids(&["a"])).is_none());
14397        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), None, &ids(&[])).is_none());
14398        let carried = ids(&["a"]);
14399        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), Some(&carried), &ids(&[])).is_none());
14400    }
14401
14402    #[test]
14403    fn pick_successor_rescue_avoids_another_seats_occupant() {
14404        // b is a carried failure and free; a is held by the other seat.
14405        let roster = [spec("a"), spec("b"), spec("c")];
14406        let carried = ids(&["b", "c"]);
14407        let next = pick_successor(&roster, 2, &ids(&["c"]), Some(&carried), &ids(&["a"]));
14408        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14409    }
14410
14411    #[test]
14412    fn next_for_seat_prefers_an_agent_that_has_not_failed() {
14413        let roster = [spec("a"), spec("b"), spec("c")];
14414        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["b"]));
14415        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
14416    }
14417
14418    #[test]
14419    fn next_for_seat_rescues_a_failed_agent_only_when_nothing_else_is_left() {
14420        let roster = [spec("a"), spec("b"), spec("c")];
14421        let failed = ids(&["a", "b", "c"]);
14422        // Rescue looks at the whole roster, once per id, then runs out.
14423        let mut tried = ids(&["b"]);
14424        let first = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
14425        assert_eq!(first.id, "a");
14426        tried.insert(first.id.clone());
14427        let second = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
14428        assert_eq!(second.id, "c");
14429        tried.insert(second.id.clone());
14430        assert!(next_for_seat(&roster, 1, &tried, &failed).is_none());
14431    }
14432
14433    #[test]
14434    fn next_for_seat_ignores_failed_ids_no_longer_on_the_roster() {
14435        let roster = [spec("a"), spec("b")];
14436        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["gone"]));
14437        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14438    }
14439
14440    #[test]
14441    fn pick_start_spec_starts_on_the_last_answerer_when_still_eligible() {
14442        let roster = [spec("a"), spec("b"), spec("c")];
14443        let h = SeatHistory {
14444            failed: ids(&["a"]),
14445            last_ok: Some("b".to_owned()),
14446            last_fail: None,
14447        };
14448        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&h)).id, "b");
14449        // A last answerer that left the roster, or later failed, is ignored.
14450        let gone = SeatHistory {
14451            last_ok: Some("zzz".to_owned()),
14452            ..h.clone()
14453        };
14454        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&gone)).id, "b");
14455        let failed = SeatHistory {
14456            failed: ids(&["a", "b"]),
14457            last_ok: Some("b".to_owned()),
14458            last_fail: None,
14459        };
14460        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&failed)).id, "c");
14461    }
14462
14463    #[test]
14464    fn handover_seat_mints_a_session_id_distinct_from_the_previous_agents() {
14465        let first = SeatState::new("review-1", "alpha", 7);
14466        let next = handover_seat("review-1", "gamma", 7);
14467        assert_ne!(first.claude_session, next.claude_session);
14468    }
14469
14470    #[test]
14471    fn re_handing_a_seat_to_the_same_agent_mints_a_new_session_id() {
14472        let mut state = state_with_summary("x", "y");
14473        let a = handover_seat("review-1", "beta", state.next_seat_seed());
14474        let b = handover_seat("review-1", "beta", state.next_seat_seed());
14475        assert_ne!(a.claude_session, b.claude_session);
14476    }
14477
14478    #[test]
14479    fn pick_start_spec_falls_back_to_the_spec_when_the_whole_roster_failed() {
14480        let roster = [spec("a"), spec("b")];
14481        let h = SeatHistory {
14482            failed: ids(&["a", "b"]),
14483            ..SeatHistory::default()
14484        };
14485        assert_eq!(pick_start_spec(&roster, spec("b"), Some(&h)).id, "b");
14486        assert_eq!(pick_start_spec(&roster, spec("b"), None).id, "b");
14487        assert_eq!(pick_start_spec(&[], spec("b"), Some(&h)).id, "b");
14488    }
14489
14490    // `next_untried_in_roster` is the property `resume_seat_handovers`'s own
14491    // fallback loop depends on to terminate: it must walk forward from the
14492    // seat's own position, never restart at the front of the roster, and it
14493    // must never hand back an id already tried, however many times that id
14494    // happens to appear.
14495
14496    #[test]
14497    fn failure_signature_ignores_numbers_and_paths() {
14498        assert_eq!(
14499            failure_signature("exited with Some(2) and no usable output"),
14500            failure_signature("exited with Some(137) and no usable output")
14501        );
14502        assert_eq!(
14503            failure_signature("process exited with no usable output (exit code 2)"),
14504            failure_signature("process exited with no usable output (exit code 137)")
14505        );
14506        for (old, new) in [
14507            (
14508                "exited with Some(2) and no usable output",
14509                "process exited with no usable output (exit code 2)",
14510            ),
14511            (
14512                "exited with None and no usable output",
14513                "process exited with no usable output (exit code unavailable)",
14514            ),
14515        ] {
14516            let previous = FailClass::Other(failure_signature(old));
14517            let current = FailClass::Other(failure_signature(new));
14518            assert_eq!(previous, current, "resumption retains the failure class");
14519            assert!(!should_hand_over(Some(&previous), &current));
14520        }
14521        assert_eq!(
14522            failure_signature("cannot open /tmp/a/b.txt: denied\nsecond line"),
14523            failure_signature("cannot open /var/x.txt: denied")
14524        );
14525        assert_ne!(failure_signature("boom"), failure_signature("bang"));
14526    }
14527
14528    #[test]
14529    fn quota_and_timeout_always_hand_over_other_failures_stop_on_a_repeat() {
14530        let other = FailClass::Other("x".into());
14531        assert!(should_hand_over(None, &FailClass::Quota));
14532        assert!(should_hand_over(Some(&other), &FailClass::Quota));
14533        assert!(should_hand_over(
14534            Some(&FailClass::Timeout),
14535            &FailClass::Timeout
14536        ));
14537        assert!(should_hand_over(None, &other));
14538        assert!(!should_hand_over(Some(&other), &other));
14539        assert!(should_hand_over(
14540            Some(&other),
14541            &FailClass::Other("y".into())
14542        ));
14543        // A quota or timeout in between ends the run of identical failures.
14544        assert!(should_hand_over(Some(&FailClass::Timeout), &other));
14545        assert!(should_hand_over(Some(&FailClass::Quota), &other));
14546    }
14547
14548    #[test]
14549    fn a_handover_seat_never_reuses_the_previous_agents_session_id() {
14550        let a = SeatState::new("judge-1", "alpha", 7);
14551        let b = handover_seat("judge-1", "beta", 7);
14552        assert_ne!(a.claude_session, b.claude_session);
14553        assert_eq!(b.turns, 0);
14554    }
14555
14556    #[test]
14557    fn a_timeout_is_classified_apart_from_other_failures() {
14558        assert_eq!(
14559            FailClass::of(&AgentOutcome::Failed(TIMED_OUT.to_owned())),
14560            Some(FailClass::Timeout)
14561        );
14562        assert!(matches!(
14563            FailClass::of(&AgentOutcome::Failed("boom".to_owned())),
14564            Some(FailClass::Other(_))
14565        ));
14566    }
14567
14568    #[test]
14569    fn next_untried_in_roster_walks_forward_from_the_seats_own_position() {
14570        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
14571        let tried = BTreeSet::from(["beta".to_owned()]);
14572        // beta sits at index 1; the next candidate is gamma, never alpha —
14573        // which is very likely a different candidate slot's own agent.
14574        let next = next_untried_in_roster(&roster, 1, &tried);
14575        assert_eq!(next.map(|s| s.id.as_str()), Some("gamma"));
14576    }
14577
14578    #[test]
14579    fn next_untried_in_roster_does_not_wrap_back_past_its_own_start() {
14580        let roster = vec![spec("alpha"), spec("beta")];
14581        let tried = BTreeSet::from(["beta".to_owned()]);
14582        // beta is the roster's last entry: nothing follows it, and alpha —
14583        // earlier in the roster, almost certainly a different candidate
14584        // slot's own agent — must not be reached by wrapping back to it.
14585        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
14586    }
14587
14588    #[test]
14589    fn next_untried_in_roster_stops_once_the_tail_is_exhausted_even_if_earlier_ids_are_untried() {
14590        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
14591        let tried = BTreeSet::from(["beta".to_owned(), "gamma".to_owned()]);
14592        // beta (index 1) and gamma (index 2, the only entry after it) have
14593        // both been tried; alpha (index 0) never has, but it comes before
14594        // beta's own position, so there is nothing further for this seat.
14595        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
14596    }
14597
14598    #[test]
14599    fn next_untried_in_roster_skips_ids_already_tried_even_when_duplicated() {
14600        let roster = vec![spec("a"), spec("a"), spec("b")];
14601        let tried = BTreeSet::from(["a".to_owned()]);
14602        let next = next_untried_in_roster(&roster, 0, &tried);
14603        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14604    }
14605
14606    #[test]
14607    fn next_untried_in_roster_returns_none_once_every_id_is_tried() {
14608        let roster = vec![spec("a"), spec("b")];
14609        let tried = BTreeSet::from(["a".to_owned(), "b".to_owned()]);
14610        assert!(next_untried_in_roster(&roster, 0, &tried).is_none());
14611    }
14612
14613    #[test]
14614    fn remove_if_empty_only_ever_takes_a_bare_directory() {
14615        let dir = tempfile::tempdir().unwrap();
14616        let bay = dir.path().join("ffff");
14617
14618        // Not there yet: nothing to do, nothing to panic on.
14619        remove_if_empty(&bay);
14620        assert!(!bay.exists());
14621
14622        // Something still inside - the winner's worktree, or a stray file -
14623        // keeps the directory standing.
14624        std::fs::create_dir_all(bay.join("cand-A")).unwrap();
14625        remove_if_empty(&bay);
14626        assert!(bay.exists(), "non-empty directory must survive");
14627
14628        // Once the last entry is gone, so is the directory itself.
14629        std::fs::remove_dir(bay.join("cand-A")).unwrap();
14630        remove_if_empty(&bay);
14631        assert!(!bay.exists(), "an empty bay is a leftover, not a record");
14632    }
14633
14634    // `round_is_clean` is the exact decision this task fixed: a round with a
14635    // seat that never answered must not read the same as a round every seat
14636    // actually reviewed. These are deterministic and process-free by design —
14637    // the equivalent end-to-end check (a real reviewer timing out under a
14638    // live graph run) is a genuine race against wall-clock contention, and a
14639    // spawn slow enough to blow even a generous budget under a loaded test
14640    // run must not turn this specific regression check flaky.
14641
14642    #[test]
14643    fn a_full_panel_that_found_nothing_is_clean() {
14644        assert!(round_is_clean(
14645            0,
14646            true,
14647            2,
14648            2,
14649            0,
14650            IncompleteReviewPolicy::Block
14651        ));
14652    }
14653
14654    #[test]
14655    fn a_missing_seat_is_never_clean_under_the_default_policy() {
14656        assert!(!round_is_clean(
14657            0,
14658            true,
14659            1,
14660            2,
14661            0,
14662            IncompleteReviewPolicy::Block
14663        ));
14664    }
14665
14666    #[test]
14667    fn warn_policy_still_refuses_a_missing_seat_with_open_findings() {
14668        assert!(!round_is_clean(
14669            1,
14670            true,
14671            1,
14672            2,
14673            0,
14674            IncompleteReviewPolicy::Warn
14675        ));
14676    }
14677
14678    #[test]
14679    fn warn_policy_gates_a_missing_seat_once_what_answered_is_clean() {
14680        assert!(round_is_clean(
14681            0,
14682            true,
14683            1,
14684            2,
14685            0,
14686            IncompleteReviewPolicy::Warn
14687        ));
14688    }
14689
14690    #[test]
14691    fn a_full_panel_with_an_open_finding_is_not_clean() {
14692        assert!(!round_is_clean(
14693            1,
14694            true,
14695            2,
14696            2,
14697            0,
14698            IncompleteReviewPolicy::Block
14699        ));
14700    }
14701
14702    #[test]
14703    fn a_full_panel_with_a_red_e2e_is_not_clean() {
14704        assert!(!round_is_clean(
14705            0,
14706            false,
14707            2,
14708            2,
14709            0,
14710            IncompleteReviewPolicy::Block
14711        ));
14712    }
14713
14714    // The stall this task closes: under the default `block` policy, a seat
14715    // missing only because it was rate limited must not force a wait for a
14716    // session limit that will not lift by the next round. `round_is_clean`
14717    // is where that quorum carve-out lives; the review loop around it never
14718    // changes what a reviewer's vote or a finding's severity means.
14719
14720    #[test]
14721    fn a_seat_missing_only_to_its_own_quota_is_clean_under_the_default_policy() {
14722        // 1 of 2 answered, and the one missing was quota'd — the exact
14723        // "review-2 rate limited (quota)" shape from the field report.
14724        assert!(round_is_clean(
14725            0,
14726            true,
14727            1,
14728            2,
14729            1,
14730            IncompleteReviewPolicy::Block
14731        ));
14732    }
14733
14734    #[test]
14735    fn a_seat_missing_for_a_reason_other_than_quota_still_waits() {
14736        // 1 of 2 answered, but the miss was a crash/timeout/parse failure,
14737        // not a quota loss (`quota_missing` stays 0) — worth another try.
14738        assert!(!round_is_clean(
14739            0,
14740            true,
14741            1,
14742            2,
14743            0,
14744            IncompleteReviewPolicy::Block
14745        ));
14746    }
14747
14748    #[test]
14749    fn a_quota_loss_does_not_excuse_an_open_finding_or_a_red_e2e() {
14750        assert!(!round_is_clean(
14751            1,
14752            true,
14753            1,
14754            2,
14755            1,
14756            IncompleteReviewPolicy::Block
14757        ));
14758        assert!(!round_is_clean(
14759            0,
14760            false,
14761            1,
14762            2,
14763            1,
14764            IncompleteReviewPolicy::Block
14765        ));
14766    }
14767
14768    #[test]
14769    fn a_panel_lost_entirely_to_quota_still_waits_rather_than_deciding_on_nobody() {
14770        // Every seat quota'd, nobody answered: there is no panel to decide
14771        // on, so this must fall through to the existing block-and-retry
14772        // fallback rather than call an unreviewed patch clean.
14773        assert!(!round_is_clean(
14774            0,
14775            true,
14776            0,
14777            2,
14778            2,
14779            IncompleteReviewPolicy::Block
14780        ));
14781    }
14782
14783    fn outcome(code: Option<i32>, resource_blocked: bool) -> CommandOutcome {
14784        CommandOutcome {
14785            command: "test".to_owned(),
14786            code,
14787            output_tail: String::new(),
14788            duration_ms: 0,
14789            resource_blocked,
14790        }
14791    }
14792
14793    #[cfg(unix)]
14794    #[tokio::test]
14795    async fn incremental_admission_is_a_resource_hold_without_a_build_retry() {
14796        ask_test_home();
14797        let temp = tempfile::tempdir().unwrap();
14798        let mut runner = runner_at(RunStatus::Gating);
14799        let shell = vec!["sh".to_owned(), "-c".to_owned()];
14800        let commands = vec![
14801            "printf '%s\\n' 'incremental cache admission blocked: budget exhausted' 'error: could not compile fixture'; exit 101".to_owned(),
14802            "touch must-not-run".to_owned(),
14803        ];
14804        let (outcomes, retried, pids) = run_e2e_with_retry(
14805            &mut runner.state,
14806            &shell,
14807            &commands,
14808            temp.path(),
14809            Duration::from_secs(5),
14810            "fixture",
14811            None,
14812        )
14813        .await;
14814        assert_eq!(outcomes.len(), 1);
14815        assert!(outcomes[0].resource_blocked);
14816        assert!(!outcomes[0].build_failed());
14817        assert!(!retried);
14818        assert!(pids.is_empty());
14819        assert!(!temp.path().join("must-not-run").exists());
14820        assert_eq!(
14821            runner.state.resource_block.as_ref().unwrap().kind,
14822            "incremental cache admission"
14823        );
14824    }
14825
14826    #[test]
14827    fn verify_is_inconclusive_only_when_a_resource_blocked_outcome_is_present() {
14828        assert!(!verify_inconclusive(&[outcome(Some(0), false)]));
14829        assert!(
14830            !verify_inconclusive(&[outcome(Some(1), false)]),
14831            "an ordinary failure is still evidence about the patch"
14832        );
14833        assert!(verify_inconclusive(&[outcome(None, true)]));
14834        assert!(
14835            verify_inconclusive(&[outcome(Some(0), false), outcome(None, true)]),
14836            "one inconclusive outcome taints the whole batch"
14837        );
14838        assert!(!verify_inconclusive(&[]));
14839    }
14840
14841    #[tokio::test]
14842    async fn timed_out_pid_waiting_returns_as_soon_as_every_pid_is_confirmed_dead() {
14843        // Alive for the first two checks, then dead - confirms the loop
14844        // actually re-polls rather than deciding once and sleeping out the
14845        // ceiling regardless.
14846        let calls = std::sync::atomic::AtomicUsize::new(0);
14847        let started = Instant::now();
14848        wait_for_pids_with(
14849            &[123],
14850            |_| calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 2,
14851            Duration::from_millis(5),
14852            Duration::from_secs(5),
14853        )
14854        .await;
14855        assert!(
14856            calls.load(std::sync::atomic::Ordering::SeqCst) >= 3,
14857            "must keep checking rather than deciding on the first answer"
14858        );
14859        assert!(
14860            started.elapsed() < Duration::from_secs(1),
14861            "must return the moment it is confirmed dead, not wait out the ceiling"
14862        );
14863    }
14864
14865    #[tokio::test]
14866    async fn timed_out_pid_waiting_gives_up_at_its_ceiling_if_never_confirmed_dead() {
14867        let started = Instant::now();
14868        wait_for_pids_with(
14869            &[123],
14870            |_| true, // never reports dead
14871            Duration::from_millis(5),
14872            Duration::from_millis(30),
14873        )
14874        .await;
14875        let elapsed = started.elapsed();
14876        assert!(
14877            elapsed >= Duration::from_millis(30),
14878            "must not give up before its own ceiling: {elapsed:?}"
14879        );
14880        assert!(
14881            elapsed < Duration::from_secs(1),
14882            "must not wait past its own ceiling either: {elapsed:?}"
14883        );
14884    }
14885
14886    #[tokio::test]
14887    async fn timed_out_pid_waiting_is_a_no_op_when_nothing_was_still_running() {
14888        let started = Instant::now();
14889        wait_for_pids_with(
14890            &[],
14891            |_| true,
14892            Duration::from_secs(5),
14893            Duration::from_secs(5),
14894        )
14895        .await;
14896        assert!(
14897            started.elapsed() < Duration::from_millis(200),
14898            "an empty pid list has nothing to confirm"
14899        );
14900    }
14901
14902    // `review_conclusion` is the exact decision the review hand-off task
14903    // fixed: a round budget spent (or a tree that stopped moving) must not
14904    // collapse into `Blocked` regardless of what verification actually
14905    // said. Deterministic and process-free for the same reason the
14906    // `round_is_clean` family above is.
14907    fn review_round(
14908        clean: bool,
14909        blocking: usize,
14910        answered: usize,
14911        expected: usize,
14912        progressed: bool,
14913        e2e_ok: bool,
14914    ) -> ReviewRound {
14915        ReviewRound {
14916            round: 1,
14917            head: "h".to_owned(),
14918            verified_head: None,
14919            verified_at: None,
14920            reviews: Vec::new(),
14921            e2e: vec![CommandOutcome {
14922                command: "test".to_owned(),
14923                code: Some(if e2e_ok { 0 } else { 1 }),
14924                output_tail: String::new(),
14925                duration_ms: 0,
14926                resource_blocked: false,
14927            }],
14928            verify_retried: false,
14929            e2e_deferred: false,
14930            e2e_defer_reason: None,
14931            fix: None,
14932            blocking,
14933            answered,
14934            expected,
14935            clean,
14936            progressed,
14937            vote_split: false,
14938            reconsideration: Vec::new(),
14939            verdict: None,
14940        }
14941    }
14942
14943    #[test]
14944    fn review_conclusion_is_none_when_nothing_has_run() {
14945        assert_eq!(review_conclusion(&[], 3), None);
14946    }
14947
14948    #[test]
14949    fn review_conclusion_is_none_while_rounds_remain() {
14950        let rounds = vec![review_round(false, 1, 2, 2, true, true)];
14951        assert_eq!(review_conclusion(&rounds, 3), None);
14952    }
14953
14954    #[test]
14955    fn review_conclusion_is_gating_once_a_round_is_clean() {
14956        let rounds = vec![review_round(true, 0, 2, 2, false, true)];
14957        assert_eq!(review_conclusion(&rounds, 3), Some(RunStatus::Gating));
14958    }
14959
14960    #[test]
14961    fn review_conclusion_hands_off_when_the_budget_is_spent_and_e2e_is_green() {
14962        let rounds = vec![
14963            review_round(false, 1, 2, 2, true, true),
14964            review_round(false, 1, 2, 2, true, true),
14965        ];
14966        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Gating));
14967    }
14968
14969    #[test]
14970    fn review_conclusion_blocks_when_the_budget_is_spent_and_e2e_is_red() {
14971        let rounds = vec![
14972            review_round(false, 1, 2, 2, true, true),
14973            review_round(false, 1, 2, 2, true, false),
14974        ];
14975        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Blocked));
14976    }
14977
14978    #[test]
14979    fn review_conclusion_stays_none_when_the_budget_is_spent_but_the_last_round_could_not_run() {
14980        // Magi never got a command to run against this round's own head — a
14981        // resource-blocked attempt, not a red one — so this must never
14982        // settle on `Blocked` the way a genuine e2e failure would. `None`
14983        // here is what tells `Runner::review_loop` to retry the check
14984        // itself rather than trust this cheap recomputation with a verdict
14985        // it cannot actually produce.
14986        let mut blocked = review_round(false, 1, 2, 2, true, false);
14987        blocked.e2e[0].resource_blocked = true;
14988        let rounds = vec![review_round(false, 1, 2, 2, true, true), blocked];
14989        assert_eq!(review_conclusion(&rounds, 2), None);
14990    }
14991
14992    #[test]
14993    fn review_conclusion_blocks_an_incomplete_panel_that_raised_nothing_even_with_green_e2e() {
14994        // Missing input, not a verified tree — never a hand-off candidate.
14995        let rounds = vec![review_round(false, 0, 1, 2, false, true)];
14996        assert_eq!(review_conclusion(&rounds, 1), Some(RunStatus::Blocked));
14997    }
14998
14999    #[test]
15000    fn review_conclusion_hands_off_when_the_tree_stagnates_before_the_budget_is_spent() {
15001        let rounds = vec![
15002            review_round(false, 1, 2, 2, false, true),
15003            review_round(false, 1, 2, 2, false, true),
15004        ];
15005        assert_eq!(review_conclusion(&rounds, 10), Some(RunStatus::Gating));
15006    }
15007
15008    fn secs(n: u64) -> Duration {
15009        Duration::from_secs(n)
15010    }
15011
15012    /// A throwaway repo with one commit on `main`, for tests that need `merge`
15013    /// to make real (and, if it runs at all, real*ly fail*) git calls.
15014    #[tokio::test]
15015    async fn selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync() {
15016        const CHILD: &str = "MAGI_SELECTED_PUBLIC_ANCESTRY_TEST";
15017        if std::env::var_os(CHILD).is_none() {
15018            // Other tests reconcile every run in the process-global home,
15019            // briefly taking owner locks. This ancestry test expects an idle
15020            // predecessor, so give it its own process and pinned test home.
15021            let output = std::process::Command::new(std::env::current_exe().unwrap())
15022                .args([
15023                    "--exact",
15024                    "graph::tests::selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync",
15025                    "--nocapture",
15026                ])
15027                .env(CHILD, "1")
15028                .env_remove("MAGI_WORKER_HOME")
15029                .env_remove("MAGI_WORKER_ID")
15030                .output()
15031                .unwrap();
15032            assert!(
15033                output.status.success()
15034                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
15035                "{}\n{}",
15036                String::from_utf8_lossy(&output.stdout),
15037                String::from_utf8_lossy(&output.stderr)
15038            );
15039            return;
15040        }
15041        ask_test_home();
15042        let tmp = tempfile::tempdir().unwrap();
15043        let repo = tmp.path().join("repo");
15044        std::fs::create_dir_all(&repo).unwrap();
15045        init_repo(&repo);
15046        let g = |args: &[&str]| {
15047            let out = std::process::Command::new("git")
15048                .args(args)
15049                .current_dir(&repo)
15050                .quiet()
15051                .output()
15052                .unwrap();
15053            assert!(
15054                out.status.success(),
15055                "{}",
15056                String::from_utf8_lossy(&out.stderr)
15057            );
15058        };
15059        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
15060        g(&["checkout", "-b", "historical"]);
15061        std::fs::write(repo.join("implementation"), "incompatible alternative").unwrap();
15062        g(&["add", "."]);
15063        g(&["commit", "-m", "old alternative"]);
15064        let obsolete = git::rev_parse(&repo, "HEAD").await.unwrap();
15065        g(&["checkout", "-b", "magi/task-selected", &base]);
15066        std::fs::write(repo.join("infrastructure"), "prerequisite").unwrap();
15067        g(&["add", "."]);
15068        g(&["commit", "-m", "measurement infrastructure"]);
15069        let prerequisite = git::rev_parse(&repo, "HEAD").await.unwrap();
15070        std::fs::write(repo.join("implementation"), "measured implementation").unwrap();
15071        g(&["add", "."]);
15072        g(&["commit", "-m", "dependent implementation"]);
15073        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
15074        g(&["checkout", "main"]);
15075        std::fs::write(repo.join("unrelated"), "current main change").unwrap();
15076        g(&["add", "."]);
15077        g(&["commit", "-m", "unrelated base change"]);
15078        let current = git::rev_parse(&repo, "HEAD").await.unwrap();
15079        let origin = tmp.path().join("origin.git");
15080        g(&[
15081            "clone",
15082            "--bare",
15083            repo.to_str().unwrap(),
15084            origin.to_str().unwrap(),
15085        ]);
15086        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
15087        g(&["fetch", "origin"]);
15088        let selection = crate::pr_recovery::Selection {
15089            url: "https://example.test/project/pull/1".into(),
15090            branch: "magi/task-selected".into(),
15091            head: head.clone(),
15092            source_head: None,
15093            source_run: None,
15094            source_proof: None,
15095            disposition: Some(crate::pr_recovery::Disposition::Review),
15096            instruction: "preserve measured behavior".into(),
15097            approved_at: jiff::Timestamp::now(),
15098        };
15099        let mut template = runner_at(RunStatus::Reviewing);
15100        template.state.repo = repo.clone();
15101        template.state.base_commit = current.clone();
15102        template.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
15103        template.state.origin = Some(crate::run::Origin::queue("selected"));
15104        template.state.pr_head = Some(selection.branch.clone());
15105        template.state.pr_recovery = Some(selection.clone());
15106        let mut runner =
15107            Runner::open_selected(&repo, template.state, template.roles, 1, current, selection)
15108                .await
15109                .unwrap();
15110        let wt = runner.state.winner().unwrap().worktree.clone();
15111        assert_eq!(git::rev_parse(&wt, "HEAD").await.unwrap(), head);
15112        assert!(git::is_ancestor(&wt, &prerequisite, "HEAD").await);
15113        assert!(!git::is_ancestor(&wt, &obsolete, "HEAD").await);
15114        assert!(runner.state.seeds.is_empty());
15115        assert_eq!(runner.state.instruction, "preserve measured behavior");
15116        runner.sync_to_base().await.unwrap();
15117        assert_eq!(
15118            std::fs::read_to_string(wt.join("infrastructure")).unwrap(),
15119            "prerequisite"
15120        );
15121        assert_eq!(
15122            std::fs::read_to_string(wt.join("implementation")).unwrap(),
15123            "measured implementation"
15124        );
15125        assert_eq!(
15126            std::fs::read_to_string(wt.join("unrelated")).unwrap(),
15127            "current main change"
15128        );
15129        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
15130        assert_eq!(
15131            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
15132            head
15133        );
15134
15135        // A failed selected-source setup stays inspectable, never resumable as a new competition.
15136        let mut partial = runner_at(RunStatus::Reviewing);
15137        partial.state.repo = repo.clone();
15138        partial.state.config.graph.worktree_root = Some(tmp.path().join("failed-worktrees"));
15139        partial.state.config.worktree.setup = vec![crate::config::SetupStep {
15140            run: Some("exit 1".into()),
15141            ..Default::default()
15142        }];
15143        let selection = runner.state.pr_recovery.clone().unwrap();
15144        partial.state.pr_recovery = Some(selection.clone());
15145        partial.state.pr_head = Some(selection.branch.clone());
15146        partial.state.origin = Some(crate::run::Origin::queue("selected"));
15147        let id = partial.state.id.clone();
15148        let error = match Runner::open_selected(
15149            &repo,
15150            partial.state,
15151            partial.roles,
15152            1,
15153            runner.state.base_commit.clone(),
15154            selection,
15155        )
15156        .await
15157        {
15158            Ok(_) => panic!("setup must fail"),
15159            Err(e) => e,
15160        };
15161        assert_eq!(
15162            error
15163                .downcast_ref::<crate::run::StartupFailure>()
15164                .unwrap()
15165                .run,
15166            id
15167        );
15168        let failed = RunState::load(&id).unwrap();
15169        assert_eq!(failed.status, RunStatus::Failed);
15170        assert_eq!(failed.liveness(false), crate::run::Liveness::Dead);
15171        assert!(Runner::resume(&id).is_err());
15172        runner.state.status = RunStatus::Ready;
15173        runner.state.driver_exited = true;
15174        runner.state.save().unwrap();
15175        let mut retry = runner_at(RunStatus::Reviewing);
15176        retry.state.repo = repo.clone();
15177        retry.state.config.graph.worktree_root = Some(tmp.path().join("retry-worktrees"));
15178        let mut reselected = runner.state.pr_recovery.clone().unwrap();
15179        reselected.approved_at = jiff::Timestamp::now();
15180        retry.state.origin = Some(crate::run::Origin::queue("selected"));
15181        retry.state.pr_head = Some(reselected.branch.clone());
15182        retry.state.pr_recovery = Some(reselected.clone());
15183        crate::pr_head::check_predecessors(&retry.state, &reselected.branch)
15184            .await
15185            .unwrap();
15186        let restarted = Runner::open_selected(
15187            &repo,
15188            retry.state,
15189            retry.roles,
15190            1,
15191            runner.state.base_commit.clone(),
15192            reselected,
15193        )
15194        .await
15195        .unwrap();
15196        assert_eq!(
15197            git::rev_parse(&restarted.state.winner().unwrap().worktree, "HEAD")
15198                .await
15199                .unwrap(),
15200            head
15201        );
15202        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
15203        assert_eq!(
15204            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
15205            head
15206        );
15207    }
15208
15209    #[tokio::test]
15210    #[cfg(unix)]
15211    async fn fallback_and_interrupted_restoration_require_coordination() {
15212        use std::os::fd::AsRawFd as _;
15213        ask_test_home();
15214        let tmp = tempfile::tempdir().unwrap();
15215        let mut runner = registered_runner(tmp.path()).await;
15216        runner.state.config.graph.timeout_resource_wait = 1;
15217        let winner = runner.state.candidates[0].clone();
15218        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
15219        let leftover = winner.worktree.join("leftover");
15220        std::fs::write(&leftover, "untrusted edits").unwrap();
15221        let next = tmp.path().join("next-fixer");
15222        let mut failed = spec("first");
15223        failed.command = vec!["sh".into(), "-c".into(), "exit 1".into()];
15224        let mut successor = spec("second");
15225        successor.command = vec![
15226            "sh".into(),
15227            "-c".into(),
15228            format!("touch '{}'; echo done", next.display()),
15229        ];
15230        let attempts = vec![
15231            (failed.clone(), "first".into()),
15232            (successor.clone(), "second".into()),
15233        ];
15234        let lock_path = runner.state.repo.join(".git/updater.lock");
15235        let external = std::fs::File::create(&lock_path).unwrap();
15236        assert_eq!(
15237            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15238            0
15239        );
15240        let artifacts = tmp.path().join("artifacts");
15241        let build = |spec, seat| SeatJob {
15242            spec,
15243            seat,
15244            cwd: winner.worktree.clone(),
15245            prompt: "fixture".into(),
15246            timeout: Duration::from_secs(10),
15247            allow_write: true,
15248            sessions: false,
15249            artifacts: artifacts.clone(),
15250            stem: "fix".into(),
15251            handover: None,
15252        };
15253        let (_, _, out) = runner
15254            .ask_fixer_among(
15255                attempts.clone(),
15256                "graft",
15257                None,
15258                Some((&winner.worktree, &head)),
15259                build,
15260            )
15261            .await;
15262        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
15263        assert!(leftover.exists(), "contention must prevent clean");
15264        assert!(!next.exists());
15265        assert!(runner.state.handovers.is_empty());
15266        // Early interrupted-repair rollback uses the same protected route.
15267        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
15268            from_run: "earlier".into(),
15269            generation: 1,
15270            mode: crate::recovery::Mode::VerifyRepair,
15271            reasons: Vec::new(),
15272            reviewed_head: None,
15273            rounds: Vec::new(),
15274            open_findings: Vec::new(),
15275            evidence: None,
15276            criteria_inherited: true,
15277            repair: crate::recovery::Repair::Started {
15278                before: head.clone(),
15279            },
15280        });
15281        assert!(
15282            runner
15283                .recovery_repair(&winner)
15284                .await
15285                .unwrap_err()
15286                .is::<crate::repo_lock::ResourceBlocked>()
15287        );
15288        assert!(matches!(
15289            runner.state.recovery.as_ref().unwrap().repair,
15290            crate::recovery::Repair::Started { .. }
15291        ));
15292        assert!(leftover.exists());
15293        drop(external);
15294        runner.recovery_repair(&winner).await.unwrap();
15295        assert!(!leftover.exists());
15296        assert!(matches!(
15297            runner.state.recovery.as_ref().unwrap().repair,
15298            crate::recovery::Repair::Done { .. }
15299        ));
15300        // A hard lock-open failure also leaves HEAD and untracked work intact.
15301        std::fs::remove_file(&lock_path).unwrap();
15302        std::fs::create_dir(&lock_path).unwrap();
15303        std::fs::write(&leftover, "untrusted edits").unwrap();
15304        let (_, _, out) = runner
15305            .ask_fixer_among(
15306                attempts,
15307                "graft",
15308                None,
15309                Some((&winner.worktree, &head)),
15310                build,
15311            )
15312            .await;
15313        assert!(matches!(out, AgentOutcome::Failed(_)));
15314        assert!(leftover.exists());
15315        assert!(!next.exists());
15316        assert_eq!(
15317            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15318            head
15319        );
15320    }
15321
15322    #[cfg(unix)]
15323    async fn registered_runner(root: &Path) -> Runner {
15324        repository_runner(root, crate::config::test_coordination()).await
15325    }
15326
15327    async fn repository_runner(
15328        root: &Path,
15329        coordination: Option<crate::config::Coordination>,
15330    ) -> Runner {
15331        ask_test_home();
15332        let repo = root.join("repo");
15333        std::fs::create_dir_all(&repo).unwrap();
15334        init_repo(&repo);
15335        if coordination.is_some() {
15336            std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
15337        }
15338        let mut runner = runner_at(RunStatus::Prep);
15339        runner.state.repo = repo.clone();
15340        runner.state.config.coordination = coordination;
15341        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
15342        runner.state.config.graph.worktree_root = Some(root.join("wt"));
15343        runner.state.config.graph.advise = false;
15344        runner.roles.implementers = vec![spec("implement")];
15345        runner.roles.judges = vec![spec("judge")];
15346        runner.prep().await.unwrap();
15347        runner
15348    }
15349
15350    const AUTH_OUTAGE: &str = r#"{"is_error":true,"terminal_reason":"api_error","result":"Failed to authenticate: OAuth session expired and could not be refreshed"}"#;
15351
15352    #[tokio::test]
15353    async fn all_unauthenticated_wave_stops_the_node_without_nudges() {
15354        let tmp = tempfile::tempdir().unwrap();
15355        let mut runner = repository_runner(tmp.path(), None).await;
15356        let prompts = runner.state.config.prompts.clone();
15357        let run = runner.state.id.clone();
15358        let ctx = WaveCtx {
15359            carry_seats: false,
15360            pauses: None,
15361            run: &run,
15362            node: "advise",
15363            prompts: &prompts,
15364            cache: None,
15365            round: None,
15366        };
15367        let jobs: Vec<_> = ["alpha", "beta"]
15368            .into_iter()
15369            .map(|id| SeatJob {
15370                spec: scripted(id, AUTH_OUTAGE),
15371                seat: SeatState::new(id, id, 7),
15372                prompt: "propose".into(),
15373                cwd: runner.state.candidates[0].worktree.clone(),
15374                timeout: Duration::from_secs(10),
15375                allow_write: false,
15376                sessions: false,
15377                artifacts: agent::artifacts_dir(&runner.state.dir()),
15378                stem: id.into(),
15379                handover: None,
15380            })
15381            .collect();
15382        let mut losses = Vec::new();
15383        let results = ask_wave_with(
15384            jobs.clone(),
15385            runner.sem.clone(),
15386            2,
15387            &[],
15388            &ctx,
15389            &mut losses,
15390            &mut runner.state,
15391            &|_: &str| Ok(()),
15392        )
15393        .await;
15394        assert!(
15395            results
15396                .iter()
15397                .all(|(seat, result, nudges)| seat.turns == 1 && result.is_err() && *nudges == 0)
15398        );
15399        assert_eq!(runner.state.quota.len(), 2);
15400        assert!(
15401            runner
15402                .state
15403                .quota
15404                .iter()
15405                .all(|q| q.cause == agent::QuotaCause::Authentication && !q.agent.is_empty())
15406        );
15407        assert!(!runner.state.advise_attempted);
15408        runner.stop_for_resource().unwrap();
15409        assert_eq!(runner.state.status, RunStatus::Blocked);
15410        assert_eq!(runner.state.resource_block.as_ref().unwrap().node, "advise");
15411        assert_eq!(
15412            runner.state.resource_block.as_ref().unwrap().kind,
15413            "agent authentication"
15414        );
15415        // A machine loss followed by an ordinary failure is not evidence
15416        // that the whole node was unavailable, and must not earn a refund.
15417        runner.state.resource_block = None;
15418        runner.state.quota.clear();
15419        let mut mixed = jobs;
15420        mixed[1].spec.command = vec!["false".into()];
15421        let results = ask_wave_with(
15422            mixed,
15423            runner.sem.clone(),
15424            0,
15425            &[],
15426            &ctx,
15427            &mut losses,
15428            &mut runner.state,
15429            &|_: &str| Ok(()),
15430        )
15431        .await;
15432        assert!(results.iter().all(|(_, res, _)| res.is_err()));
15433        assert!(runner.state.resource_block.is_none());
15434        assert_eq!(losses.len(), 1);
15435    }
15436
15437    #[tokio::test]
15438    async fn unauthenticated_implementation_keeps_its_candidate_pending() {
15439        let tmp = tempfile::tempdir().unwrap();
15440        let mut runner = repository_runner(tmp.path(), None).await;
15441        let implementer = scripted("implement", AUTH_OUTAGE);
15442        runner.roles.implementers = vec![implementer.clone()];
15443        runner.state.config.agents = vec![implementer];
15444        runner.implement().await.unwrap();
15445        assert_eq!(runner.state.status, RunStatus::Blocked);
15446        assert_eq!(runner.state.quota.len(), 1);
15447        assert_eq!(
15448            runner.state.quota[0].cause,
15449            agent::QuotaCause::Authentication
15450        );
15451        let candidate = &runner.state.candidates[0];
15452        assert!(candidate.failed.is_none() && !candidate.empty && candidate.commits == 0);
15453        assert_eq!(runner.state.seats["impl-A"].turns, 1);
15454    }
15455
15456    #[tokio::test]
15457    #[cfg(unix)]
15458    async fn parked_implementer_persists_completed_work() {
15459        for registered in [false, true] {
15460            let tmp = tempfile::tempdir().unwrap();
15461            let mut runner = registered_runner(tmp.path()).await;
15462            if !registered {
15463                std::fs::remove_file(runner.state.repo.join(".git/updater.contract")).unwrap();
15464            }
15465            let marker = tmp.path().join("started");
15466            let release = tmp.path().join("release");
15467            let mut implementer = spec("implement");
15468            implementer.command = vec![
15469                "sh".into(),
15470                "-c".into(),
15471                format!(
15472                    "touch '{}'; while [ ! -f '{}' ]; do sleep 0.01; done; echo completed > completed; echo saved-result",
15473                    marker.display(),
15474                    release.display()
15475                ),
15476            ];
15477            runner.roles.implementers = vec![implementer.clone()];
15478            runner.state.config.agents = vec![implementer];
15479            let pause = runner.pause.clone();
15480            let (result, ()) = tokio::join!(runner.implement(), async {
15481                tokio::time::timeout(Duration::from_secs(10), async {
15482                    while !marker.exists() {
15483                        tokio::time::sleep(Duration::from_millis(10)).await;
15484                    }
15485                })
15486                .await
15487                .unwrap();
15488                pause.park();
15489                std::fs::write(&release, "go").unwrap();
15490            });
15491            result.unwrap();
15492            let candidate = &runner.state.candidates[0];
15493            assert!(candidate.commits > 0, "{candidate:?}");
15494            assert!(candidate.summary.contains("saved-result"));
15495            assert_eq!(candidate.files, 1);
15496            let before = candidate.commits;
15497            runner.implement().await.unwrap();
15498            assert_eq!(runner.state.candidates[0].commits, before);
15499        }
15500    }
15501
15502    #[tokio::test]
15503    #[cfg(unix)]
15504    async fn resource_blocked_recovery_retries_the_unstarted_fixer() {
15505        let tmp = tempfile::tempdir().unwrap();
15506        let mut runner = registered_runner(tmp.path()).await;
15507        let winner = runner.state.candidates[0].clone();
15508        let cache = tmp.path().join("cache");
15509        runner.state.config.verify.e2e = vec![format!("CARGO_TARGET_DIR={} true", cache.display())];
15510        runner.state.config.graph.timeout_resource_wait = 0;
15511        let owner = crate::cache::Owner::here("other", "e2e", "e2e", &cache, "abc");
15512        let crate::cache::AcquireOutcome::Acquired(held) =
15513            crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap()
15514        else {
15515            panic!("cache must be free")
15516        };
15517        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
15518            from_run: "earlier".into(),
15519            generation: 1,
15520            mode: crate::recovery::Mode::VerifyRepair,
15521            reasons: Vec::new(),
15522            reviewed_head: None,
15523            rounds: Vec::new(),
15524            open_findings: Vec::new(),
15525            evidence: None,
15526            criteria_inherited: true,
15527            repair: crate::recovery::Repair::NotStarted,
15528        });
15529        runner.recovery_repair(&winner).await.unwrap();
15530        assert!(matches!(
15531            runner.state.recovery.as_ref().unwrap().repair,
15532            crate::recovery::Repair::WaitingForRestore { .. }
15533        ));
15534        drop(held);
15535        runner.state.resource_block = None;
15536        runner.state.config.graph.timeout_resource_wait = 1;
15537        runner.recovery_repair(&winner).await.unwrap();
15538        assert!(matches!(
15539            runner.state.recovery.as_ref().unwrap().repair,
15540            crate::recovery::Repair::Done { .. }
15541        ));
15542        assert!(runner.state.seats.values().any(|seat| seat.turns > 0));
15543    }
15544
15545    #[tokio::test]
15546    #[cfg(unix)]
15547    async fn repository_blocked_graft_and_recovery_retry_after_deferred_restore() {
15548        use std::os::fd::AsRawFd as _;
15549        for graft in [false, true] {
15550            let tmp = tempfile::tempdir().unwrap();
15551            let mut runner = registered_runner(tmp.path()).await;
15552            runner.state.config.graph.timeout_resource_wait = 1;
15553            let winner = runner.state.candidates[0].clone();
15554            let marker = tmp.path().join("fixer-started");
15555            let mut fixer = spec("fixer");
15556            fixer.command = vec![
15557                "sh".into(),
15558                "-c".into(),
15559                format!("echo started >> '{}'; echo done", marker.display()),
15560            ];
15561            runner.roles.fixer = Some(vec![fixer]);
15562            if graft {
15563                let mut loser = winner.clone();
15564                loser.label = 'B';
15565                loser.index = 1;
15566                runner.state.candidates.push(loser);
15567                runner.state.config.graph.graft_runner_up = true;
15568                runner.state.tally = Some(Tally {
15569                    first_choice: BTreeMap::new(),
15570                    borda: BTreeMap::new(),
15571                    winner: winner.label,
15572                    rankings: 1,
15573                    unanimous_initial: true,
15574                    deliberated: false,
15575                    changed_votes: 0,
15576                    unanimous_final: true,
15577                    tie_break: None,
15578                    judges: 1,
15579                    present: 1,
15580                    quorum: 1,
15581                    met_quorum: true,
15582                    uncontested: None,
15583                });
15584                runner.state.judgements.push(crate::run::Judgement {
15585                    judge: 1,
15586                    seat: "judge-1".into(),
15587                    agent: "judge".into(),
15588                    ranking: vec![winner.label, 'B'],
15589                    reasons: BTreeMap::new(),
15590                    confidence: None,
15591                    strengths: BTreeMap::from([("B".into(), vec!["handles empty input".into()])]),
15592                    order: vec![0, 1],
15593                    failed: None,
15594                    duration_ms: 0,
15595                });
15596            } else {
15597                runner.state.recovery = Some(crate::recovery::RecoveryRecord {
15598                    from_run: "earlier".into(),
15599                    generation: 1,
15600                    mode: crate::recovery::Mode::VerifyRepair,
15601                    reasons: Vec::new(),
15602                    reviewed_head: None,
15603                    rounds: Vec::new(),
15604                    open_findings: Vec::new(),
15605                    evidence: None,
15606                    criteria_inherited: true,
15607                    repair: crate::recovery::Repair::NotStarted,
15608                });
15609            }
15610            let reader = crate::repo_lock::SeatLease::for_checkout(
15611                &winner.worktree,
15612                false,
15613                crate::config::test_coordination().as_ref(),
15614            )
15615            .await
15616            .unwrap();
15617            let pause = runner.pause.clone();
15618            let (result, ()) = tokio::join!(
15619                async {
15620                    if graft {
15621                        runner.graft().await
15622                    } else {
15623                        runner.recovery_repair(&winner).await
15624                    }
15625                },
15626                async {
15627                    tokio::time::sleep(Duration::from_millis(100)).await;
15628                    pause.park();
15629                }
15630            );
15631            result.unwrap();
15632            assert!(!marker.exists(), "a blocked seat must not spawn");
15633            // Exercise the persisted state, as a binary replacement/resume does.
15634            runner.state = RunState::load(&runner.state.id).unwrap();
15635            if graft {
15636                assert_eq!(
15637                    runner.state.graft.as_ref().unwrap().outcome,
15638                    GraftOutcome::WaitingForRestore
15639                );
15640            } else {
15641                assert!(matches!(
15642                    runner.state.recovery.as_ref().unwrap().repair,
15643                    crate::recovery::Repair::WaitingForRestore { .. }
15644                ));
15645            }
15646            drop(reader);
15647            runner.pause = Pause::new();
15648            runner.state.resource_block = None;
15649            // Deferred restoration must still respect an external lock owner.
15650            let external =
15651                std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
15652            assert_eq!(
15653                unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15654                0
15655            );
15656            let leftover = winner.worktree.join("leftover");
15657            std::fs::write(&leftover, "earlier fallback edits").unwrap();
15658            let result = if graft {
15659                runner.graft().await
15660            } else {
15661                runner.recovery_repair(&winner).await
15662            };
15663            assert!(
15664                result
15665                    .unwrap_err()
15666                    .is::<crate::repo_lock::ResourceBlocked>()
15667            );
15668            assert!(leftover.exists());
15669            assert!(!marker.exists());
15670            drop(external);
15671            runner.state.resource_block = None;
15672            let result = if graft {
15673                runner.graft().await
15674            } else {
15675                runner.recovery_repair(&winner).await
15676            };
15677            result.unwrap();
15678            assert!(!leftover.exists(), "restore must precede retry");
15679            assert_eq!(std::fs::read_to_string(&marker).unwrap(), "started\n");
15680            if graft {
15681                assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
15682            } else {
15683                assert!(matches!(
15684                    runner.state.recovery.as_ref().unwrap().repair,
15685                    crate::recovery::Repair::Done { .. }
15686                ));
15687            }
15688        }
15689    }
15690
15691    #[tokio::test]
15692    #[cfg(unix)]
15693    async fn interrupted_graft_restore_waits_and_preserves_its_record() {
15694        use std::os::fd::AsRawFd as _;
15695        let tmp = tempfile::tempdir().unwrap();
15696        let mut runner = registered_runner(tmp.path()).await;
15697        runner.state.config.graph.timeout_resource_wait = 1;
15698        let winner = runner.state.candidates[0].clone();
15699        let pre = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
15700        runner.state.tally = Some(Tally {
15701            first_choice: BTreeMap::new(),
15702            borda: BTreeMap::new(),
15703            winner: winner.label,
15704            rankings: 0,
15705            unanimous_initial: false,
15706            deliberated: false,
15707            changed_votes: 0,
15708            unanimous_final: false,
15709            tie_break: None,
15710            judges: 0,
15711            present: 0,
15712            quorum: 0,
15713            met_quorum: true,
15714            uncontested: Some("fixture".into()),
15715        });
15716        runner.state.graft = Some(GraftRecord {
15717            pre: pre.clone(),
15718            post: None,
15719            lines: None,
15720            limit: None,
15721            agent: None,
15722            outcome: GraftOutcome::Running,
15723            requested: Vec::new(),
15724            adoption: None,
15725            adoption_error: None,
15726        });
15727        std::fs::write(winner.worktree.join("README.md"), "unfinished graft\n").unwrap();
15728        git::commit_all(&winner.worktree, "unfinished graft")
15729            .await
15730            .unwrap();
15731        let unfinished = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
15732        let leftover = winner.worktree.join("leftover");
15733        std::fs::write(&leftover, "untrusted edits").unwrap();
15734        let path = runner.state.repo.join(".git/updater.lock");
15735        let external = std::fs::File::create(&path).unwrap();
15736        assert_eq!(
15737            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15738            0
15739        );
15740        assert!(
15741            runner
15742                .graft()
15743                .await
15744                .unwrap_err()
15745                .is::<crate::repo_lock::ResourceBlocked>()
15746        );
15747        assert!(matches!(
15748            runner.state.graft.as_ref().unwrap().outcome,
15749            GraftOutcome::Running
15750        ));
15751        assert_eq!(
15752            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15753            unfinished
15754        );
15755        assert!(leftover.exists());
15756        drop(external);
15757        std::fs::remove_file(&path).unwrap();
15758        std::fs::create_dir(&path).unwrap();
15759        assert!(runner.graft().await.is_err());
15760        assert!(matches!(
15761            runner.state.graft.as_ref().unwrap().outcome,
15762            GraftOutcome::Running
15763        ));
15764        assert_eq!(
15765            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15766            unfinished
15767        );
15768        assert!(leftover.exists());
15769        std::fs::remove_dir(&path).unwrap();
15770        runner.graft().await.unwrap();
15771        assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
15772        assert_eq!(git::rev_parse(&winner.worktree, "HEAD").await.unwrap(), pre);
15773        assert!(!leftover.exists());
15774    }
15775
15776    #[tokio::test]
15777    #[cfg(unix)]
15778    async fn repository_contention_blocks_and_parks_without_poisoning_preparation() {
15779        use std::os::fd::AsRawFd as _;
15780        let tmp = tempfile::tempdir().unwrap();
15781        let mut runner = registered_runner(tmp.path()).await;
15782        runner.state.prep_complete = Some(false);
15783        runner.state.config.graph.timeout_resource_wait = 1;
15784        runner.state.save().unwrap();
15785        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
15786        assert_eq!(
15787            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15788            0
15789        );
15790        runner.execute().await.unwrap();
15791        let disk = RunState::load(&runner.state.id).unwrap();
15792        assert!(disk.driver_exited);
15793        assert_eq!(disk.driver_pid, None);
15794        assert_eq!(runner.state.status, RunStatus::Blocked);
15795        assert_eq!(
15796            runner.state.resource_block.as_ref().unwrap().kind,
15797            "repository coordination"
15798        );
15799        assert!(runner.state.prep_failure.is_none());
15800        assert!(runner.state.seats.is_empty());
15801        runner.pause.park();
15802        // Include headroom for Git subprocesses under parallel test load;
15803        // the repository contention deadline itself remains one second.
15804        tokio::time::timeout(Duration::from_secs(10), runner.execute())
15805            .await
15806            .unwrap()
15807            .unwrap();
15808        assert!(runner.state.parked);
15809        assert!(runner.state.prep_failure.is_none());
15810        let disk = RunState::load(&runner.state.id).unwrap();
15811        assert!(disk.driver_exited);
15812        assert_eq!(disk.driver_pid, None);
15813    }
15814
15815    #[tokio::test]
15816    #[cfg(unix)]
15817    async fn dropping_execute_during_a_repository_wait_releases_the_driver() {
15818        use std::os::fd::AsRawFd as _;
15819        let tmp = tempfile::tempdir().unwrap();
15820        let mut runner = registered_runner(tmp.path()).await;
15821        runner.state.prep_complete = Some(false);
15822        runner.state.config.graph.timeout_resource_wait = 30;
15823        runner.state.save().unwrap();
15824        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
15825        assert_eq!(
15826            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15827            0
15828        );
15829        assert!(
15830            tokio::time::timeout(Duration::from_millis(100), runner.execute())
15831                .await
15832                .is_err()
15833        );
15834        let disk = RunState::load(&runner.state.id).unwrap();
15835        assert!(disk.driver_exited);
15836        assert_eq!(disk.driver_pid, None);
15837        assert!(disk.status.resumable());
15838        assert!(runner.state.driver_exited);
15839        assert_eq!(runner.state.driver_pid, None);
15840        runner.state.save().unwrap();
15841        assert_eq!(RunState::load(&runner.state.id).unwrap().driver_pid, None);
15842    }
15843
15844    #[tokio::test]
15845    #[cfg(unix)]
15846    async fn gate_takes_cache_before_repository_so_an_editing_wave_can_finish() {
15847        let tmp = tempfile::tempdir().unwrap();
15848        let mut runner = registered_runner(tmp.path()).await;
15849        let winner = runner.state.candidates[0].clone();
15850        let cache = tmp.path().join("cache");
15851        let started = tmp.path().join("pre-gate-started");
15852        runner.state.config.verify.pre_gate = vec![format!("touch '{}'", started.display())];
15853        runner.state.config.verify.gate =
15854            vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
15855        let home = crate::run::home();
15856        let owner =
15857            crate::cache::Owner::here("editing-wave", "implement", "*", &winner.worktree, "HEAD");
15858        let guard = match crate::cache::try_acquire(&home, &cache, &owner).unwrap() {
15859            crate::cache::AcquireOutcome::Acquired(g) => g,
15860            crate::cache::AcquireOutcome::Busy(busy) => panic!("cache must be free: {busy:?}"),
15861        };
15862        let mut gate = Box::pin(runner.run_gate(&winner));
15863        assert!(
15864            tokio::time::timeout(Duration::from_millis(150), &mut gate)
15865                .await
15866                .is_err()
15867        );
15868        assert!(!started.exists(), "pre-gate must wait for the cache too");
15869        // Simulate the wave that already owns the cache entering invoke.
15870        // It must obtain the editor reservation and finish without waiting
15871        // for the gate that is queued behind its cache.
15872        let wait = crate::repo_lock::WaitPolicy::new(Duration::from_millis(200), || false);
15873        let editor = crate::repo_lock::SeatLease::checkout_with(
15874            &winner.worktree,
15875            true,
15876            crate::config::test_coordination().as_ref(),
15877            &wait,
15878        )
15879        .await
15880        .unwrap();
15881        drop(editor);
15882        guard.release();
15883        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
15884            .await
15885            .unwrap()
15886            .unwrap();
15887        drop(gate);
15888        assert!(outcomes.iter().all(CommandOutcome::ok));
15889        assert!(started.exists());
15890    }
15891
15892    #[tokio::test]
15893    #[cfg(unix)]
15894    async fn post_seat_rescue_and_gate_wait_for_shared_lock() {
15895        use std::os::fd::AsRawFd as _;
15896
15897        ask_test_home();
15898        let tmp = tempfile::tempdir().unwrap();
15899        let repo = tmp.path().join("repo");
15900        std::fs::create_dir_all(&repo).unwrap();
15901        init_repo(&repo);
15902        let common = repo.join(".git");
15903        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
15904        let mut runner = runner_at(RunStatus::Prep);
15905        runner.state.repo = repo.clone();
15906        runner.state.config.coordination = crate::config::test_coordination();
15907        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
15908        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
15909        runner.state.config.graph.advise = false;
15910        runner.roles.implementers = vec![spec("implement")];
15911        runner.roles.judges = vec![spec("judge")];
15912        runner.prep().await.unwrap();
15913        let winner = runner.state.candidates[0].clone();
15914        // Emulate edits already left by a completed seat. The fixture CLI
15915        // only reports completion; it performs no repository operations.
15916        std::fs::write(winner.worktree.join("leftover"), "seat work\n").unwrap();
15917        let completed = tmp.path().join("seat-completed");
15918        runner.roles.implementers[0].command = vec![
15919            "sh".into(),
15920            "-c".into(),
15921            format!("touch '{}'; echo completed", completed.display()),
15922        ];
15923        let outsider = std::fs::File::create(common.join("updater.lock")).unwrap();
15924        assert_eq!(
15925            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15926            0
15927        );
15928        let before = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
15929        let mut implement = Box::pin(runner.implement());
15930        tokio::select! {
15931            result = &mut implement => panic!("rescue must wait: {result:?}"),
15932            result = tokio::time::timeout(Duration::from_secs(10), async {
15933                while !completed.exists() {
15934                    tokio::time::sleep(Duration::from_millis(20)).await;
15935                }
15936            }) => result.unwrap(),
15937        }
15938        assert!(
15939            tokio::time::timeout(Duration::from_millis(200), &mut implement)
15940                .await
15941                .is_err()
15942        );
15943        assert_eq!(
15944            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15945            before
15946        );
15947        assert_eq!(
15948            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
15949            0
15950        );
15951        tokio::time::timeout(Duration::from_secs(10), &mut implement)
15952            .await
15953            .unwrap()
15954            .unwrap();
15955        drop(implement);
15956        assert_ne!(
15957            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15958            before
15959        );
15960        assert!(git::is_clean(&winner.worktree).await.unwrap());
15961
15962        let started = tmp.path().join("pre-gate-started");
15963        let proceed = tmp.path().join("pre-gate-proceed");
15964        let checked = tmp.path().join("gate-ran");
15965        runner.state.config.verify.pre_gate = vec![format!(
15966            "echo mechanical >> README.md; touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
15967            started.display(),
15968            proceed.display()
15969        )];
15970        runner.state.config.verify.gate = vec![format!("touch '{}'", checked.display())];
15971        assert_eq!(
15972            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15973            0
15974        );
15975        let mut gate = Box::pin(runner.run_gate(&winner));
15976        assert!(
15977            tokio::time::timeout(Duration::from_millis(200), &mut gate)
15978                .await
15979                .is_err()
15980        );
15981        assert!(!started.exists());
15982        assert!(!checked.exists());
15983        assert!(git::is_clean(&winner.worktree).await.unwrap());
15984        assert_eq!(
15985            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
15986            0
15987        );
15988        tokio::select! {
15989            result = &mut gate => panic!("pre-gate must wait for signal: {result:?}"),
15990            result = tokio::time::timeout(Duration::from_secs(10), async {
15991                while !started.exists() {
15992                    tokio::time::sleep(Duration::from_millis(20)).await;
15993                }
15994            }) => result.unwrap(),
15995        }
15996        assert_eq!(
15997            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15998            -1,
15999            "mechanical edits must hold the real lock"
16000        );
16001        std::fs::write(proceed, "ready").unwrap();
16002        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
16003            .await
16004            .unwrap()
16005            .unwrap();
16006        drop(gate);
16007        assert!(outcomes.iter().all(CommandOutcome::ok));
16008        assert!(checked.exists());
16009        assert!(runner.state.pre_gate_commit.is_some());
16010        assert!(git::is_clean(&winner.worktree).await.unwrap());
16011        assert_eq!(
16012            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16013            0,
16014            "gate completion must release coordination"
16015        );
16016        drop(outsider);
16017        std::fs::remove_file(common.join("updater.lock")).unwrap();
16018        std::fs::create_dir(common.join("updater.lock")).unwrap();
16019        std::fs::remove_file(&started).unwrap();
16020        std::fs::remove_file(&checked).unwrap();
16021        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16022        let error = runner.run_gate(&winner).await.unwrap_err();
16023        assert!(
16024            error
16025                .to_string()
16026                .contains("acquire mandatory repository lock")
16027        );
16028        assert!(
16029            !started.exists(),
16030            "failed acquisition must prevent pre-gate"
16031        );
16032        assert!(!checked.exists(), "failed acquisition must prevent gate");
16033        assert!(git::is_clean(&winner.worktree).await.unwrap());
16034        assert_eq!(
16035            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16036            head
16037        );
16038    }
16039
16040    #[tokio::test]
16041    #[cfg(unix)]
16042    async fn preparation_waits_for_shared_lock_before_checkout_and_holds_it_through_setup() {
16043        use std::os::fd::AsRawFd as _;
16044        use std::time::Duration;
16045
16046        ask_test_home();
16047        let tmp = tempfile::tempdir().unwrap();
16048        let repo = tmp.path().join("repo");
16049        std::fs::create_dir_all(&repo).unwrap();
16050        init_repo(&repo);
16051        let common = repo.join(".git");
16052        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
16053        let lock = std::fs::File::create(common.join("updater.lock")).unwrap();
16054        assert_eq!(
16055            unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16056            0
16057        );
16058        let mut runner = runner_at(RunStatus::Prep);
16059        runner.state.repo = repo.clone();
16060        runner.state.config.coordination = crate::config::test_coordination();
16061        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16062        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16063        runner.state.config.graph.advise = true;
16064        runner.state.config.graph.advisors = 1;
16065        runner.roles.implementers = vec![spec("implement")];
16066        runner.roles.judges = vec![spec("judge")];
16067        let root = runner.state.worktree_root();
16068        let started = tmp.path().join("setup-started");
16069        let proceed = tmp.path().join("setup-proceed");
16070        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
16071            run: Some(format!(
16072                "touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
16073                started.display(),
16074                proceed.display()
16075            )),
16076            ..Default::default()
16077        }];
16078        let branches = git::git(&repo, &["branch", "--list"]).await.unwrap();
16079        let config = git::git(&repo, &["config", "--local", "--list"])
16080            .await
16081            .unwrap();
16082        let mut prep = Box::pin(runner.prep());
16083        assert!(
16084            tokio::time::timeout(Duration::from_millis(200), &mut prep)
16085                .await
16086                .is_err()
16087        );
16088        assert!(
16089            !root.exists(),
16090            "contention must prevent even checkout creation"
16091        );
16092        assert!(!started.exists(), "contention must prevent setup");
16093        assert_eq!(
16094            git::git(&repo, &["branch", "--list"]).await.unwrap(),
16095            branches
16096        );
16097        assert_eq!(
16098            git::git(&repo, &["config", "--local", "--list"])
16099                .await
16100                .unwrap(),
16101            config
16102        );
16103        drop(lock);
16104        tokio::select! {
16105            result = &mut prep => panic!("setup must wait for its signal: {result:?}"),
16106            result = tokio::time::timeout(Duration::from_secs(10), async {
16107                while !started.exists() {
16108                    tokio::time::sleep(Duration::from_millis(20)).await;
16109                }
16110            }) => result.unwrap(),
16111        }
16112        let outsider = std::fs::File::open(common.join("updater.lock")).unwrap();
16113        assert_eq!(
16114            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16115            -1
16116        );
16117        assert!(
16118            tokio::time::timeout(
16119                Duration::from_millis(100),
16120                crate::repo_lock::SeatLease::for_checkout(
16121                    &repo,
16122                    true,
16123                    crate::config::test_coordination().as_ref()
16124                )
16125            )
16126            .await
16127            .is_err(),
16128            "preparation must also exclude local editors"
16129        );
16130        std::fs::write(proceed, "ready").unwrap();
16131        tokio::time::timeout(Duration::from_secs(10), &mut prep)
16132            .await
16133            .unwrap()
16134            .unwrap();
16135        drop(prep);
16136        assert_eq!(runner.state.prep_complete, Some(true));
16137        assert!(root.join("judge-1").exists());
16138        assert!(root.join("advisor-1").exists());
16139        assert_eq!(
16140            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16141            0
16142        );
16143    }
16144
16145    #[tokio::test]
16146    #[cfg(unix)]
16147    async fn preparation_lock_failure_prevents_repository_changes() {
16148        ask_test_home();
16149        let tmp = tempfile::tempdir().unwrap();
16150        let repo = tmp.path().join("repo");
16151        std::fs::create_dir_all(&repo).unwrap();
16152        init_repo(&repo);
16153        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
16154        // A directory at the required lock path makes opening the real lock
16155        // fail, rather than merely exercising an invalid registration.
16156        std::fs::create_dir(repo.join(".git/updater.lock")).unwrap();
16157        let mut runner = runner_at(RunStatus::Prep);
16158        runner.state.repo = repo.clone();
16159        runner.state.config.coordination = crate::config::test_coordination();
16160        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16161        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16162        runner.roles.implementers = vec![spec("implement")];
16163        let error = runner.prep().await.unwrap_err();
16164        assert!(
16165            error
16166                .to_string()
16167                .contains("acquire mandatory repository lock")
16168        );
16169        assert!(!runner.state.worktree_root().exists());
16170        assert!(runner.state.candidates.is_empty());
16171        assert!(!repo.join(".git/config.worktree").exists());
16172        assert_eq!(
16173            git::git(&repo, &["branch", "--list"]).await.unwrap().trim(),
16174            "* main"
16175        );
16176    }
16177
16178    #[tokio::test]
16179    async fn preparation_records_creation_intent_before_git_can_fail() {
16180        ask_test_home();
16181        let tmp = tempfile::tempdir().unwrap();
16182        let repo = tmp.path().join("repo");
16183        std::fs::create_dir_all(&repo).unwrap();
16184        init_repo(&repo);
16185        let mut runner = runner_at(RunStatus::Prep);
16186        runner.state.repo = repo.clone();
16187        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16188        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16189        runner.state.config.blind.commit_msg_hook = false;
16190        runner.roles.implementers = vec![spec("one")];
16191        let label = blind::assign_labels(1, runner.state.seed)[0];
16192        let branch = runner.state.branch_for(label);
16193        // A conflicting branch makes Git refuse creation before a candidate
16194        // can be registered. The durable intent must still identify it.
16195        git::git(&repo, &["branch", &branch]).await.unwrap();
16196        assert!(runner.prep().await.is_err());
16197        let saved = RunState::load(&runner.state.id).unwrap();
16198        assert!(saved.candidates.is_empty());
16199        let event = saved
16200            .events
16201            .iter()
16202            .find(|e| e.node == "prep-intent")
16203            .unwrap();
16204        let intent: serde_json::Value = serde_json::from_str(&event.message).unwrap();
16205        assert_eq!(intent["branch"], branch);
16206        assert_eq!(intent["start"], runner.state.base_commit);
16207        assert_eq!(
16208            intent["worktree"],
16209            runner
16210                .state
16211                .worktree_root()
16212                .join(format!("cand-{label}"))
16213                .to_string_lossy()
16214                .as_ref()
16215        );
16216        assert_eq!(intent["picks"], serde_json::json!([]));
16217    }
16218
16219    #[tokio::test]
16220    async fn invalid_pinned_sources_create_no_partial_worktrees() {
16221        ask_test_home();
16222        let tmp = tempfile::tempdir().unwrap();
16223        let repo = tmp.path().join("repo");
16224        std::fs::create_dir_all(&repo).unwrap();
16225        init_repo(&repo);
16226        let mut runner = runner_at(RunStatus::Prep);
16227        runner.state.repo = repo.clone();
16228        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16229        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
16230        runner.state.sources.pick_commits.push(refs::Input {
16231            token: "missing".into(),
16232            sha: "0".repeat(40),
16233            provenance: refs::Provenance::ExplicitCli,
16234        });
16235        assert!(runner.prep().await.is_err());
16236        assert!(runner.state.candidates.is_empty());
16237        assert!(!runner.state.worktree_root().exists());
16238    }
16239
16240    #[tokio::test]
16241    async fn prose_and_legacy_inference_never_import_into_candidates() {
16242        ask_test_home();
16243        let tmp = tempfile::tempdir().unwrap();
16244        let repo = tmp.path().join("repo");
16245        std::fs::create_dir_all(&repo).unwrap();
16246        init_repo(&repo);
16247        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
16248        git::git(&repo, &["checkout", "-b", "magi/history/A"])
16249            .await
16250            .unwrap();
16251        std::fs::write(repo.join("unwanted"), "do not import").unwrap();
16252        git::git(&repo, &["add", "."]).await.unwrap();
16253        git::git(&repo, &["commit", "-m", "historical implementation"])
16254            .await
16255            .unwrap();
16256        let source = git::rev_parse(&repo, "HEAD").await.unwrap();
16257        git::git(&repo, &["checkout", "main"]).await.unwrap();
16258        for instruction in [
16259            format!("Example: magi/history/A at {source}"),
16260            format!("Quoted failure: cannot apply referenced commit {source} from magi/history/A"),
16261            format!("Never import magi/history/A or {source}"),
16262            format!("Conversation answer: I mentioned {source} only as background"),
16263        ] {
16264            let mut runner = runner_at(RunStatus::Prep);
16265            runner.state.repo = repo.clone();
16266            runner.state.base_commit = base.clone();
16267            runner.state.instruction = instruction.clone();
16268            runner.state.config.graph.worktree_root = Some(tmp.path().join(&runner.state.id));
16269            runner.state.config.blind.commit_msg_hook = false;
16270            runner.state.seeds = vec![refs::Seed {
16271                token: "magi/history/A".into(),
16272                sha: source.clone(),
16273                kind: refs::SeedKind::Unmerged,
16274                branch: true,
16275                detail: String::new(),
16276            }];
16277            runner.roles.implementers = vec![spec("one")];
16278            assert_eq!(seeded_instruction(&runner.state), instruction);
16279            // Model an old record with inferred seeds but no structured input field.
16280            let mut legacy = serde_json::to_value(&runner.state).unwrap();
16281            legacy.as_object_mut().unwrap().remove("sources");
16282            runner.state = serde_json::from_value(legacy).unwrap();
16283            assert_eq!(runner.state.sources, refs::Sources::default());
16284            runner.state.save().unwrap();
16285            runner.state = RunState::load(&runner.state.id).unwrap();
16286            runner.prep().await.unwrap();
16287            for candidate in &runner.state.candidates {
16288                assert_eq!(
16289                    git::rev_parse(&candidate.worktree, "HEAD").await.unwrap(),
16290                    base
16291                );
16292                assert!(!candidate.worktree.join("unwanted").exists());
16293            }
16294        }
16295    }
16296
16297    #[tokio::test]
16298    async fn preparation_retries_after_explicit_release_and_rebuilds_partial_candidates() {
16299        ask_test_home();
16300        let tmp = tempfile::tempdir().unwrap();
16301        let repo = tmp.path().join("repo");
16302        std::fs::create_dir_all(&repo).unwrap();
16303        init_repo(&repo);
16304        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
16305        git::git(&repo, &["checkout", "-b", "seed"]).await.unwrap();
16306        std::fs::write(repo.join("referenced"), "required commit").unwrap();
16307        git::git(&repo, &["add", "."]).await.unwrap();
16308        git::git(&repo, &["commit", "-m", "required seed"])
16309            .await
16310            .unwrap();
16311        let seed = git::rev_parse(&repo, "HEAD").await.unwrap();
16312        git::git(&repo, &["checkout", "main"]).await.unwrap();
16313        let mut runner = runner_at(RunStatus::Prep);
16314        runner.state.repo = repo.clone();
16315        runner.state.base_commit = base.clone();
16316        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16317        runner.state.config.graph.advise = false;
16318        runner.state.config.blind.commit_msg_hook = false;
16319        runner.state.sources =
16320            refs::Sources::resolve(&repo, "origin", None, std::slice::from_ref(&seed))
16321                .await
16322                .unwrap();
16323        runner.roles.implementers = vec![spec("one"), spec("two")];
16324        runner.roles.judges = vec![spec("judge")];
16325        let label = blind::assign_labels(2, runner.state.seed)[0];
16326        let branch = runner.state.branch_for(label);
16327        let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
16328        git::worktree_add_branch(&repo, &worktree, &branch, &base)
16329            .await
16330            .unwrap();
16331        runner.state.candidates.push(Candidate {
16332            index: 0,
16333            label,
16334            agent: "one".into(),
16335            branch,
16336            worktree,
16337            summary: String::new(),
16338            stat: String::new(),
16339            files: 0,
16340            commits: 0,
16341            empty: false,
16342            failed: None,
16343            verified_noop: None,
16344            duration_ms: 0,
16345            folded: false,
16346        });
16347        runner.state.save().unwrap();
16348        // Reload the checkpoint immediately before its first cherry-pick.
16349        runner.state = RunState::load(&runner.state.id).unwrap();
16350        assert_eq!(runner.state.prep_complete, Some(false));
16351        runner.prep().await.unwrap();
16352        assert_eq!(runner.state.prep_complete, Some(true));
16353        assert_eq!(runner.state.candidates.len(), 2);
16354        for candidate in &runner.state.candidates {
16355            assert_eq!(
16356                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
16357                git::tree_of(&repo, &seed).await.unwrap()
16358            );
16359            assert_eq!(
16360                std::fs::read_to_string(candidate.worktree.join("referenced")).unwrap(),
16361                "required commit"
16362            );
16363        }
16364        assert!(runner.state.worktree_root().join("judge-1").exists());
16365        let heads: Vec<String> = candidate_heads(&runner.state.candidates).await;
16366        runner.prep().await.unwrap();
16367        assert_eq!(candidate_heads(&runner.state.candidates).await, heads);
16368
16369        runner.state.prep_complete = Some(false);
16370        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
16371            run: Some(format!(
16372                "test -f '{}'",
16373                tmp.path().join("dependency-ready").display()
16374            )),
16375            ..Default::default()
16376        }];
16377        assert!(runner.prep().await.is_err());
16378        assert!(runner.state.prep_failure.is_some());
16379        std::fs::write(tmp.path().join("dependency-ready"), "available").unwrap();
16380        runner.state = RunState::load(&runner.state.id).unwrap();
16381        assert!(
16382            runner.prep().await.is_err(),
16383            "correcting the cause alone must not auto-retry"
16384        );
16385        let failed_at = runner.state.events.last().unwrap().at;
16386        assert!(
16387            runner.retry_preparation(failed_at).is_err(),
16388            "old approvals cannot unlock the hold"
16389        );
16390        let mut task = crate::queue::Task::new(
16391            "retry".into(),
16392            "retry setup".into(),
16393            repo.clone(),
16394            crate::queue::Source::Human,
16395        );
16396        task.start(runner.state.id.clone());
16397        task.hold_machine(Some("setup failed".into()));
16398        task.release_operator("cli", None);
16399        runner
16400            .retry_preparation(task.resumption.as_ref().unwrap().at)
16401            .unwrap();
16402        runner.prep().await.unwrap();
16403        assert!(runner.state.prep_failure.is_none());
16404        assert_eq!(runner.state.prep_complete, Some(true));
16405        assert_eq!(runner.state.candidates.len(), 2);
16406        assert!(runner.state.worktree_root().join("judge-1").exists());
16407        for candidate in &runner.state.candidates {
16408            assert_eq!(
16409                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
16410                git::tree_of(&repo, &seed).await.unwrap()
16411            );
16412        }
16413    }
16414
16415    async fn candidate_heads(candidates: &[Candidate]) -> Vec<String> {
16416        let mut heads = Vec::new();
16417        for candidate in candidates {
16418            heads.push(git::rev_parse(&candidate.worktree, "HEAD").await.unwrap());
16419        }
16420        heads
16421    }
16422
16423    async fn preservation_resume_fixture() -> (tempfile::TempDir, Runner) {
16424        ask_test_home();
16425        let tmp = tempfile::tempdir().unwrap();
16426        let repo = tmp.path().join("repo");
16427        std::fs::create_dir(&repo).unwrap();
16428        init_repo(&repo);
16429        let mut runner = runner_at(RunStatus::Reviewing);
16430        runner.state.repo = repo.clone();
16431        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16432        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16433        for (index, label) in ['A', 'B'].into_iter().enumerate() {
16434            let branch = format!("candidate-{label}");
16435            let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
16436            git::worktree_add_branch(&repo, &worktree, &branch, "main")
16437                .await
16438                .unwrap();
16439            if label == 'B' {
16440                std::fs::write(worktree.join("change"), "winner").unwrap();
16441                git::rescue_commit(&worktree, "candidate change")
16442                    .await
16443                    .unwrap();
16444            }
16445            runner.state.candidates.push(Candidate {
16446                index,
16447                label,
16448                agent: "alpha".into(),
16449                branch,
16450                worktree,
16451                summary: "completed reply".into(),
16452                stat: String::new(),
16453                files: usize::from(label == 'B'),
16454                commits: usize::from(label == 'B'),
16455                empty: label == 'A',
16456                failed: None,
16457                verified_noop: None,
16458                duration_ms: 1,
16459                folded: false,
16460            });
16461        }
16462        runner.state.judge_skipped = true;
16463        runner.state.tally = Some(Tally {
16464            first_choice: BTreeMap::new(),
16465            borda: BTreeMap::new(),
16466            winner: 'B',
16467            rankings: 0,
16468            unanimous_initial: false,
16469            deliberated: false,
16470            changed_votes: 0,
16471            unanimous_final: false,
16472            tie_break: None,
16473            judges: 0,
16474            present: 0,
16475            quorum: 0,
16476            met_quorum: true,
16477            uncontested: Some("only B produced a change".into()),
16478        });
16479        runner.state.save().unwrap();
16480        (tmp, runner)
16481    }
16482
16483    #[tokio::test]
16484    async fn fold_losers_reclaims_isolated_outputs_without_a_pool_limit() {
16485        let (_tmp, mut runner) = preservation_resume_fixture().await;
16486        runner.state.config.verify.build_cache = crate::config::BuildCache::Isolated;
16487        runner.state.config.disk.cache_limit_bytes = 0;
16488        runner.state.config.graph.advise = true;
16489        runner.state.config.graph.advisors = 1;
16490        let advisor = runner.state.worktree_root().join("advisor-1");
16491        git::worktree_add_detached(&runner.state.repo, &advisor, "main")
16492            .await
16493            .unwrap();
16494        let home = crate::run::home();
16495        let loser =
16496            crate::build_target::resolve(&home, &runner.state.candidates[0].worktree).unwrap();
16497        let winner =
16498            crate::build_target::resolve(&home, &runner.state.candidates[1].worktree).unwrap();
16499        let advisor = crate::build_target::resolve(&home, &advisor).unwrap();
16500        for target in [&loser, &winner, &advisor] {
16501            std::fs::write(target.join("build-output"), "compiled").unwrap();
16502        }
16503
16504        runner.fold_losers().await.unwrap();
16505
16506        assert!(!loser.join("build-output").exists());
16507        assert!(!advisor.join("build-output").exists());
16508        assert!(winner.join("build-output").is_file());
16509    }
16510
16511    #[tokio::test]
16512    async fn fold_losers_persists_discard_before_later_teardown_failure() {
16513        let (_tmp, mut runner) = preservation_resume_fixture().await;
16514        runner.state.candidates[0].folded = true;
16515        runner.state.config.graph.advise = true;
16516        runner.state.config.graph.advisors = 2;
16517        let repo = runner.state.repo.clone();
16518        let root = runner.state.worktree_root();
16519        let discarded = root.join("advisor-1");
16520        git::worktree_add_detached(&repo, &discarded, "main")
16521            .await
16522            .unwrap();
16523        std::fs::write(discarded.join("design_proposal.json"), "{}").unwrap();
16524        let protected = root.join("advisor-2");
16525        git::worktree_add_branch(&repo, &protected, "attached-advisor", "main")
16526            .await
16527            .unwrap();
16528        std::fs::write(protected.join("keep"), "uncommitted").unwrap();
16529        runner.state.save().unwrap();
16530
16531        assert!(runner.fold_losers().await.is_err());
16532        assert!(!discarded.exists());
16533        assert!(protected.join("keep").exists());
16534        let saved = RunState::load(&runner.state.id).unwrap();
16535        assert!(saved.events.iter().any(|event| {
16536            event.message.contains("advisor-1") && event.message.contains("design_proposal.json")
16537        }));
16538    }
16539
16540    #[tokio::test]
16541    async fn read_seat_teardown_discards_only_owned_detached_seats() {
16542        let (tmp, mut runner) = preservation_resume_fixture().await;
16543        let repo = runner.state.repo.clone();
16544        let root = runner.state.worktree_root();
16545        for name in ["advisor-3", "judge-1", "review-2"] {
16546            let path = root.join(name);
16547            git::worktree_add_detached(&repo, &path, "main")
16548                .await
16549                .unwrap();
16550            std::fs::write(path.join("README.md"), "uncommitted edit").unwrap();
16551            std::fs::write(path.join("design_proposal.json"), "{}").unwrap();
16552            remove_read_seat_worktree(&mut runner.state, &path)
16553                .await
16554                .unwrap();
16555            assert!(!path.exists());
16556        }
16557        let outside = tmp.path().join("advisor-1");
16558        let unknown = root.join("unknown");
16559        let attached = root.join("advisor-4");
16560        git::worktree_add_detached(&repo, &outside, "main")
16561            .await
16562            .unwrap();
16563        git::worktree_add_detached(&repo, &unknown, "main")
16564            .await
16565            .unwrap();
16566        git::worktree_add_branch(&repo, &attached, "attached-advisor", "main")
16567            .await
16568            .unwrap();
16569        let foreign = tmp.path().join("foreign");
16570        std::fs::create_dir(&foreign).unwrap();
16571        init_repo(&foreign);
16572        let wrong_repo = root.join("judge-2");
16573        git::worktree_add_detached(&foreign, &wrong_repo, "main")
16574            .await
16575            .unwrap();
16576        let candidate = runner.state.candidates[0].worktree.clone();
16577        for path in [outside, unknown, attached, wrong_repo, candidate] {
16578            std::fs::write(path.join("uncommitted"), "keep").unwrap();
16579            assert!(
16580                remove_read_seat_worktree(&mut runner.state, &path)
16581                    .await
16582                    .is_err()
16583            );
16584            assert_eq!(
16585                std::fs::read_to_string(path.join("uncommitted")).unwrap(),
16586                "keep"
16587            );
16588        }
16589    }
16590
16591    #[tokio::test]
16592    #[cfg(unix)]
16593    async fn disk_interrupted_empty_implementation_retries_after_reload_and_failed_checkpoint() {
16594        for (solo, failed_checkpoint) in
16595            [(true, false), (false, false), (true, true), (false, true)]
16596        {
16597            let (_tmp, mut runner) = preservation_resume_fixture().await;
16598            if solo {
16599                runner.state.candidates.retain(|c| c.label == 'A');
16600            }
16601            runner.state.candidates[0].empty = false;
16602            runner.state.candidates[0].summary.clear();
16603            runner.state.tally = None;
16604            runner.state.judge_skipped = false;
16605            runner.state.status = RunStatus::Implementing;
16606            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
16607            let mut implementer = spec("alpha");
16608            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
16609            runner.roles.implementers = vec![implementer];
16610            let patch = runner.state.dir().join("artifacts/cand-A.patch");
16611            if failed_checkpoint {
16612                std::fs::create_dir_all(&patch).unwrap();
16613            }
16614            runner.state.save().unwrap();
16615            assert_eq!(runner.implement().await.is_err(), failed_checkpoint);
16616            drop(pressure);
16617            runner.state = RunState::load(&runner.state.id).unwrap();
16618            assert_eq!(runner.state.status, RunStatus::Blocked);
16619            assert!(runner.state.interrupted_implementations.contains(&'A'));
16620            assert_eq!(runner.state.candidates[0].commits, 0);
16621            assert!(!runner.state.candidates[0].empty);
16622            assert!(runner.state.candidates[0].failed.is_none());
16623            if failed_checkpoint {
16624                assert!(runner.state.candidate_preservation.contains_key(&'A'));
16625                std::fs::remove_dir(patch).unwrap();
16626            }
16627            runner.state.resource_block = None;
16628            runner.state.config.disk.min_free_bytes = 0;
16629            runner.roles.implementers[0].command = vec![
16630                "sh".into(),
16631                "-c".into(),
16632                "printf 'retried empty interrupted seat\\n' > retry-source; echo completed".into(),
16633            ];
16634            runner.implement().await.unwrap();
16635            assert!(runner.state.interrupted_implementations.is_empty());
16636            assert!(runner.state.candidate_preservation.is_empty());
16637            assert_eq!(runner.state.candidates[0].commits, 1);
16638            assert!(!runner.state.candidates[0].empty);
16639            assert!(
16640                std::fs::read_to_string(runner.state.candidates[0].worktree.join("retry-source"))
16641                    .unwrap()
16642                    .contains("retried empty interrupted seat")
16643            );
16644            if !solo {
16645                assert_eq!(runner.state.candidates[1].commits, 1);
16646            }
16647        }
16648    }
16649
16650    #[tokio::test]
16651    #[cfg(unix)]
16652    async fn disk_interrupted_implementation_preserves_edits_and_commits_before_resource_hold() {
16653        for (committed, block_rescue) in [(false, false), (false, true), (true, false)] {
16654            let (_tmp, mut runner) = preservation_resume_fixture().await;
16655            runner.state.candidates.retain(|c| c.label == 'A');
16656            runner.state.candidates[0].empty = false;
16657            runner.state.candidates[0].summary.clear();
16658            runner.state.tally = None;
16659            runner.state.judge_skipped = false;
16660            runner.state.status = RunStatus::Implementing;
16661            // Force only the real post-spawn watchdog, without failing the
16662            // separate admission check. Existing edits predate its measurement.
16663            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
16664            let wt = runner.state.candidates[0].worktree.clone();
16665            std::fs::write(
16666                wt.join("interrupted-source"),
16667                "retain implementation work\n",
16668            )
16669            .unwrap();
16670            if committed {
16671                git::rescue_commit(&wt, "implementation checkpoint")
16672                    .await
16673                    .unwrap();
16674            }
16675            let lock = git::git(
16676                &wt,
16677                &[
16678                    "rev-parse",
16679                    "--path-format=absolute",
16680                    "--git-path",
16681                    "index.lock",
16682                ],
16683            )
16684            .await
16685            .unwrap();
16686            if block_rescue {
16687                std::fs::write(&lock, "fixture-owned lock").unwrap();
16688            }
16689            let mut implementer = spec("alpha");
16690            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
16691            runner.roles.implementers = vec![implementer];
16692            runner.state.save().unwrap();
16693            let result = runner.implement().await;
16694            drop(pressure);
16695            assert_eq!(result.is_err(), block_rescue);
16696            assert_eq!(
16697                runner.state.resource_block.as_ref().unwrap().kind,
16698                "disk pressure"
16699            );
16700            assert!(
16701                runner
16702                    .state
16703                    .events
16704                    .iter()
16705                    .any(|e| e.message.contains("agent execution interrupted"))
16706            );
16707            assert!(
16708                runner
16709                    .state
16710                    .dir()
16711                    .join("artifacts/candidate-A-recovery/staged.patch")
16712                    .exists()
16713            );
16714            if block_rescue {
16715                let saved = RunState::load(&runner.state.id).unwrap();
16716                assert!(saved.candidate_preservation.contains_key(&'A'));
16717                assert!(!saved.candidates[0].empty);
16718                assert_eq!(
16719                    std::fs::read_to_string(wt.join("interrupted-source")).unwrap(),
16720                    "retain implementation work\n"
16721                );
16722                std::fs::remove_file(lock).unwrap();
16723                runner.state = saved;
16724            } else {
16725                assert_eq!(runner.state.status, RunStatus::Blocked);
16726                assert_eq!(runner.state.candidates[0].commits, 1);
16727            }
16728            // Recovery must save the candidate before deciding whether another
16729            // implementation is needed. No implementer is available on retry.
16730            runner.roles.implementers.clear();
16731            runner.state.config.disk.min_free_bytes = 0;
16732            runner.state.resource_block = None;
16733            runner.implement().await.unwrap();
16734            assert!(runner.state.candidate_preservation.is_empty());
16735            assert_eq!(runner.state.candidates[0].commits, 1);
16736            assert!(!runner.state.candidates[0].empty);
16737            assert!(git::is_clean(&wt).await.unwrap());
16738            assert!(
16739                crate::run::read_artifact(&runner.state, "cand-A.patch")
16740                    .unwrap()
16741                    .contains("retain implementation work")
16742            );
16743        }
16744    }
16745
16746    #[tokio::test]
16747    async fn candidate_preservation_does_not_reflag_confirmed_or_folded_empty_candidates() {
16748        let (_tmp, mut runner) = preservation_resume_fixture().await;
16749        // Schema 15 already confirmed the unfolded no-change result.
16750        runner.implement().await.unwrap();
16751        assert!(runner.state.candidate_preservation.is_empty());
16752        assert!(
16753            !runner
16754                .state
16755                .dir()
16756                .join("artifacts/candidate-A-recovery")
16757                .exists()
16758        );
16759        runner.fold_losers().await.unwrap();
16760        assert!(!runner.state.candidates[0].worktree.exists());
16761        for schema in [14, crate::run::SCHEMA] {
16762            runner.state.schema = schema;
16763            runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
16764            runner.state.save().unwrap();
16765            runner.state = RunState::load(&runner.state.id).unwrap();
16766            runner.implement().await.unwrap();
16767            assert!(runner.state.candidate_preservation.is_empty());
16768            assert!(runner.state.candidates[0].folded);
16769            assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
16770        }
16771    }
16772
16773    #[tokio::test]
16774    async fn infrastructure_failure_report_retains_eligible_candidate_edits() {
16775        let (_tmp, mut runner) = preservation_resume_fixture().await;
16776        runner.state.candidates.retain(|c| c.label == 'A');
16777        runner.state.tally = None;
16778        runner.state.judge_skipped = false;
16779        let candidate = &mut runner.state.candidates[0];
16780        candidate.summary = "Reproduction bind denied with EPERM; source repair complete, deployed browser validation remains parent-owned.".into();
16781        candidate.failed = Some("deployment validation unavailable".into());
16782        std::fs::write(
16783            candidate.worktree.join("repair"),
16784            "future launcher policy\n",
16785        )
16786        .unwrap();
16787        runner
16788            .state
16789            .candidate_preservation
16790            .insert('A', "awaiting persistence".into());
16791        runner.persist_candidates().await.unwrap();
16792        let candidate = &runner.state.candidates[0];
16793        assert!(!candidate.empty);
16794        assert_eq!(candidate.commits, 1);
16795        assert_eq!(candidate.files, 1);
16796        assert!(candidate.failed.is_none());
16797        assert!(candidate.summary.contains("EPERM"));
16798        assert!(
16799            crate::run::read_artifact(&runner.state, "cand-A.patch")
16800                .unwrap()
16801                .contains("future launcher policy")
16802        );
16803        assert!(runner.state.candidate_preservation.is_empty());
16804    }
16805
16806    #[tokio::test]
16807    async fn candidate_preservation_legacy_recovery_blocks_stale_verdict_on_every_resume() {
16808        let (_tmp, mut runner) = preservation_resume_fixture().await;
16809        let wt = runner.state.candidates[0].worktree.clone();
16810        std::fs::write(wt.join("recovered"), "owned edits").unwrap();
16811        runner.state.schema = 14;
16812        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
16813        assert!(runner.state.candidate_preservation.contains_key(&'A'));
16814        let tally = serde_json::to_value(&runner.state.tally).unwrap();
16815        for _ in 0..2 {
16816            assert!(runner.implement().await.is_err());
16817            assert_eq!(runner.state.status, RunStatus::Blocked);
16818            assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
16819            assert!(
16820                runner.state.candidates[0].empty,
16821                "old verdict must remain unusable"
16822            );
16823            assert_eq!(serde_json::to_value(&runner.state.tally).unwrap(), tally);
16824            assert!(runner.state.judge_skipped);
16825            assert!(runner.state.judgements.is_empty() && runner.state.votes.is_empty());
16826            assert!(
16827                crate::run::read_artifact(&runner.state, "cand-A.patch")
16828                    .unwrap()
16829                    .contains("owned edits")
16830            );
16831            assert!(wt.exists());
16832            assert_eq!(
16833                git::commits_ahead(&wt, &runner.state.base_commit, "HEAD")
16834                    .await
16835                    .unwrap(),
16836                1
16837            );
16838            runner.state = RunState::load(&runner.state.id).unwrap();
16839        }
16840    }
16841
16842    #[tokio::test]
16843    async fn candidate_preservation_legacy_failed_seat_keeps_edits_before_judging() {
16844        let (_tmp, mut runner) = preservation_resume_fixture().await;
16845        let wt = runner.state.candidates[0].worktree.clone();
16846        runner.state.candidates[0].failed = Some("CLI failed before commit".into());
16847        std::fs::write(wt.join("recovered"), "failed seat edits").unwrap();
16848        let index_lock = PathBuf::from(
16849            git::git(
16850                &wt,
16851                &[
16852                    "rev-parse",
16853                    "--path-format=absolute",
16854                    "--git-path",
16855                    "index.lock",
16856                ],
16857            )
16858            .await
16859            .unwrap(),
16860        );
16861        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
16862        runner.state.schema = 14;
16863        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
16864        assert!(runner.state.candidate_preservation.contains_key(&'A'));
16865        assert!(runner.implement().await.is_err());
16866        assert!(runner.after_implement().is_err());
16867        assert!(runner.fold_losers().await.is_err());
16868        assert_eq!(
16869            std::fs::read_to_string(wt.join("recovered")).unwrap(),
16870            "failed seat edits"
16871        );
16872        assert!(runner.state.candidate_preservation.contains_key(&'A'));
16873        runner.state = RunState::load(&runner.state.id).unwrap();
16874        std::fs::remove_file(index_lock).unwrap();
16875        // Recovery finds changes that the old uncontested result never judged.
16876        assert!(runner.implement().await.is_err());
16877        assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
16878        assert!(runner.state.candidates[0].empty);
16879        assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
16880        assert!(
16881            crate::run::read_artifact(&runner.state, "cand-A.patch")
16882                .unwrap()
16883                .contains("failed seat edits")
16884        );
16885        assert!(wt.exists());
16886    }
16887
16888    #[tokio::test]
16889    async fn candidate_preservation_loser_cleanup_resumes_after_branch_and_judge_failures() {
16890        let (_tmp, mut runner) = preservation_resume_fixture().await;
16891        let repo = runner.state.repo.clone();
16892        let common = git::git(
16893            &repo,
16894            &["rev-parse", "--path-format=absolute", "--git-common-dir"],
16895        )
16896        .await
16897        .unwrap();
16898        let branch_lock = PathBuf::from(common).join("refs/heads/candidate-A.lock");
16899        std::fs::write(&branch_lock, "fixture-owned lock").unwrap();
16900        assert!(runner.fold_losers().await.is_err());
16901        assert!(!runner.state.candidates[0].worktree.exists());
16902        assert!(!runner.state.candidates[0].folded);
16903        assert!(git::branch_exists(&repo, "candidate-A").await.unwrap());
16904        runner.state = RunState::load(&runner.state.id).unwrap();
16905        std::fs::remove_file(branch_lock).unwrap();
16906        let judge = runner.state.worktree_root().join("judge-1");
16907        git::worktree_add_detached(&repo, &judge, "main")
16908            .await
16909            .unwrap();
16910        std::fs::write(judge.join("uncommitted"), "retain").unwrap();
16911        git::git(&repo, &["worktree", "lock", &git::path_arg(&judge)])
16912            .await
16913            .unwrap();
16914        runner.roles.judges = vec![spec("judge")];
16915        assert!(runner.fold_losers().await.is_err());
16916        runner.state = RunState::load(&runner.state.id).unwrap();
16917        assert!(
16918            runner.state.candidates[0].folded,
16919            "candidate progress saved before judge failure"
16920        );
16921        assert!(!git::branch_exists(&repo, "candidate-A").await.unwrap());
16922        assert!(judge.join("uncommitted").exists());
16923        git::git(&repo, &["worktree", "unlock", &git::path_arg(&judge)])
16924            .await
16925            .unwrap();
16926        runner.fold_losers().await.unwrap();
16927        assert!(!judge.exists());
16928        runner.fold_losers().await.unwrap();
16929    }
16930
16931    #[tokio::test]
16932    async fn candidate_preservation_selected_implementer_resumes_through_execute_graph() {
16933        let (_tmp, mut runner) = preservation_resume_fixture().await;
16934        runner.state.candidates.retain(|c| c.label == 'B');
16935        runner.state.tally = None;
16936        runner.state.judge_skipped = false;
16937        runner.state.prep_complete = Some(true);
16938        runner.state.config.graph.advise = false;
16939        runner.state.config.graph.selected_implementer = Some("alpha".into());
16940        let wt = runner.state.candidates[0].worktree.clone();
16941        std::fs::write(wt.join("leftover"), "completed implementation").unwrap();
16942        runner
16943            .state
16944            .candidate_preservation
16945            .insert('B', "awaiting persistence".into());
16946        let index_lock = git::git(
16947            &wt,
16948            &[
16949                "rev-parse",
16950                "--path-format=absolute",
16951                "--git-path",
16952                "index.lock",
16953            ],
16954        )
16955        .await
16956        .unwrap();
16957        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
16958        runner.state.save().unwrap();
16959        assert!(runner.execute_graph().await.is_err());
16960        assert_eq!(runner.state.status, RunStatus::Blocked);
16961        assert!(runner.state.candidate_preservation.contains_key(&'B'));
16962        std::fs::remove_file(index_lock).unwrap();
16963        // Park at the next graph boundary: this tests the real selected-seat
16964        // hold guard without dispatching reviewers or publishing anything.
16965        for _ in 0..2 {
16966            runner.state = RunState::load(&runner.state.id).unwrap();
16967            runner.pause.park();
16968            runner.execute_graph().await.unwrap();
16969            assert_eq!(runner.state.status, RunStatus::Implementing);
16970            assert!(runner.state.candidate_preservation.is_empty());
16971            assert_eq!(runner.state.candidates[0].commits, 2);
16972            assert!(runner.state.tally.is_none());
16973        }
16974        runner.implement().await.unwrap();
16975        assert_eq!(runner.state.status, RunStatus::Judging);
16976        // A genuine selected-implementer hold must still require release.
16977        runner.state.status = RunStatus::Blocked;
16978        runner.state.candidates[0].failed = Some("implementation failed".into());
16979        runner.state.save().unwrap();
16980        let error = runner.execute_graph().await.unwrap_err();
16981        assert!(
16982            error
16983                .to_string()
16984                .contains("selected implementation is held")
16985        );
16986    }
16987
16988    #[tokio::test]
16989    async fn candidate_preservation_cleanup_unregisters_a_vanished_worktree() {
16990        let (_tmp, mut runner) = preservation_resume_fixture().await;
16991        let repo = runner.state.repo.clone();
16992        let candidate = runner.state.candidates[0].clone();
16993        // Remove only the disposable fixture directory, leaving Git's linked
16994        // worktree registration and branch intact, as in a vanished checkout.
16995        let registered = git::worktree_holding(&repo, &candidate.branch)
16996            .await
16997            .unwrap()
16998            .unwrap();
16999        assert_eq!(
17000            registered.canonicalize().unwrap(),
17001            candidate.worktree.canonicalize().unwrap()
17002        );
17003        std::fs::remove_dir_all(&candidate.worktree).unwrap();
17004        assert_eq!(
17005            git::worktree_holding(&repo, &candidate.branch)
17006                .await
17007                .unwrap(),
17008            Some(registered)
17009        );
17010        assert!(
17011            !git::branch_delete(&repo, &candidate.branch).await.unwrap(),
17012            "the stale registration initially keeps the branch checked out"
17013        );
17014        runner.fold_losers().await.unwrap();
17015        assert!(runner.state.candidates[0].folded);
17016        assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
17017        assert_eq!(
17018            git::worktree_holding(&repo, &candidate.branch)
17019                .await
17020                .unwrap(),
17021            None
17022        );
17023        runner.state = RunState::load(&runner.state.id).unwrap();
17024        runner.fold_losers().await.unwrap();
17025    }
17026
17027    #[tokio::test]
17028    async fn fold_run_unregisters_a_vanished_worktree_and_can_retry() {
17029        let (_tmp, mut runner) = preservation_resume_fixture().await;
17030        let repo = runner.state.repo.clone();
17031        let candidate = runner.state.candidates[0].clone();
17032        let winner = runner.state.candidates[1].clone();
17033        let registered = git::worktree_holding(&repo, &candidate.branch)
17034            .await
17035            .unwrap()
17036            .unwrap();
17037        assert_eq!(
17038            registered.canonicalize().unwrap(),
17039            candidate.worktree.canonicalize().unwrap()
17040        );
17041        std::fs::remove_dir_all(&candidate.worktree).unwrap();
17042        assert_eq!(
17043            git::worktree_holding(&repo, &candidate.branch)
17044                .await
17045                .unwrap(),
17046            Some(registered)
17047        );
17048        assert!(!git::branch_delete(&repo, &candidate.branch).await.unwrap());
17049
17050        for _ in 0..2 {
17051            fold_run(&mut runner.state, false, &crate::run::home())
17052                .await
17053                .unwrap();
17054            runner.state = RunState::load(&runner.state.id).unwrap();
17055            assert!(runner.state.candidates[0].folded);
17056            assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
17057            assert_eq!(
17058                git::worktree_holding(&repo, &candidate.branch)
17059                    .await
17060                    .unwrap(),
17061                None
17062            );
17063            assert!(!runner.state.candidates[1].folded);
17064            assert!(winner.worktree.exists());
17065            assert!(git::branch_exists(&repo, &winner.branch).await.unwrap());
17066        }
17067    }
17068    #[tokio::test]
17069    async fn fold_recovery_override_archives_sources_and_keeps_safety_checks() {
17070        for sidecar in [false, true] {
17071            let tmp = tempfile::tempdir().unwrap();
17072            let home = tmp.path().join("home");
17073            let repo = tmp.path().join("repo");
17074            std::fs::create_dir(&repo).unwrap();
17075            init_repo(&repo);
17076            let mut state = runner_at(RunStatus::Superseded).state;
17077            state.repo = repo.clone();
17078            state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17079            state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17080            state.driver_exited = true;
17081            state.reserve_under(&home).unwrap();
17082            git::git(
17083                &repo,
17084                &["update-ref", "refs/remotes/origin/main", &state.base_commit],
17085            )
17086            .await
17087            .unwrap();
17088            let wt = state.worktree_root().join("cand-A");
17089            git::worktree_add_branch(&repo, &wt, "candidate", "main")
17090                .await
17091                .unwrap();
17092            std::fs::write(wt.join("independent"), "retained implementation\n").unwrap();
17093            git::commit_all(&wt, "fixture: independent source")
17094                .await
17095                .unwrap();
17096            let head = git::rev_parse(&wt, "HEAD").await.unwrap();
17097            state.candidates.push(Candidate {
17098                index: 0,
17099                label: 'A',
17100                agent: "fixture".into(),
17101                branch: "candidate".into(),
17102                worktree: wt.clone(),
17103                summary: String::new(),
17104                stat: String::new(),
17105                files: 0,
17106                commits: 0,
17107                empty: false,
17108                failed: None,
17109                verified_noop: None,
17110                duration_ms: 0,
17111                folded: false,
17112            });
17113            let mut task = crate::queue::Task::new(
17114                "task".into(),
17115                "task".into(),
17116                repo.clone(),
17117                crate::queue::Source::Human,
17118            );
17119            task.runs.push(state.id.clone());
17120            crate::queue::Queue::at(home.join("queue"))
17121                .put(&mut task)
17122                .unwrap();
17123            if sidecar {
17124                crate::pr_recovery::retain_sources(&task, &home).unwrap();
17125            }
17126            state.save_under(&home).unwrap();
17127            let reason = crate::pr_recovery::source_retention_reason(&home, &state).unwrap();
17128            assert!(
17129                fold_run(&mut state, true, &home)
17130                    .await
17131                    .unwrap_err()
17132                    .to_string()
17133                    .contains(&reason)
17134            );
17135            let mut disk = state.config.disk.clone();
17136            disk.fold_grace_secs = 0;
17137            assert_eq!(
17138                crate::clean::fold_due(
17139                    &home.join("runs"),
17140                    &home,
17141                    &state.worktree_root(),
17142                    &disk,
17143                    Timestamp::now() + std::time::Duration::from_secs(10),
17144                )
17145                .await
17146                .unwrap(),
17147                (0, 0)
17148            );
17149            assert!(wt.exists());
17150            state.status = RunStatus::Blocked;
17151            state.save_under(&home).unwrap();
17152            assert!(
17153                fold_run_overriding_recovery_retention(&mut state, true, &home)
17154                    .await
17155                    .is_err()
17156            );
17157            state.status = RunStatus::Superseded;
17158            state.driver_exited = false;
17159            state.driver_claimed = None;
17160            state.save_under(&home).unwrap();
17161            assert!(
17162                fold_run_overriding_recovery_retention(&mut state, true, &home)
17163                    .await
17164                    .is_err()
17165            );
17166            state.driver_pid = Some(std::process::id());
17167            state.driver_started_at = crate::proc::process_started_at(std::process::id());
17168            state.save_under(&home).unwrap();
17169            assert!(
17170                fold_run_overriding_recovery_retention(&mut state, true, &home)
17171                    .await
17172                    .is_err()
17173            );
17174            state.driver_exited = true;
17175            state.driver_pid = None;
17176            state.driver_started_at = None;
17177            state.save_under(&home).unwrap();
17178            let lease = crate::driver::maintenance(&home, &state.id).unwrap();
17179            assert!(
17180                fold_run_overriding_recovery_retention(&mut state, true, &home)
17181                    .await
17182                    .is_err()
17183            );
17184            drop(lease);
17185            #[cfg(unix)]
17186            {
17187                let output = crate::retention::OutputLease::take(&wt, false).unwrap();
17188                assert!(
17189                    fold_run_overriding_recovery_retention(&mut state, true, &home)
17190                        .await
17191                        .is_err()
17192                );
17193                drop(output);
17194            }
17195            let owner = crate::pr_head::owner_lock(&home, &state.id).unwrap();
17196            assert!(
17197                fold_run_overriding_recovery_retention(&mut state, true, &home)
17198                    .await
17199                    .is_err()
17200            );
17201            drop(owner);
17202            let checkpoint = git::git(
17203                &wt,
17204                &[
17205                    "rev-parse",
17206                    "--path-format=absolute",
17207                    "--git-path",
17208                    "CHERRY_PICK_HEAD",
17209                ],
17210            )
17211            .await
17212            .unwrap();
17213            std::fs::write(&checkpoint, &head).unwrap();
17214            assert!(
17215                fold_run_overriding_recovery_retention(&mut state, true, &home)
17216                    .await
17217                    .is_err()
17218            );
17219            std::fs::remove_file(checkpoint).unwrap();
17220            std::fs::write(wt.join("dirty"), "keep").unwrap();
17221            assert!(
17222                fold_run_overriding_recovery_retention(&mut state, true, &home)
17223                    .await
17224                    .is_err()
17225            );
17226            assert!(wt.join("dirty").exists());
17227            std::fs::remove_file(wt.join("dirty")).unwrap();
17228            let evidence = home
17229                .join("runs")
17230                .join(&state.id)
17231                .join("artifacts/fold-evidence");
17232            std::fs::create_dir_all(evidence.parent().unwrap()).unwrap();
17233            std::fs::write(&evidence, "blocked archive").unwrap();
17234            assert!(
17235                fold_run_overriding_recovery_retention(&mut state, true, &home)
17236                    .await
17237                    .is_err()
17238            );
17239            assert!(wt.exists());
17240            assert!(
17241                !RunState::load_under(&state.id, &home)
17242                    .unwrap()
17243                    .events
17244                    .iter()
17245                    .any(|event| event.message.contains("--override-recovery-retention"))
17246            );
17247            std::fs::remove_file(&evidence).unwrap();
17248            fold_run_overriding_recovery_retention(&mut state, true, &home)
17249                .await
17250                .unwrap();
17251            assert!(!wt.exists());
17252            assert!(!git::branch_exists(&repo, "candidate").await.unwrap());
17253            assert!(
17254                git::worktree_holding(&repo, "candidate")
17255                    .await
17256                    .unwrap()
17257                    .is_none()
17258            );
17259            assert!(
17260                std::fs::read_to_string(evidence.join(format!("{head}.patch")))
17261                    .unwrap()
17262                    .contains("retained implementation")
17263            );
17264            assert!(evidence.join(format!("{head}.index")).is_file());
17265            let saved = RunState::load_under(&state.id, &home).unwrap();
17266            assert_eq!(saved.status, RunStatus::Superseded);
17267            assert!(saved.candidates[0].folded);
17268            assert!(saved.events.iter().any(|event| {
17269                event.message.contains("--override-recovery-retention")
17270                    && event.message.contains(&state.id)
17271                    && event.message.contains(&reason)
17272            }));
17273            assert_eq!(
17274                crate::pr_recovery::explicit_sources_retained(&home, &state.id),
17275                sidecar
17276            );
17277        }
17278    }
17279
17280    #[tokio::test]
17281    async fn candidate_preservation_retries_after_upgrade_without_rerunning_seats() {
17282        ask_test_home();
17283        let tmp = tempfile::tempdir().unwrap();
17284        let repo = tmp.path().join("repo");
17285        std::fs::create_dir(&repo).unwrap();
17286        init_repo(&repo);
17287        let mut runner = runner_at(RunStatus::Implementing);
17288        runner.state.repo = repo.clone();
17289        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17290        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17291        for (index, label) in ['A', 'B'].into_iter().enumerate() {
17292            let branch = format!("candidate-{label}");
17293            let wt = runner.state.worktree_root().join(format!("cand-{label}"));
17294            git::worktree_add_branch(&repo, &wt, &branch, "main")
17295                .await
17296                .unwrap();
17297            std::fs::write(wt.join("README.md"), "tracked edits\n").unwrap();
17298            git::git(&wt, &["add", "README.md"]).await.unwrap();
17299            std::fs::write(wt.join("README.md"), "later tracked edits\n").unwrap();
17300            std::fs::write(wt.join("new-file"), "untracked edits\n").unwrap();
17301            runner.state.candidates.push(Candidate {
17302                index,
17303                label,
17304                agent: "alpha".to_owned(),
17305                branch,
17306                worktree: wt,
17307                summary: "completed implementation".to_owned(),
17308                stat: String::new(),
17309                files: 0,
17310                commits: 0,
17311                empty: false,
17312                failed: None,
17313                verified_noop: None,
17314                duration_ms: 42,
17315                folded: false,
17316            });
17317            runner
17318                .state
17319                .candidate_preservation
17320                .insert(label, "awaiting persistence".to_owned());
17321        }
17322        let wt = runner.state.candidates[0].worktree.clone();
17323        let index_lock = git::git(
17324            &wt,
17325            &[
17326                "rev-parse",
17327                "--path-format=absolute",
17328                "--git-path",
17329                "index.lock",
17330            ],
17331        )
17332        .await
17333        .unwrap();
17334        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
17335        runner.state.save().unwrap();
17336        assert!(runner.persist_candidates().await.is_err());
17337        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17338        assert!(!runner.state.candidate_preservation.contains_key(&'B'));
17339        assert_eq!(
17340            runner.state.candidates[1].commits, 1,
17341            "other results are still collected"
17342        );
17343        assert!(
17344            !runner.state.candidates[0].empty,
17345            "failed rescue is not no change"
17346        );
17347        assert_eq!(
17348            runner.state.candidates[0].summary,
17349            "completed implementation"
17350        );
17351        assert!(runner.after_implement().is_err());
17352        let home = tmp.path().join("fold-home");
17353        assert!(fold_run(&mut runner.state, true, &home).await.is_err());
17354        assert!(wt.join("new-file").exists());
17355        let recovery = runner.state.dir().join("artifacts/candidate-A-recovery");
17356        assert!(recovery.join("staged.patch").exists());
17357        assert!(recovery.join("unstaged.patch").exists());
17358        assert_eq!(
17359            std::fs::read_to_string(recovery.join("untracked/new-file")).unwrap(),
17360            "untracked edits\n"
17361        );
17362        runner.state.begin_pass();
17363        runner.state.end_pass_parked(ParkCause::Upgrade {
17364            from: "1.0".into(),
17365            to: Some("1.1".into()),
17366        });
17367        runner.state.save().unwrap();
17368        runner.state = RunState::load(&runner.state.id).unwrap();
17369        assert!(matches!(
17370            runner.state.passes.last().unwrap().end,
17371            Some(crate::run::PassEnd::Parked {
17372                cause: ParkCause::Upgrade { .. }
17373            })
17374        ));
17375        std::fs::remove_file(index_lock).unwrap();
17376        // No implementer is configured: a persistence retry cannot dispatch a seat.
17377        runner.implement().await.unwrap();
17378        assert!(runner.state.candidate_preservation.is_empty());
17379        assert!(
17380            runner
17381                .state
17382                .candidates
17383                .iter()
17384                .all(|c| c.commits == 1 && !c.empty)
17385        );
17386        assert!(git::is_clean(&wt).await.unwrap());
17387        assert!(
17388            crate::run::read_artifact(&runner.state, "cand-A.patch")
17389                .unwrap()
17390                .contains("later tracked edits")
17391        );
17392    }
17393
17394    #[tokio::test]
17395    async fn candidate_preservation_git_read_and_cleanup_fail_closed() {
17396        ask_test_home();
17397        let tmp = tempfile::tempdir().unwrap();
17398        let repo = tmp.path().join("repo");
17399        std::fs::create_dir(&repo).unwrap();
17400        init_repo(&repo);
17401        let wt = tmp.path().join("candidate");
17402        git::worktree_add_branch(&repo, &wt, "candidate", "main")
17403            .await
17404            .unwrap();
17405        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
17406        assert!(remove_preserved_worktree(&repo, &wt).await.is_err());
17407        assert!(wt.join("uncommitted").exists());
17408        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
17409        std::fs::remove_file(wt.join("uncommitted")).unwrap();
17410        let mut runner = runner_at(RunStatus::Implementing);
17411        runner.state.repo = repo.clone();
17412        runner.state.base_commit = "missing-base".to_owned();
17413        runner.state.candidates.push(Candidate {
17414            index: 0,
17415            label: 'A',
17416            agent: "alpha".into(),
17417            branch: "candidate".into(),
17418            worktree: wt.clone(),
17419            summary: "completed".into(),
17420            stat: String::new(),
17421            files: 0,
17422            commits: 0,
17423            empty: false,
17424            failed: None,
17425            verified_noop: None,
17426            duration_ms: 1,
17427            folded: false,
17428        });
17429        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
17430        assert!(
17431            fold_run(&mut runner.state, true, &tmp.path().join("home"))
17432                .await
17433                .is_err()
17434        );
17435        assert!(!runner.state.candidates[0].folded);
17436        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
17437        std::fs::remove_file(wt.join("uncommitted")).unwrap();
17438        runner
17439            .state
17440            .candidate_preservation
17441            .insert('A', "pending".into());
17442        assert!(runner.persist_candidates().await.is_err());
17443        assert!(!runner.state.candidates[0].empty);
17444        assert!(!runner.state.candidates[0].folded);
17445        assert!(wt.exists());
17446        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17447        let patch_path = runner.state.dir().join("artifacts/cand-A.patch");
17448        std::fs::create_dir_all(&patch_path).unwrap();
17449        assert!(
17450            runner.persist_candidates().await.is_err(),
17451            "artifact failure stays pending"
17452        );
17453        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17454        assert!(!runner.state.candidates[0].empty);
17455        std::fs::remove_dir(patch_path).unwrap();
17456        runner.persist_candidates().await.unwrap();
17457        assert!(
17458            runner.state.candidates[0].empty,
17459            "only successful inspection confirms no change"
17460        );
17461    }
17462
17463    fn init_repo(dir: &Path) {
17464        let run = |args: &[&str]| {
17465            let out = std::process::Command::new("git")
17466                .args(args)
17467                .current_dir(dir)
17468                .quiet()
17469                .output()
17470                .expect("spawn git");
17471            assert!(
17472                out.status.success(),
17473                "git {args:?} failed: {}",
17474                String::from_utf8_lossy(&out.stderr)
17475            );
17476        };
17477        run(&["init", "-b", "main"]);
17478        run(&["config", "user.name", "magi test"]);
17479        run(&["config", "user.email", "magi@example.com"]);
17480        std::fs::write(dir.join("README.md"), "# fixture\n").unwrap();
17481        run(&["add", "-A"]);
17482        run(&["commit", "-m", "init"]);
17483    }
17484
17485    // `settle_questions` is what closes the ghost the phone showed: a run's
17486    // seat asked something, the run then ended, and nothing was left to
17487    // abandon the question it left `open`. `HOME` is a process-wide
17488    // `OnceLock` (see `run::set_home`'s doc), so this only wins the race the
17489    // first time it runs in the binary — every test below still reaches the
17490    // same directory whichever call won, and each gets its own run id from
17491    // `RunState::new`, so they never collide there.
17492    fn ask_test_home() {
17493        crate::run::pin_test_home();
17494    }
17495
17496    #[test]
17497    fn startup_terminal_save_failure_preserves_original_error_and_reservation() {
17498        ask_test_home();
17499        let mut runner = runner_at(RunStatus::Prep);
17500        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
17501        // A blocked temporary output path makes the terminal save fail while
17502        // preserving the already published reservation.
17503        std::fs::create_dir(runner.state.dir().join("run.json.tmp")).unwrap();
17504        let error = guard
17505            .finish(
17506                &mut runner.state,
17507                Err(
17508                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "original refusal")
17509                        .into(),
17510                ),
17511            )
17512            .unwrap_err();
17513        assert_eq!(
17514            error.downcast_ref::<std::io::Error>().unwrap().kind(),
17515            std::io::ErrorKind::PermissionDenied
17516        );
17517        assert!(error.downcast_ref::<crate::run::StartupFailure>().is_some());
17518        let message = format!("{error:#}");
17519        assert!(message.contains("original refusal"));
17520        assert!(!message.contains("could not save terminal"));
17521        assert_eq!(
17522            error.chain().count(),
17523            2,
17524            "only startup attribution wraps the original error"
17525        );
17526        let saved = RunState::load(&runner.state.id).unwrap();
17527        assert_eq!(saved.status, RunStatus::Blocked);
17528        assert!(!saved.startup.unwrap().complete);
17529    }
17530
17531    #[test]
17532    fn reserved_startup_interruption_is_blocked_and_not_resumable() {
17533        ask_test_home();
17534        let mut runner = runner_at(RunStatus::Prep);
17535        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
17536        let id = runner.state.id.clone();
17537        drop(guard);
17538        let saved = RunState::load(&id).unwrap();
17539        assert_eq!(saved.status, RunStatus::Blocked);
17540        assert!(!saved.startup.as_ref().unwrap().complete);
17541        assert!(
17542            saved
17543                .startup
17544                .unwrap()
17545                .failure
17546                .unwrap()
17547                .contains("interrupted")
17548        );
17549        assert!(Runner::resume(&id).is_err());
17550    }
17551
17552    #[test]
17553    fn startup_failure_keeps_typed_cause_and_separate_task_history() {
17554        ask_test_home();
17555        let mut runner = runner_at(RunStatus::Prep);
17556        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
17557        let error = guard
17558            .finish(
17559                &mut runner.state,
17560                Err(
17561                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "refused startup")
17562                        .into(),
17563                ),
17564            )
17565            .unwrap_err();
17566        assert_eq!(
17567            error.downcast_ref::<std::io::Error>().unwrap().kind(),
17568            std::io::ErrorKind::PermissionDenied
17569        );
17570        let failure = error.downcast_ref::<crate::run::StartupFailure>().unwrap();
17571        let mut task = crate::queue::Task::new(
17572            "review".into(),
17573            "criteria".into(),
17574            runner.state.repo.clone(),
17575            crate::queue::Source::Human,
17576        );
17577        task.record_startup_failure(failure.clone());
17578        task.record_startup_failure(failure.clone());
17579        assert_eq!(task.startup_failures.len(), 1);
17580        assert!(task.runs.is_empty());
17581        assert_eq!(task.attempts, 0);
17582    }
17583
17584    async fn exhausted_base_fixture() -> (tempfile::TempDir, Runner, String, String) {
17585        ask_test_home();
17586        let tmp = tempfile::tempdir().unwrap();
17587        let repo = tmp.path().join("repo");
17588        std::fs::create_dir(&repo).unwrap();
17589        init_repo(&repo);
17590        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
17591        let origin = tmp.path().join("origin.git");
17592        git::git(&repo, &["init", "--bare", origin.to_str().unwrap()])
17593            .await
17594            .unwrap();
17595        git::git(
17596            &repo,
17597            &["remote", "add", "origin", origin.to_str().unwrap()],
17598        )
17599        .await
17600        .unwrap();
17601        git::git(&repo, &["checkout", "-b", "fix/retained"])
17602            .await
17603            .unwrap();
17604        std::fs::write(repo.join("retained"), "retained change").unwrap();
17605        git::git(&repo, &["add", "."]).await.unwrap();
17606        git::git(&repo, &["commit", "-m", "retained implementation"])
17607            .await
17608            .unwrap();
17609        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
17610        git::git(&repo, &["checkout", "main"]).await.unwrap();
17611        std::fs::write(repo.join("base-change"), "new base").unwrap();
17612        git::git(&repo, &["add", "."]).await.unwrap();
17613        git::git(&repo, &["commit", "-m", "base moved"])
17614            .await
17615            .unwrap();
17616        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
17617        git::git(&repo, &["checkout", "fix/retained"])
17618            .await
17619            .unwrap();
17620        let mut runner = runner_at(RunStatus::Voting);
17621        runner.state.repo = repo.clone();
17622        runner.state.base_commit = base;
17623        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
17624        runner.state.config.disk.min_free_bytes = 0;
17625        runner.state.config.graph.review_rounds = 1;
17626        runner.state.config.verify.e2e = vec!["true".into()];
17627        runner.state.config.verify.gate = vec!["true".into()];
17628        runner.state.candidates = vec![Candidate {
17629            index: 0,
17630            label: 'A',
17631            agent: "fixture".into(),
17632            branch: "fix/retained".into(),
17633            worktree: repo.clone(),
17634            summary: String::new(),
17635            stat: String::new(),
17636            files: 1,
17637            commits: 1,
17638            empty: false,
17639            failed: None,
17640            verified_noop: None,
17641            duration_ms: 0,
17642            folded: false,
17643        }];
17644        runner.state.tally = Some(Tally {
17645            first_choice: BTreeMap::new(),
17646            borda: BTreeMap::new(),
17647            winner: 'A',
17648            rankings: 0,
17649            unanimous_initial: true,
17650            deliberated: false,
17651            changed_votes: 0,
17652            unanimous_final: true,
17653            tie_break: None,
17654            judges: 0,
17655            present: 0,
17656            quorum: 0,
17657            met_quorum: true,
17658            uncontested: Some("review-only".into()),
17659        });
17660        let mut task = crate::queue::Task::new(
17661            "fixture".into(),
17662            "fixture".into(),
17663            repo,
17664            crate::queue::Source::Human,
17665        );
17666        task.link_run(&runner.state.id);
17667        crate::queue::Queue::open().put(&mut task).unwrap();
17668        runner.state.origin = Some(crate::run::Origin::queue(&task.id));
17669        runner.state.base_sync = Some(BaseSync {
17670            tip: String::new(),
17671            behind: 1,
17672            attempts: BASE_SYNC_ROUNDS,
17673            conflict: None,
17674            already_in: None,
17675        });
17676        runner.sync_to_base().await.unwrap();
17677        assert_eq!(runner.state.status, RunStatus::Blocked);
17678        (tmp, runner, head, task.id)
17679    }
17680
17681    #[tokio::test]
17682    async fn rebase_preparation_failure_preserves_base_sync_budget_and_resumes() {
17683        let (_tmp, mut runner, head, _task) = exhausted_base_fixture().await;
17684        runner.state.status = RunStatus::Voting;
17685        runner.state.base_sync = None;
17686        runner.state.base_sync_recovery = Default::default();
17687        let scratch = runner.state.dir().join("base-sync");
17688        std::fs::create_dir_all(&scratch).unwrap();
17689        std::fs::write(scratch.join("obstruction"), "keep").unwrap();
17690        runner.sync_to_base().await.unwrap();
17691        assert!(runner.state.resource_block.is_some());
17692        assert!(!runner.state.base_sync_blocked());
17693        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 0);
17694        assert_eq!(runner.state.base_episode_used(), 0);
17695        assert!(runner.state.base_sync_recovery.operations.is_empty());
17696        assert!(runner.state.rebase_fixes.is_empty());
17697        assert_eq!(
17698            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
17699            head
17700        );
17701        std::fs::remove_dir_all(&scratch).unwrap();
17702        runner.state.resource_block = None;
17703        runner.sync_to_base().await.unwrap();
17704        assert!(!runner.state.base_sync_blocked());
17705        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
17706        assert_eq!(runner.state.base_episode_used(), 1);
17707        assert!(runner.state.base_sync_recovery.operations[0].finished);
17708        assert!(runner.state.rebase_fixes.is_empty());
17709        assert!(git::is_ancestor(&runner.state.repo, "origin/main", "HEAD").await);
17710        assert!(git::is_clean(&runner.state.repo).await.unwrap());
17711    }
17712
17713    #[cfg(unix)]
17714    #[tokio::test]
17715    async fn base_recovery_control_rechecks_owner_decision_and_routing_at_consumption() {
17716        for routed in [false, true] {
17717            let (_tmp, mut runner, head, owner) = exhausted_base_fixture().await;
17718            let home = crate::run::home();
17719            let queue = crate::queue::Queue::open();
17720            let task = queue.get(&owner).unwrap();
17721            runner.state.task_instruction = Some(task.instruction.clone());
17722            runner.state.driver_exited = true;
17723            runner.state.save().unwrap();
17724            let questions = crate::ask::Questions::at(home.join("questions"));
17725            let mut q = crate::ask::Question::new(
17726                runner.state.id.clone(),
17727                "base-recovery".into(),
17728                "owner".into(),
17729                "Recover bounded base movement?".into(),
17730                String::new(),
17731                vec!["recover".into()],
17732            );
17733            q.actions.insert(
17734                "recover".into(),
17735                crate::ask::ChoiceAction::RecoverBase {
17736                    run: runner.state.id.clone(),
17737                    stop: runner.state.base_sync_recovery.stop.clone().unwrap(),
17738                    episode: runner.state.base_sync_recovery.episodes.last().unwrap().id,
17739                },
17740            );
17741            q.routed_task = Some(owner.clone());
17742            q.answer(crate::ask::Answer::Choice("recover".into()))
17743                .unwrap();
17744            questions.put(&mut q).unwrap();
17745            crate::base_recovery_control::recover(
17746                &queue,
17747                &home,
17748                crate::base_recovery_control::Request {
17749                    run: runner.state.id.clone(),
17750                    head: head.clone(),
17751                    actor: "decisions".into(),
17752                    request: q.id.clone(),
17753                    decision: Some((owner.clone(), q.answered_at.unwrap())),
17754                    expected_stop: Some((
17755                        runner.state.base_sync_recovery.stop.clone().unwrap(),
17756                        runner.state.base_sync_recovery.episodes.last().unwrap().id,
17757                    )),
17758                },
17759            )
17760            .await
17761            .unwrap();
17762            if routed {
17763                questions
17764                    .update(&q.id, |q| {
17765                        q.routed_task = Some("another-owner".into());
17766                        Ok(())
17767                    })
17768                    .unwrap();
17769            } else {
17770                let mut task = queue.get(&owner).unwrap();
17771                task.hold_manual(Some("new owner decision".into()));
17772                // Keep the generation to exercise the separate owner-decision binding.
17773                task.status = crate::queue::TaskStatus::Queued;
17774                queue.put(&mut task).unwrap();
17775            }
17776            runner.state = RunState::load(&runner.state.id).unwrap();
17777            runner.sync_to_base().await.unwrap();
17778            let approval = runner
17779                .state
17780                .base_sync_recovery
17781                .authorizations
17782                .last()
17783                .unwrap();
17784            assert!(approval.consumed);
17785            assert!(approval.invalidated.as_ref().unwrap().contains(if routed {
17786                "routing"
17787            } else {
17788                "owner decision"
17789            }));
17790            assert_eq!(
17791                runner.state.base_sync.as_ref().unwrap().attempts,
17792                BASE_SYNC_ROUNDS
17793            );
17794            assert_eq!(
17795                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
17796                head
17797            );
17798        }
17799    }
17800
17801    #[cfg(unix)]
17802    #[tokio::test]
17803    async fn base_recovery_authorizes_its_worker_but_rejects_other_workers() {
17804        const CHILD: &str = "MAGI_BASE_RECOVERY_WORKER_TEST";
17805        if std::env::var_os(CHILD).is_none() {
17806            let home = tempfile::tempdir().unwrap();
17807            let output = std::process::Command::new(std::env::current_exe().unwrap())
17808                .args([
17809                    "--exact",
17810                    "graph::tests::base_recovery_authorizes_its_worker_but_rejects_other_workers",
17811                    "--nocapture",
17812                ])
17813                .env(CHILD, "1")
17814                .env("MAGI_HOME", home.path())
17815                .env("MAGI_WORKER_HOME", home.path())
17816                .env("MAGI_WORKER_ID", "abcdef")
17817                .output()
17818                .unwrap();
17819            assert!(
17820                output.status.success()
17821                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
17822                "{}\n{}",
17823                String::from_utf8_lossy(&output.stdout),
17824                String::from_utf8_lossy(&output.stderr)
17825            );
17826            return;
17827        }
17828        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
17829        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
17830        let home = crate::run::home();
17831        let queue = crate::queue::Queue::open();
17832        let mut owner = queue.get(&task).unwrap();
17833        owner.release_operator("test-release", None);
17834        owner.start(runner.state.id.clone());
17835        queue.put(&mut owner).unwrap();
17836        runner.state.driver_exited = true;
17837        runner.state.task_instruction = Some(owner.instruction.clone());
17838        runner.state.save().unwrap();
17839        let _claim = queue.claim(&task).unwrap();
17840        let reserve = |id: &str| {
17841            let directory = home.join("workers/jobs").join(id);
17842            std::fs::create_dir_all(&directory).unwrap();
17843            let job = crate::worker::Job {
17844                id: id.into(),
17845                sequence: 1,
17846                kind: "task".into(),
17847                key: format!("task:{task}"),
17848                payload: serde_json::json!({"opts": crate::daemon::Opts::default(), "queue": queue.root(), "task": task}),
17849                generation: "fixture-generation".into(),
17850                version: None,
17851                status: crate::worker::Status::Running,
17852                result: None,
17853                pid: Some(std::process::id()),
17854                created_at: 0,
17855                finished_at: None,
17856            };
17857            std::fs::write(
17858                directory.join("job.json"),
17859                serde_json::to_vec(&job).unwrap(),
17860            )
17861            .unwrap();
17862            crate::worker::execution_lease_for_test(&directory.join("live.lock"))
17863        };
17864        let _own = reserve("abcdef");
17865        let other = reserve("fedcba");
17866        assert!(
17867            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
17868                .await
17869                .is_err()
17870        );
17871        assert!(
17872            RunState::load(&runner.state.id)
17873                .unwrap()
17874                .base_sync_recovery
17875                .authorizations
17876                .is_empty()
17877        );
17878        drop(other);
17879        assert!(crate::daemon::is_working_on(
17880            &home,
17881            &runner.state.id,
17882            Timestamp::now()
17883        ));
17884        assert!(
17885            !crate::daemon::is_working_on_other(&home, &runner.state.id, Timestamp::now()).unwrap()
17886        );
17887        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
17888            .await
17889            .unwrap();
17890        assert!(
17891            RunState::load(&runner.state.id)
17892                .unwrap()
17893                .base_recovery_pending()
17894        );
17895    }
17896
17897    #[cfg(unix)]
17898    #[tokio::test]
17899    async fn base_recovery_authorizes_a_crashed_driver_with_a_free_matching_lease() {
17900        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
17901        let home = crate::run::home();
17902        runner.state.driver_pid = Some(std::process::id());
17903        runner.state.driver_started_at = crate::proc::process_started_at(std::process::id());
17904        runner.state.driver_exited = false;
17905        runner.state.begin_pass();
17906        runner.state.save().unwrap();
17907        let mut driver = crate::driver::DriverGuard::acquire(&home, &runner.state).unwrap();
17908        driver.record(&runner.state).unwrap();
17909        let saved = std::fs::read(runner.state.dir().join("run.json")).unwrap();
17910        // Preserve the durable claim as if the process died before Drop saved.
17911        drop(driver);
17912        std::fs::write(runner.state.dir().join("run.json"), saved).unwrap();
17913        assert_eq!(
17914            runner.state.liveness_under(&home, false),
17915            crate::run::Liveness::Dead
17916        );
17917        let queue = crate::queue::Queue::open();
17918        let _claim = queue.claim(&task).unwrap();
17919        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
17920            .await
17921            .unwrap();
17922        let disk = RunState::load(&runner.state.id).unwrap();
17923        assert!(!disk.driver_exited);
17924        assert!(disk.base_recovery_pending());
17925    }
17926
17927    #[cfg(unix)]
17928    #[tokio::test]
17929    async fn base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase() {
17930        const CHILD: &str = "MAGI_BASE_RECOVERY_CLOSURE_TEST";
17931        if std::env::var_os(CHILD).is_none() {
17932            use std::os::unix::fs::PermissionsExt;
17933            let tmp = tempfile::tempdir().unwrap();
17934            let gh = tmp.path().join("gh");
17935            std::fs::write(&gh, r#"#!/bin/sh
17936case "$1 $2" in
17937  'pr view') printf '{"headRefName":"fix/retained","headRefOid":"%s","baseRefName":"main","state":"OPEN","isCrossRepository":false}' "$(git rev-parse fix/retained)" ;;
17938  'pr close') if [ ! -f "$MAGI_BASE_CLOSURE_MARKER" ]; then touch "$MAGI_BASE_CLOSURE_MARKER"; echo 'transient closure failure' >&2; exit 1; fi ;;
17939  *) exit 2 ;;
17940esac
17941"#).unwrap();
17942            std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
17943            let mut paths = vec![tmp.path().to_path_buf()];
17944            paths.extend(std::env::split_paths(&std::env::var_os("PATH").unwrap()));
17945            let output = std::process::Command::new(std::env::current_exe().unwrap())
17946                .args(["--exact", "graph::tests::base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase", "--nocapture"])
17947                .env(CHILD, "1")
17948                .env("MAGI_BASE_CLOSURE_MARKER", tmp.path().join("closure-attempted"))
17949                .env("PATH", std::env::join_paths(paths).unwrap())
17950                .env_remove("MAGI_WORKER_HOME").env_remove("MAGI_WORKER_ID")
17951                .output().unwrap();
17952            assert!(
17953                output.status.success()
17954                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
17955                "{}\n{}",
17956                String::from_utf8_lossy(&output.stdout),
17957                String::from_utf8_lossy(&output.stderr)
17958            );
17959            return;
17960        }
17961        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
17962        let repo = runner.state.repo.clone();
17963        git::git(&repo, &["checkout", "main"]).await.unwrap();
17964        git::git(&repo, &["cherry-pick", &head]).await.unwrap();
17965        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
17966        git::git(&repo, &["checkout", "fix/retained"])
17967            .await
17968            .unwrap();
17969        runner.state.pr = Some(crate::run::PrRecord {
17970            url: "https://example.test/project/pull/1".into(),
17971            number: 1,
17972            state: "open".into(),
17973            checks: "unknown".into(),
17974            round: 0,
17975            rounds: 1,
17976            red_at_merge: Vec::new(),
17977        });
17978        runner.sync_to_base().await.unwrap();
17979        assert_eq!(runner.state.status, RunStatus::Blocked);
17980        assert_eq!(
17981            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
17982            crate::base_sync_recovery::StopKind::ClosingIntegratedPr
17983        );
17984        assert!(runner.state.base_sync_closure_pending());
17985        assert!(crate::handover::can_resume(&runner.state));
17986        let queue = crate::queue::Queue::open();
17987        assert!(!crate::base_sync_recovery::held_task(
17988            &queue,
17989            &queue.get(&task).unwrap()
17990        ));
17991        assert!(runner.state.authorize_base_sync(&task).is_err());
17992        // Legacy closure stops have no typed stop but must retain the checkpoint.
17993        runner.state.base_sync_recovery.stop = None;
17994        runner.state.status = RunStatus::Voting;
17995        runner.state.gate_ran = true;
17996        runner.state.config.graph.review_rounds = 0;
17997        runner.state.save().unwrap();
17998        assert!(crate::handover::can_resume(&runner.state));
17999        runner.state = RunState::load(&runner.state.id).unwrap();
18000        runner.execute_graph().await.unwrap();
18001        assert_eq!(runner.state.status, RunStatus::AlreadyInBase);
18002        assert_eq!(runner.state.pr.as_ref().unwrap().state, "closed");
18003        assert_eq!(
18004            runner.state.base_sync.as_ref().unwrap().attempts,
18005            BASE_SYNC_ROUNDS
18006        );
18007        assert!(runner.state.base_sync_recovery.authorizations.is_empty());
18008        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), head);
18009        assert!(runner.state.reviews.is_empty());
18010        assert!(runner.state.gate.is_empty());
18011    }
18012
18013    #[cfg(unix)]
18014    #[tokio::test]
18015    async fn base_recovery_authorization_requires_current_owner_free_lease_and_clean_tree() {
18016        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
18017        runner.state.driver_exited = true;
18018        runner.state.save().unwrap();
18019        let home = crate::run::home();
18020        let queue = crate::queue::Queue::open();
18021        let _claim = queue.claim(&task).unwrap();
18022        let lease = crate::driver::maintenance(&home, &runner.state.id).unwrap();
18023        assert!(
18024            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18025                .await
18026                .is_err()
18027        );
18028        drop(lease);
18029        std::fs::write(runner.state.repo.join("dirty"), "retained uncommitted work").unwrap();
18030        assert!(
18031            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18032                .await
18033                .is_err()
18034        );
18035        std::fs::remove_file(runner.state.repo.join("dirty")).unwrap();
18036        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18037            .await
18038            .unwrap();
18039        let disk = RunState::load(&runner.state.id).unwrap();
18040        assert!(disk.base_recovery_pending());
18041        assert_eq!(disk.base_sync_recovery.authorizations.len(), 1);
18042        assert!(
18043            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18044                .await
18045                .is_err()
18046        );
18047        assert_eq!(
18048            RunState::load(&runner.state.id)
18049                .unwrap()
18050                .base_sync_recovery
18051                .authorizations
18052                .len(),
18053            1
18054        );
18055        let mut owner = queue.get(&task).unwrap();
18056        owner.runs.push("20260101-000000-ffff".into());
18057        queue.put(&mut owner).unwrap();
18058        let error = Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18059            .await
18060            .unwrap_err();
18061        assert!(error.to_string().contains("run task ownership changed"));
18062    }
18063
18064    #[cfg(unix)]
18065    #[tokio::test]
18066    async fn base_recovery_legacy_voting_and_repeated_resume_stay_blocked() {
18067        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
18068        let mut legacy = serde_json::to_value(&runner.state).unwrap();
18069        legacy.as_object_mut().unwrap().remove("base_sync_recovery");
18070        legacy["status"] = serde_json::json!("voting");
18071        runner.state = serde_json::from_value(legacy).unwrap();
18072        runner.state.save().unwrap();
18073        for _ in 0..3 {
18074            runner.execute_graph().await.unwrap();
18075            assert_eq!(runner.state.status, RunStatus::Blocked);
18076            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18077            assert!(!crate::handover::can_resume(&runner.state));
18078            assert_eq!(
18079                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18080                head
18081            );
18082            assert!(runner.state.reviews.is_empty());
18083            assert!(!runner.state.gate_ran);
18084        }
18085        let notice = crate::notices::run_ended(&runner.state).unwrap();
18086        let stop = runner.state.base_sync_recovery.stop.clone().unwrap();
18087        runner.state.begin_pass();
18088        runner.state.status = RunStatus::Voting;
18089        runner.deliberate().await.unwrap();
18090        runner.vote().await.unwrap();
18091        runner.finish_after_tally().await.unwrap();
18092        assert_eq!(runner.state.status, RunStatus::Blocked);
18093        assert_eq!(runner.state.base_sync_recovery.stop.as_ref(), Some(&stop));
18094        assert_eq!(
18095            crate::notices::run_ended(&runner.state).unwrap().since,
18096            notice.since
18097        );
18098    }
18099
18100    #[cfg(unix)]
18101    #[tokio::test]
18102    async fn base_recovery_never_authorizes_conflicts_publication_or_unknown_stops() {
18103        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18104        for detail in [
18105            "fix/retained conflicts with origin/main and did not rebase: conflict",
18106            "rebased fix/retained locally but origin refused the push",
18107            "unknown failure",
18108        ] {
18109            runner.state.base_sync.as_mut().unwrap().conflict = Some(detail.into());
18110            runner.state.record_base_sync_stop(&head);
18111            assert!(runner.state.authorize_base_sync(&task).is_err());
18112            runner.state.status = RunStatus::Voting;
18113            runner.execute_graph().await.unwrap();
18114            assert_eq!(runner.state.status, RunStatus::Blocked);
18115            assert!(!crate::handover::can_resume(&runner.state));
18116            assert_eq!(
18117                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18118                head
18119            );
18120        }
18121    }
18122
18123    #[cfg(unix)]
18124    #[tokio::test]
18125    async fn base_recovery_consumption_survives_crash_without_another_attempt() {
18126        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18127        runner.state.authorize_base_sync(&task).unwrap();
18128        assert!(runner.state.consume_base_recovery(&head));
18129        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18130        runner.state.reserve_base_operation(&head, &tip);
18131        runner.state.save().unwrap();
18132        runner.state = RunState::load(&runner.state.id).unwrap();
18133        assert!(!runner.state.consume_base_recovery(&head));
18134        runner.sync_to_base().await.unwrap();
18135        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18136        assert_eq!(runner.state.base_episode_used(), 1);
18137        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
18138        assert!(
18139            runner
18140                .state
18141                .base_sync_recovery
18142                .operations
18143                .last()
18144                .unwrap()
18145                .finished
18146        );
18147        assert!(!runner.state.base_sync_blocked());
18148        runner.sync_to_base().await.unwrap();
18149        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18150    }
18151
18152    #[cfg(unix)]
18153    #[tokio::test]
18154    async fn base_recovery_legacy_authorization_and_unrecorded_wait_grant_no_interval() {
18155        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18156        // Both historical diagnostic spellings retain an exhaustion identity.
18157        let original = runner
18158            .state
18159            .base_sync
18160            .as_ref()
18161            .unwrap()
18162            .conflict
18163            .clone()
18164            .unwrap();
18165        runner.state.base_sync.as_mut().unwrap().conflict = Some(
18166            original
18167                .replace("synchronization(s)", "rebase(s)")
18168                .replace("synchronizing", "rebasing"),
18169        );
18170        runner.state.base_sync_recovery = Default::default();
18171        runner.state.record_base_sync_stop(&head);
18172        assert_eq!(
18173            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
18174            crate::base_sync_recovery::StopKind::Exhausted
18175        );
18176        runner.state.authorize_base_sync(&task).unwrap();
18177        let mut legacy = serde_json::to_value(&runner.state).unwrap();
18178        let auth = legacy["base_sync_recovery"]["authorizations"][0]
18179            .as_object_mut()
18180            .unwrap();
18181        auth.remove("interval");
18182        auth.remove("scope");
18183        runner.state = serde_json::from_value(legacy).unwrap();
18184        assert!(runner.state.consume_base_recovery(&head));
18185        assert_eq!(runner.state.base_episode_used(), 3);
18186        runner.sync_to_base().await.unwrap();
18187        assert_eq!(runner.state.base_episode_used(), 4);
18188        runner.state.resource_block = Some(crate::run::ResourceBlock {
18189            node: "gate".into(),
18190            kind: "cache".into(),
18191            detail: "legacy wait".into(),
18192            at: Timestamp::now(),
18193            cause: crate::run::ResourceBlockCause::Unrecorded,
18194        });
18195        runner.state.save().unwrap();
18196        assert!(
18197            runner
18198                .state
18199                .base_sync_recovery
18200                .episodes
18201                .last()
18202                .unwrap()
18203                .boundary
18204                .is_none()
18205        );
18206        runner.state.resource_block = None;
18207        advance_base_fixture(&runner).await;
18208        runner.sync_to_base().await.unwrap();
18209        assert!(runner.state.base_sync_blocked());
18210        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18211    }
18212
18213    #[cfg(unix)]
18214    async fn advance_base_fixture(runner: &Runner) {
18215        let repo = &runner.state.repo;
18216        for args in [
18217            vec!["checkout", "main"],
18218            vec!["commit", "--allow-empty", "-m", "base advanced"],
18219            vec!["push", "origin", "main"],
18220            vec!["checkout", "fix/retained"],
18221        ] {
18222            git::git(repo, &args).await.unwrap();
18223        }
18224    }
18225
18226    #[cfg(unix)]
18227    fn fresh_base_interval_fixture(runner: &mut Runner) {
18228        runner.state.base_sync.as_mut().unwrap().attempts = 0;
18229        runner.state.base_sync.as_mut().unwrap().conflict = None;
18230        runner.state.base_sync_recovery = Default::default();
18231        runner.state.status = RunStatus::Voting;
18232    }
18233
18234    #[cfg(unix)]
18235    #[tokio::test]
18236    async fn base_recovery_resource_boundary_requires_new_owner_and_is_single_use() {
18237        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
18238        fresh_base_interval_fixture(&mut runner);
18239        runner.state.begin_pass();
18240        runner.sync_to_base().await.unwrap();
18241        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
18242        runner.state.resource_block = Some(crate::run::ResourceBlock {
18243            node: "gate".into(),
18244            kind: "build cache".into(),
18245            detail: "busy".into(),
18246            at: Timestamp::now(),
18247            cause: crate::run::ResourceBlockCause::Timeout {
18248                waited_secs: 1,
18249                limit_secs: 1,
18250            },
18251        });
18252        runner.state.save().unwrap();
18253        let queue = crate::queue::Queue::open();
18254        let mut owner = queue.get(&task).unwrap();
18255        runner.state.task_instruction = Some(owner.instruction.clone());
18256        owner.release_operator("fixture-owner", None);
18257        queue.put(&mut owner).unwrap();
18258        let approval = owner.resumption.clone().unwrap();
18259        runner.state.resource_block = None;
18260        runner.state.save().unwrap();
18261        runner.state = RunState::load(&runner.state.id).unwrap();
18262        advance_base_fixture(&runner).await;
18263        runner.sync_to_base().await.unwrap();
18264        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
18265        assert_eq!(runner.state.base_episode_used(), 1);
18266        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
18267        assert!(
18268            runner.state.base_sync_recovery.episodes[0]
18269                .boundary
18270                .as_ref()
18271                .unwrap()
18272                .consumed
18273        );
18274        assert!(
18275            !runner
18276                .state
18277                .renew_base_episode(&task, &approval, &head, "base")
18278        );
18279        for _ in 0..3 {
18280            owner.release_operator("fixture-owner", None);
18281            queue.put(&mut owner).unwrap();
18282            runner.state = RunState::load(&runner.state.id).unwrap();
18283            runner.state.begin_pass();
18284            runner.sync_to_base().await.unwrap();
18285            assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
18286            assert_eq!(runner.state.base_episode_used(), 1);
18287        }
18288        runner.state.resource_block = Some(crate::run::ResourceBlock {
18289            node: "gate".into(),
18290            kind: "disk pressure".into(),
18291            detail: "free space required".into(),
18292            at: Timestamp::now(),
18293            cause: crate::run::ResourceBlockCause::Other,
18294        });
18295        runner.state.end_pass_parked(ParkCause::Interrupt {
18296            reason: "disk pressure".into(),
18297        });
18298        runner.state.save().unwrap();
18299        owner.release_operator("fixture-owner-after-disk", None);
18300        queue.put(&mut owner).unwrap();
18301        runner.state.resource_block = None;
18302        advance_base_fixture(&runner).await;
18303        runner.sync_to_base().await.unwrap();
18304        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 3);
18305        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 3);
18306        assert_eq!(runner.state.base_episode_used(), 1);
18307        assert_eq!(runner.state.base_sync_recovery.renewals.len(), 2);
18308    }
18309
18310    #[cfg(unix)]
18311    #[tokio::test]
18312    async fn base_recovery_continuous_advancement_stops_at_four() {
18313        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
18314        fresh_base_interval_fixture(&mut runner);
18315        for spent in 1..=BASE_SYNC_ROUNDS {
18316            runner.sync_to_base().await.unwrap();
18317            assert!(!runner.state.base_sync_blocked());
18318            assert_eq!(runner.state.base_episode_used(), spent);
18319            advance_base_fixture(&runner).await;
18320        }
18321        runner.sync_to_base().await.unwrap();
18322        assert_eq!(
18323            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
18324            crate::base_sync_recovery::StopKind::Exhausted
18325        );
18326        let stop = runner.state.base_sync_recovery.stop.as_ref().unwrap();
18327        assert!(stop.unverified_sync);
18328        let action = runner.state.base_sync_next_action();
18329        assert!(action.contains("never reached its gate"));
18330        assert!(action.contains("4/4 in episode 0, 4 lifetime"));
18331        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18332        runner.state = RunState::load(&runner.state.id).unwrap();
18333        runner.sync_to_base().await.unwrap();
18334        assert_eq!(runner.state.base_episode_used(), 4);
18335        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 1);
18336    }
18337
18338    #[cfg(unix)]
18339    #[tokio::test]
18340    async fn base_recovery_stop_diagnostic_requires_synced_head_without_current_gate() {
18341        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
18342        runner.state.ensure_base_episode();
18343        // Verification progress alone is not evidence of a successful sync.
18344        runner.state.record_base_progress(&head);
18345        runner.state.base_sync_recovery.stop = None;
18346        runner.state.record_base_sync_stop(&head);
18347        assert!(
18348            !runner
18349                .state
18350                .base_sync_recovery
18351                .stop
18352                .as_ref()
18353                .unwrap()
18354                .unverified_sync
18355        );
18356
18357        runner.state.finish_base_operation(Some(&head));
18358        // A gate for another head cannot verify this synchronization.
18359        runner.state.gate_ran = true;
18360        runner.state.gate_head = Some("older-head".into());
18361        runner.state.base_sync_recovery.stop = None;
18362        runner.state.record_base_sync_stop(&head);
18363        runner.state.save().unwrap();
18364        runner.state = RunState::load(&runner.state.id).unwrap();
18365        assert!(
18366            runner
18367                .state
18368                .base_sync_recovery
18369                .stop
18370                .as_ref()
18371                .unwrap()
18372                .unverified_sync
18373        );
18374
18375        runner.state.gate_head = Some(head.clone());
18376        runner.state.base_sync_recovery.stop = None;
18377        runner.state.record_base_sync_stop(&head);
18378        assert!(
18379            !runner
18380                .state
18381                .base_sync_recovery
18382                .stop
18383                .as_ref()
18384                .unwrap()
18385                .unverified_sync
18386        );
18387        assert!(
18388            !runner
18389                .state
18390                .base_sync_next_action()
18391                .contains("never reached its gate")
18392        );
18393
18394        // Historical records cannot establish the missing synchronization evidence.
18395        let mut legacy = serde_json::to_value(&runner.state).unwrap();
18396        legacy["base_sync_recovery"]["stop"]
18397            .as_object_mut()
18398            .unwrap()
18399            .remove("unverified_sync");
18400        legacy["base_sync_recovery"]["episodes"][0]
18401            .as_object_mut()
18402            .unwrap()
18403            .remove("last_sync_head");
18404        runner.state = serde_json::from_value(legacy).unwrap();
18405        assert!(
18406            !runner
18407                .state
18408                .base_sync_recovery
18409                .stop
18410                .as_ref()
18411                .unwrap()
18412                .unverified_sync
18413        );
18414        assert!(
18415            runner.state.base_sync_recovery.episodes[0]
18416                .last_sync_head
18417                .is_none()
18418        );
18419    }
18420
18421    #[cfg(unix)]
18422    #[tokio::test]
18423    async fn base_recovery_next_action_reports_new_episode_and_pending_approval() {
18424        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18425        runner.state.authorize_base_sync(&task).unwrap();
18426        assert!(
18427            runner
18428                .state
18429                .base_sync_next_action()
18430                .contains("Approval recorded")
18431        );
18432        assert!(
18433            runner
18434                .state
18435                .base_sync_next_action()
18436                .contains("4/4 in episode 0, 4 lifetime")
18437        );
18438        assert!(runner.state.consume_base_recovery(&head));
18439        assert!(
18440            runner
18441                .state
18442                .base_sync_next_action()
18443                .contains("0/4 in episode 1, 4 lifetime")
18444        );
18445    }
18446
18447    #[cfg(unix)]
18448    #[tokio::test]
18449    async fn base_recovery_changed_head_invalidates_without_spending() {
18450        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
18451        runner.state.authorize_base_sync(&task).unwrap();
18452        git::git(
18453            &runner.state.repo,
18454            &["commit", "--allow-empty", "-m", "external head change"],
18455        )
18456        .await
18457        .unwrap();
18458        runner.sync_to_base().await.unwrap();
18459        let a = runner
18460            .state
18461            .base_sync_recovery
18462            .authorizations
18463            .last()
18464            .unwrap();
18465        assert!(a.consumed);
18466        assert!(a.invalidated.as_deref().unwrap().contains("HEAD changed"));
18467        runner.state = RunState::load(&runner.state.id).unwrap();
18468        assert!(
18469            runner
18470                .state
18471                .base_sync_next_action()
18472                .contains("Approval invalidated")
18473        );
18474        assert!(!runner.state.base_recovery_pending());
18475        assert!(runner.state.base_sync_blocked());
18476        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18477    }
18478
18479    #[cfg(unix)]
18480    #[tokio::test]
18481    async fn base_recovery_stale_fetched_base_invalidates_approval() {
18482        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18483        runner.state.driver_exited = true;
18484        runner.state.save().unwrap();
18485        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
18486            .await
18487            .unwrap();
18488        runner.state = RunState::load(&runner.state.id).unwrap();
18489        advance_base_fixture(&runner).await;
18490        runner.sync_to_base().await.unwrap();
18491        let a = runner
18492            .state
18493            .base_sync_recovery
18494            .authorizations
18495            .last()
18496            .unwrap();
18497        assert!(
18498            a.consumed
18499                && a.invalidated
18500                    .as_deref()
18501                    .unwrap()
18502                    .contains("fetched base changed")
18503        );
18504        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18505        assert_eq!(
18506            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18507            head
18508        );
18509        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
18510            .await
18511            .unwrap();
18512        runner.state = RunState::load(&runner.state.id).unwrap();
18513        runner.sync_to_base().await.unwrap();
18514        assert!(!runner.state.base_sync_blocked());
18515        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18516    }
18517
18518    #[cfg(unix)]
18519    #[tokio::test]
18520    async fn base_recovery_crash_after_git_finishes_reserved_operation_once() {
18521        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18522        runner.state.authorize_base_sync(&task).unwrap();
18523        assert!(runner.state.consume_base_recovery(&head));
18524        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18525        runner.state.reserve_base_operation(&head, &tip);
18526        runner.state.save().unwrap();
18527        let scratch = runner.state.dir().join("base-sync");
18528        assert_eq!(
18529            crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
18530                .await
18531                .unwrap(),
18532            crate::rebase::Rebased::Applied
18533        );
18534        runner.state = RunState::load(&runner.state.id).unwrap();
18535        runner.sync_to_base().await.unwrap();
18536        assert!(
18537            runner
18538                .state
18539                .base_sync_recovery
18540                .operations
18541                .last()
18542                .unwrap()
18543                .finished
18544        );
18545        assert_eq!(runner.state.base_episode_used(), 1);
18546        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18547        assert!(!runner.state.base_sync_blocked());
18548    }
18549
18550    #[cfg(unix)]
18551    #[tokio::test]
18552    async fn base_recovery_crash_preserves_untracked_files() {
18553        for ignored in [false, true] {
18554            let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18555            runner.state.authorize_base_sync(&task).unwrap();
18556            assert!(runner.state.consume_base_recovery(&head));
18557            let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18558            runner.state.reserve_base_operation(&head, &tip);
18559            runner.state.save().unwrap();
18560            let scratch = runner.state.dir().join("base-sync");
18561            assert_eq!(
18562                crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
18563                    .await
18564                    .unwrap(),
18565                crate::rebase::Rebased::Applied
18566            );
18567            let repo = &runner.state.repo;
18568            let result = git::rev_parse(repo, "HEAD").await.unwrap();
18569            assert_ne!(result, head);
18570            if ignored {
18571                let exclude = git::git(repo, &["rev-parse", "--git-path", "info/exclude"])
18572                    .await
18573                    .unwrap();
18574                std::fs::write(repo.join(exclude), "local-notes\n").unwrap();
18575            }
18576            std::fs::write(repo.join("local-notes"), "retained work\n").unwrap();
18577            assert!(
18578                git::git_raw(repo, &["diff", "--quiet", &head])
18579                    .await
18580                    .unwrap()
18581                    .ok()
18582            );
18583            // Resume after the branch moved, before its checkout was reset.
18584            runner.state = RunState::load(&runner.state.id).unwrap();
18585            runner.sync_to_base().await.unwrap();
18586            assert!(runner.state.base_sync_blocked());
18587            assert!(!runner.state.base_sync_recovery.operations[0].finished);
18588            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18589            assert_eq!(
18590                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18591                result
18592            );
18593            assert_eq!(
18594                std::fs::read_to_string(runner.state.repo.join("local-notes")).unwrap(),
18595                "retained work\n"
18596            );
18597            assert!(
18598                git::git_raw(&runner.state.repo, &["diff", "--quiet", &head])
18599                    .await
18600                    .unwrap()
18601                    .ok()
18602            );
18603        }
18604    }
18605
18606    #[cfg(unix)]
18607    #[tokio::test]
18608    async fn base_recovery_crash_does_not_adopt_foreign_commits() {
18609        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18610        runner.state.authorize_base_sync(&task).unwrap();
18611        assert!(runner.state.consume_base_recovery(&head));
18612        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18613        runner.state.reserve_base_operation(&head, &tip);
18614        runner.state.save().unwrap();
18615        let scratch = runner.state.dir().join("base-sync");
18616        crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
18617            .await
18618            .unwrap();
18619        git::sync_to_head(&runner.state.repo).await.unwrap();
18620        std::fs::write(runner.state.repo.join("foreign"), "foreign work").unwrap();
18621        git::git(&runner.state.repo, &["add", "foreign"])
18622            .await
18623            .unwrap();
18624        git::git(&runner.state.repo, &["commit", "-m", "foreign work"])
18625            .await
18626            .unwrap();
18627        let foreign_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
18628        runner.state = RunState::load(&runner.state.id).unwrap();
18629        runner.sync_to_base().await.unwrap();
18630        assert!(runner.state.base_sync_blocked());
18631        assert!(
18632            !runner
18633                .state
18634                .base_sync_recovery
18635                .operations
18636                .last()
18637                .unwrap()
18638                .finished
18639        );
18640        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18641        assert_eq!(
18642            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18643            foreign_head
18644        );
18645    }
18646
18647    #[cfg(unix)]
18648    async fn paused_base_conflict_fixture() -> (tempfile::TempDir, Runner, String, String, PathBuf)
18649    {
18650        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
18651        fresh_base_interval_fixture(&mut runner);
18652        let repo = &runner.state.repo;
18653        git::git(repo, &["checkout", "main"]).await.unwrap();
18654        std::fs::write(repo.join("retained"), "upstream change\n").unwrap();
18655        git::git(repo, &["add", "retained"]).await.unwrap();
18656        git::git(repo, &["commit", "-m", "upstream retained change"])
18657            .await
18658            .unwrap();
18659        git::git(repo, &["push", "origin", "main"]).await.unwrap();
18660        let tip = git::rev_parse(repo, "HEAD").await.unwrap();
18661        git::git(repo, &["checkout", "fix/retained"]).await.unwrap();
18662        let scratch = runner.state.dir().join("base-sync");
18663        assert!(matches!(
18664            git::rebase_start(repo, &scratch, "fix/retained", &tip)
18665                .await
18666                .unwrap(),
18667            git::RebaseStart::Conflicted(_)
18668        ));
18669        runner.state.rebase_fixes.push(crate::run::RebaseFixRecord {
18670            agent: "fixture".into(),
18671            paths: vec!["retained".into()],
18672            from: Some(head.clone()),
18673            stop: Some(git::rev_parse(&scratch, "REBASE_HEAD").await.unwrap()),
18674            index_outside: None,
18675            finished: false,
18676            error: None,
18677            launcher: None,
18678            infra: None,
18679            outage: None,
18680        });
18681        (tmp, runner, head, tip, scratch)
18682    }
18683
18684    #[cfg(unix)]
18685    #[tokio::test]
18686    async fn base_recovery_imports_legacy_rebase_before_following_new_main() {
18687        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
18688        // A resource stop from before reservations existed, with resolved
18689        // contents left for the launcher's ordinary staging continuation.
18690        std::fs::write(
18691            scratch.join("retained"),
18692            "upstream and retained resolution\n",
18693        )
18694        .unwrap();
18695        runner.state.resource_block = Some(crate::run::ResourceBlock {
18696            node: "rebase".into(),
18697            kind: "repository coordination".into(),
18698            detail: "busy".into(),
18699            at: Timestamp::now(),
18700            cause: crate::run::ResourceBlockCause::Other,
18701        });
18702        runner.state.save().unwrap();
18703        // Advance the remote without moving either checkout participating
18704        // in the standing rebase.
18705        let newer = git::git(
18706            &runner.state.repo,
18707            &[
18708                "commit-tree",
18709                "main^{tree}",
18710                "-p",
18711                "main",
18712                "-m",
18713                "base advanced during wait",
18714            ],
18715        )
18716        .await
18717        .unwrap();
18718        git::git(
18719            &runner.state.repo,
18720            &[
18721                "push",
18722                "origin",
18723                &format!("{}:refs/heads/main", newer.trim()),
18724            ],
18725        )
18726        .await
18727        .unwrap();
18728        runner.state = RunState::load(&runner.state.id).unwrap();
18729        runner.state.resource_block = None;
18730        runner.sync_to_base().await.unwrap();
18731        assert!(!runner.state.base_sync_blocked());
18732        let op = &runner.state.base_sync_recovery.operations[0];
18733        assert_eq!(op.head, head);
18734        assert_eq!(op.tip, tip);
18735        assert!(op.finished);
18736        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18737        assert_eq!(runner.state.rebase_fixes.len(), 1);
18738        let latest = git::rev_parse(&runner.state.repo, "origin/main")
18739            .await
18740            .unwrap();
18741        assert_ne!(latest, tip);
18742        runner.state = RunState::load(&runner.state.id).unwrap();
18743        runner.sync_to_base().await.unwrap();
18744        assert!(!runner.state.base_sync_blocked());
18745        assert_eq!(runner.state.base_sync_recovery.operations.len(), 2);
18746        assert_eq!(runner.state.base_sync_recovery.operations[1].tip, latest);
18747        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
18748    }
18749
18750    #[cfg(unix)]
18751    #[tokio::test]
18752    async fn base_recovery_resumes_exact_validated_conflict_result_after_crash() {
18753        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
18754        runner.state.reserve_base_operation(&head, &tip);
18755        runner.state.save().unwrap();
18756        std::fs::write(
18757            scratch.join("retained"),
18758            "upstream and retained resolution\n",
18759        )
18760        .unwrap();
18761        git::git(&scratch, &["add", "retained"]).await.unwrap();
18762        git::git(
18763            &scratch,
18764            &["-c", "core.editor=true", "rebase", "--continue"],
18765        )
18766        .await
18767        .unwrap();
18768        let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
18769        assert!(
18770            !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
18771                .await
18772                .unwrap()
18773                .is_empty()
18774        );
18775        assert_eq!(
18776            crate::rebase::finish(
18777                &mut runner.state,
18778                &scratch,
18779                "fix/retained",
18780                &head,
18781                &tip,
18782                &["retained".into()],
18783                ""
18784            )
18785            .await
18786            .unwrap(),
18787            crate::rebase::Rebased::Applied
18788        );
18789        assert!(!scratch.exists());
18790        // Simulate losing the caller before finish_base_operation/save.
18791        runner.state = RunState::load(&runner.state.id).unwrap();
18792        let op = &runner.state.base_sync_recovery.operations[0];
18793        assert!(!op.finished);
18794        assert_eq!(op.validated_head.as_deref(), Some(result.as_str()));
18795        runner.sync_to_base().await.unwrap();
18796        assert!(!runner.state.base_sync_blocked());
18797        assert!(runner.state.base_sync_recovery.operations[0].finished);
18798        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18799        assert_eq!(runner.state.rebase_fixes.len(), 1);
18800        let winner = runner.state.winner().unwrap().clone();
18801        let wait = runner.repository_wait();
18802        assert!(
18803            verify_current_head(&mut runner.state, &winner, &wait)
18804                .await
18805                .unwrap()
18806        );
18807        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
18808    }
18809
18810    #[cfg(unix)]
18811    #[tokio::test]
18812    async fn base_recovery_revalidates_completed_scratch_before_validation_save() {
18813        for damage in [None, Some("record"), Some("foreign"), Some("dirty")] {
18814            let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
18815            runner.state.reserve_base_operation(&head, &tip);
18816            runner.state.save().unwrap();
18817            std::fs::write(
18818                scratch.join("retained"),
18819                "upstream and retained resolution\n",
18820            )
18821            .unwrap();
18822            git::git(&scratch, &["add", "retained"]).await.unwrap();
18823            git::git(
18824                &scratch,
18825                &["-c", "core.editor=true", "rebase", "--continue"],
18826            )
18827            .await
18828            .unwrap();
18829            let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
18830            assert!(!git::rebase_in_progress(&scratch).await);
18831            assert!(
18832                !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
18833                    .await
18834                    .unwrap()
18835                    .is_empty()
18836            );
18837            match damage {
18838                Some("record") => {
18839                    let path =
18840                        git::git(&scratch, &["rev-parse", "--git-path", "magi-rebase-heads"])
18841                            .await
18842                            .unwrap();
18843                    std::fs::write(scratch.join(path), "").unwrap();
18844                }
18845                Some("foreign") => {
18846                    std::fs::write(scratch.join("foreign"), "foreign work").unwrap();
18847                    git::git(&scratch, &["add", "foreign"]).await.unwrap();
18848                    git::git(&scratch, &["commit", "-m", "foreign work"])
18849                        .await
18850                        .unwrap();
18851                }
18852                Some("dirty") => {
18853                    std::fs::write(scratch.join("retained"), "uncommitted work").unwrap();
18854                }
18855                _ => {}
18856            }
18857            let retained_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
18858            // Crash immediately after Git continuation, before finish runs.
18859            runner.state = RunState::load(&runner.state.id).unwrap();
18860            assert!(
18861                runner.state.base_sync_recovery.operations[0]
18862                    .validated_head
18863                    .is_none()
18864            );
18865            runner.sync_to_base().await.unwrap();
18866            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18867            assert_eq!(runner.state.base_episode_used(), 1);
18868            assert_eq!(runner.state.rebase_fixes.len(), 1);
18869            assert_eq!(
18870                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18871                retained_head
18872            );
18873            if damage.is_some() {
18874                assert!(runner.state.base_sync_blocked());
18875                assert!(scratch.exists());
18876                assert!(!runner.state.base_sync_recovery.operations[0].finished);
18877                assert!(
18878                    runner.state.base_sync_recovery.operations[0]
18879                        .validated_head
18880                        .is_none()
18881                );
18882            } else {
18883                assert!(!runner.state.base_sync_blocked());
18884                assert!(!scratch.exists());
18885                assert!(runner.state.base_sync_recovery.operations[0].finished);
18886                assert_eq!(
18887                    runner.state.base_sync_recovery.operations[0]
18888                        .validated_head
18889                        .as_deref(),
18890                    Some(result.as_str())
18891                );
18892                let winner = runner.state.winner().unwrap().clone();
18893                let wait = runner.repository_wait();
18894                assert!(
18895                    verify_current_head(&mut runner.state, &winner, &wait)
18896                        .await
18897                        .unwrap()
18898                );
18899                assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
18900                runner.state = RunState::load(&runner.state.id).unwrap();
18901                runner.sync_to_base().await.unwrap();
18902                assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18903            }
18904        }
18905    }
18906
18907    #[cfg(unix)]
18908    async fn resumed_gate_fixture() -> (tempfile::TempDir, Runner, String) {
18909        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
18910        // This is an ordinary gate stop, not an authorized base-budget recovery.
18911        runner.state.prep_complete = Some(true);
18912        runner.state.base_sync = None;
18913        runner.state.base_sync_recovery = Default::default();
18914        runner.state.config.graph.gate_fix_rounds = 1;
18915        let mut review = review_round(true, 0, 1, 1, false, true);
18916        review.head = head.clone();
18917        review.verified_head = Some(head.clone());
18918        runner.state.reviews = vec![review];
18919        runner.state.gate = vec![CommandOutcome {
18920            command: "old gate".into(),
18921            code: Some(1),
18922            output_tail: "old failure".into(),
18923            duration_ms: 0,
18924            resource_blocked: false,
18925        }];
18926        runner.state.gate_head = Some(head.clone());
18927        runner.state.gate_ran = true;
18928        runner.state.gate_fixes = vec![crate::run::GateFixRecord {
18929            agent: "fixture".into(),
18930            failed: runner.state.gate.clone(),
18931            notes: "spent".into(),
18932            committed: false,
18933            error: None,
18934        }];
18935        runner.state.land_approval = Some(crate::run::LandApproval {
18936            question: "old approval".into(),
18937            head: head.clone(),
18938        });
18939        runner.state.status = RunStatus::Blocked;
18940        (tmp, runner, head)
18941    }
18942
18943    #[cfg(unix)]
18944    #[tokio::test]
18945    async fn resumed_gate_rebase_verifies_new_head_without_refilling_repairs() {
18946        for (e2e_ok, gate_ok) in [(true, true), (true, false), (false, true)] {
18947            let (tmp, mut runner, old) = resumed_gate_fixture().await;
18948            let phases = tmp.path().join("phases");
18949            runner.state.config.verify.e2e = vec![format!(
18950                "echo e2e >> '{}'; {}",
18951                phases.display(),
18952                if e2e_ok {
18953                    "true"
18954                } else {
18955                    "echo new-e2e-failure; false"
18956                }
18957            )];
18958            runner.state.config.verify.gate = vec![format!(
18959                "echo gate >> '{}'; {}",
18960                phases.display(),
18961                if gate_ok {
18962                    "true"
18963                } else {
18964                    "echo new-gate-failure; false"
18965                }
18966            )];
18967            runner.state.save().unwrap();
18968            runner.state = RunState::load(&runner.state.id).unwrap();
18969            runner.sync_to_base().await.unwrap();
18970            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
18971            assert_ne!(head, old);
18972            // Reentry after Git updated but before verification was invalidated.
18973            runner.state = RunState::load(&runner.state.id).unwrap();
18974            runner.execute_graph().await.unwrap();
18975            assert_eq!(runner.state.gate_fixes.len(), 1);
18976            assert_eq!(runner.state.reviews.len(), 1);
18977            assert_eq!(runner.state.reviews[0].head, old);
18978            assert_eq!(runner.state.land_approval.as_ref().unwrap().head, old);
18979            assert_eq!(runner.state.verification_history.len(), 1);
18980            let history = &runner.state.verification_history[0];
18981            assert_eq!(history.gate_head.as_deref(), Some(old.as_str()));
18982            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
18983            assert!(history.archived_at.is_some());
18984            assert_eq!(history.fixes_spent, Some(1));
18985            assert_eq!(history.gate[0].output_tail, "old failure");
18986            let archive_events: Vec<_> = runner
18987                .state
18988                .events
18989                .iter()
18990                .filter(|e| e.node == "gate" && e.message.starts_with("archived gate on "))
18991                .collect();
18992            assert_eq!(archive_events.len(), 1);
18993            assert!(archive_events[0].message.contains(&short(&old)));
18994            assert!(archive_events[0].message.contains(&short(&head)));
18995            assert!(
18996                archive_events[0]
18997                    .message
18998                    .contains("1 gate-fix round(s) already spent stay spent")
18999            );
19000            assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, head);
19001            assert_eq!(runner.state.head_e2e.as_ref().unwrap().passed, e2e_ok);
19002            if e2e_ok {
19003                assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
19004                assert_eq!(runner.state.gate_allows_progress(), gate_ok);
19005            } else {
19006                assert!(!runner.state.gate_ran);
19007            }
19008            assert_eq!(
19009                runner.state.status,
19010                if e2e_ok && gate_ok {
19011                    RunStatus::Ready
19012                } else {
19013                    RunStatus::Blocked
19014                }
19015            );
19016            if !e2e_ok || !gate_ok {
19017                let cause = runner.state.verification_blocking_cause().unwrap();
19018                assert!(cause.contains(&head));
19019                assert!(cause.contains(if e2e_ok { "gate failed" } else { "e2e failed" }));
19020                // A later successful progress event must not become the cause.
19021                runner.state.event("land", "rebased successfully");
19022                let notice = crate::notices::run_ended(&runner.state).unwrap();
19023                assert!(!format!("{notice:?}").contains("rebased successfully"));
19024                assert!(runner.state.merge.is_none());
19025            }
19026            let before = std::fs::read_to_string(&phases).unwrap();
19027            runner.state.save().unwrap();
19028            runner.state = RunState::load(&runner.state.id).unwrap();
19029            runner.review_loop().await.unwrap();
19030            runner.gate().await.unwrap();
19031            assert_eq!(std::fs::read_to_string(&phases).unwrap(), before);
19032            assert_eq!(runner.state.verification_history.len(), 1);
19033            let history = &runner.state.verification_history[0];
19034            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
19035            assert!(history.archived_at.is_some());
19036            assert_eq!(history.fixes_spent, Some(1));
19037        }
19038    }
19039
19040    #[cfg(unix)]
19041    #[tokio::test]
19042    async fn resumed_gate_unchanged_head_keeps_failure_and_unknown_head_rechecks() {
19043        let (tmp, mut runner, head) = resumed_gate_fixture().await;
19044        let marker = tmp.path().join("gate-ran");
19045        runner.state.config.verify.gate = vec![format!("touch '{}'", marker.display())];
19046        runner.review_loop().await.unwrap();
19047        runner.gate().await.unwrap();
19048        assert_eq!(runner.state.status, RunStatus::Blocked);
19049        assert!(!marker.exists());
19050        assert!(runner.state.verification_history.is_empty());
19051        runner.state.gate_head = None;
19052        runner.gate().await.unwrap();
19053        assert!(marker.exists());
19054        assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
19055        assert_eq!(runner.state.verification_history.len(), 1);
19056        assert_eq!(runner.state.gate_fixes.len(), 1);
19057    }
19058
19059    #[cfg(unix)]
19060    #[tokio::test]
19061    async fn resumed_gate_pending_e2e_retries_without_spending_or_landing() {
19062        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
19063        runner.sync_to_base().await.unwrap();
19064        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19065        runner.state.reconcile_verification_head(&head);
19066        // Both crash-before-command and resource wait are unresolved evidence.
19067        for outcomes in [
19068            Vec::new(),
19069            vec![CommandOutcome {
19070                command: "true".into(),
19071                code: None,
19072                output_tail: "cache unavailable".into(),
19073                duration_ms: 0,
19074                resource_blocked: true,
19075            }],
19076        ] {
19077            runner.state.head_e2e = Some(crate::run::GateRepairE2e {
19078                head: head.clone(),
19079                passed: false,
19080                outcomes,
19081            });
19082            runner.state.gate_ran = false;
19083            runner.state.gate.clear();
19084            runner.state.save().unwrap();
19085            runner.state = RunState::load(&runner.state.id).unwrap();
19086            runner.merge().await.unwrap();
19087            assert!(runner.state.merge.is_none());
19088            runner.review_loop().await.unwrap();
19089            runner.gate().await.unwrap();
19090            assert!(runner.state.head_e2e.as_ref().unwrap().passed);
19091            assert!(runner.state.gate_allows_progress());
19092            assert_eq!(runner.state.gate_fixes.len(), 1);
19093            assert!(runner.state.merge.is_none());
19094        }
19095        // Moving the winner after a successful gate cannot publish an unchecked SHA.
19096        git::git(
19097            &runner.state.repo,
19098            &["commit", "--allow-empty", "-m", "external update"],
19099        )
19100        .await
19101        .unwrap();
19102        runner.merge().await.unwrap();
19103        assert!(runner.state.merge.is_none());
19104        assert_eq!(runner.state.status, RunStatus::Blocked);
19105    }
19106
19107    #[cfg(unix)]
19108    #[tokio::test]
19109    async fn resumed_gate_resource_waits_preserve_budget_and_retry_on_reentry() {
19110        for waiting_on_gate in [false, true] {
19111            let (tmp, mut runner, _old) = resumed_gate_fixture().await;
19112            runner.sync_to_base().await.unwrap();
19113            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19114            runner.state.reconcile_verification_head(&head);
19115            if waiting_on_gate {
19116                runner.state.head_e2e = Some(crate::run::GateRepairE2e {
19117                    head: head.clone(),
19118                    passed: true,
19119                    outcomes: Vec::new(),
19120                });
19121            }
19122            let cache = tmp.path().join("cache");
19123            runner.state.config.verify.e2e =
19124                vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
19125            runner.state.config.verify.gate = vec!["true".into()];
19126            runner.state.config.graph.timeout_resource_wait = 1;
19127            let owner =
19128                crate::cache::Owner::here("other", "e2e", "e2e", &runner.state.repo, "other-head");
19129            let guard =
19130                match crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap() {
19131                    crate::cache::AcquireOutcome::Acquired(g) => g,
19132                    crate::cache::AcquireOutcome::Busy(b) => panic!("unexpected busy cache: {b:?}"),
19133                };
19134            runner.review_loop().await.unwrap();
19135            runner.gate().await.unwrap();
19136            assert!(!runner.state.gate_ran);
19137            assert_eq!(runner.state.gate_fixes.len(), 1);
19138            assert!(runner.state.resource_block.is_some());
19139            runner.merge().await.unwrap();
19140            assert!(runner.state.merge.is_none());
19141            drop(guard);
19142            runner.state = RunState::load(&runner.state.id).unwrap();
19143            // The driver clears the previous pass's resource stop on resume.
19144            runner.state.resource_block = None;
19145            runner.review_loop().await.unwrap();
19146            runner.gate().await.unwrap();
19147            assert!(runner.state.gate_allows_progress());
19148            assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
19149            assert_eq!(runner.state.gate_fixes.len(), 1);
19150        }
19151    }
19152
19153    #[cfg(unix)]
19154    #[tokio::test]
19155    async fn resumed_gate_pre_gate_head_change_and_review_holds() {
19156        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
19157        runner.sync_to_base().await.unwrap();
19158        let before = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19159        runner.state.config.verify.pre_gate = vec!["echo mechanical > mechanical".into()];
19160        // Verification passes before pre_gate and fails on the mechanically changed head.
19161        runner.state.config.verify.e2e = vec!["test ! -f mechanical".into()];
19162        runner.review_loop().await.unwrap();
19163        runner.gate().await.unwrap();
19164        let after = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19165        assert_ne!(before, after);
19166        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, after);
19167        assert!(!runner.state.head_e2e.as_ref().unwrap().passed);
19168        assert!(!runner.state.gate_allows_progress());
19169        runner.merge().await.unwrap();
19170        assert!(runner.state.merge.is_none());
19171        assert!(
19172            runner
19173                .state
19174                .verification_history
19175                .iter()
19176                .any(|h| h.e2e.as_ref().is_some_and(|e| e.head == before && e.passed))
19177        );
19178
19179        // An incomplete review is still an independent hold on a changed head.
19180        runner.state.reviews[0].clean = false;
19181        runner.state.reviews[0].answered = 0;
19182        runner.state.config.verify.e2e = vec!["true".into()];
19183        runner.review_loop().await.unwrap();
19184        runner.gate().await.unwrap();
19185        runner.merge().await.unwrap();
19186        assert_eq!(runner.state.status, RunStatus::Blocked);
19187        assert!(runner.state.merge.is_none());
19188        assert!(
19189            runner
19190                .state
19191                .verification_blocking_cause()
19192                .unwrap()
19193                .contains("review blocked")
19194        );
19195    }
19196
19197    #[cfg(unix)]
19198    #[tokio::test]
19199    async fn resumed_gate_cannot_certify_a_head_changed_by_its_command() {
19200        let (_tmp, mut runner, old) = resumed_gate_fixture().await;
19201        runner.state.gate_head = None;
19202        runner.state.config.verify.gate =
19203            vec!["git -c commit.gpgsign=false commit --allow-empty -m 'gate changed head'".into()];
19204        runner.review_loop().await.unwrap();
19205        runner.gate().await.unwrap();
19206        assert_ne!(
19207            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19208            old
19209        );
19210        assert_eq!(runner.state.gate_head.as_deref(), Some(old.as_str()));
19211        assert!(!runner.state.gate_allows_progress());
19212        assert_eq!(runner.state.status, RunStatus::Blocked);
19213        runner.merge().await.unwrap();
19214        assert!(runner.state.merge.is_none());
19215    }
19216
19217    #[cfg(unix)]
19218    #[tokio::test]
19219    async fn base_recovery_success_requires_new_review_e2e_and_gate() {
19220        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19221        let mut old_review = review_round(true, 0, 1, 1, false, true);
19222        old_review.head = head.clone();
19223        old_review.verified_head = Some(head.clone());
19224        runner.state.reviews = vec![old_review];
19225        runner.state.gate = vec![CommandOutcome {
19226            command: "old gate".into(),
19227            code: None,
19228            output_tail: "timed out after 2400s".into(),
19229            duration_ms: 2_400_000,
19230            resource_blocked: false,
19231        }];
19232        runner.state.gate_ran = true;
19233        runner.state.gate_head = Some(head.clone());
19234        runner.state.land_approval = Some(crate::run::LandApproval {
19235            question: "old-head-approval".into(),
19236            head: head.clone(),
19237        });
19238        runner.state.authorize_base_sync(&task).unwrap();
19239        runner.sync_to_base().await.unwrap();
19240        assert!(!runner.state.base_sync_blocked());
19241        let fresh = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19242        assert_ne!(head, fresh);
19243        assert_eq!(runner.state.reviews.len(), 1);
19244        assert!(!runner.state.gate_ran);
19245        let saved = &runner.state.base_sync_recovery.authorizations[0];
19246        assert_eq!(saved.reviews[0].head, head);
19247        assert_eq!(saved.gate_head.as_deref(), Some(head.as_str()));
19248        assert!(saved.gate_ran);
19249        assert!(!saved.gate[0].ok());
19250        runner.review_loop().await.unwrap();
19251        runner.gate().await.unwrap();
19252        assert_eq!(runner.state.reviews[0].head, head);
19253        assert_eq!(
19254            runner.state.reviews[0].verified_head.as_deref(),
19255            Some(head.as_str())
19256        );
19257        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, fresh);
19258        assert!(runner.state.head_e2e.as_ref().unwrap().passed);
19259        assert_eq!(runner.state.gate_head.as_deref(), Some(fresh.as_str()));
19260        assert!(runner.state.gate_ran);
19261        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
19262        assert_eq!(runner.state.land_approval.as_ref().unwrap().head, head);
19263        assert_ne!(runner.state.land_approval.as_ref().unwrap().head, fresh);
19264        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19265        assert_eq!(
19266            std::fs::read_to_string(runner.state.repo.join("retained")).unwrap(),
19267            "retained change"
19268        );
19269    }
19270
19271    #[cfg(unix)]
19272    #[tokio::test]
19273    async fn base_recovery_moving_base_uses_bounded_authorized_interval() {
19274        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
19275        let queue = crate::queue::Queue::open();
19276        let mut owner = queue.get(&task).unwrap();
19277        owner.release_operator("test-resume", None);
19278        queue.put(&mut owner).unwrap();
19279        let generation = owner.resumption.as_ref().unwrap().generation;
19280        runner.state.task_instruction = Some(owner.instruction.clone());
19281        runner.state.driver_exited = true;
19282        runner.state.save().unwrap();
19283        let home = crate::run::home();
19284        let _claim = queue.claim(&task).unwrap();
19285        owner.resumption.as_mut().unwrap().at =
19286            runner.state.base_sync_recovery.stop.as_ref().unwrap().at;
19287        queue.put(&mut owner).unwrap();
19288        assert!(
19289            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19290                .await
19291                .is_err(),
19292            "an approval from before the stop grants nothing"
19293        );
19294        owner.resumption.as_mut().unwrap().at = Timestamp::now();
19295        queue.put(&mut owner).unwrap();
19296        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19297            .await
19298            .unwrap();
19299        assert!(
19300            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19301                .await
19302                .is_err()
19303        );
19304        runner.state = RunState::load(&runner.state.id).unwrap();
19305        assert_eq!(
19306            runner.state.base_sync_recovery.authorizations[0].generation,
19307            Some(generation)
19308        );
19309        runner.sync_to_base().await.unwrap();
19310        let repo = runner.state.repo.clone();
19311        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
19312        git::git(&repo, &["checkout", "main"]).await.unwrap();
19313        std::fs::write(repo.join("base-change"), "base moved again").unwrap();
19314        git::git(&repo, &["add", "."]).await.unwrap();
19315        git::git(&repo, &["commit", "-m", "move base again"])
19316            .await
19317            .unwrap();
19318        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
19319        git::git(&repo, &["checkout", "fix/retained"])
19320            .await
19321            .unwrap();
19322        runner.sync_to_base().await.unwrap();
19323        assert!(!runner.state.base_sync_blocked());
19324        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
19325        assert_eq!(runner.state.base_episode_used(), 2);
19326        let fresh = git::rev_parse(&repo, "HEAD").await.unwrap();
19327        assert_ne!(fresh, head);
19328        assert!(!runner.state.base_recovery_pending());
19329        // Even replaying the generation with a later timestamp grants nothing.
19330        owner.resumption.as_mut().unwrap().at = Timestamp::now();
19331        queue.put(&mut owner).unwrap();
19332        assert!(
19333            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
19334                .await
19335                .is_err()
19336        );
19337        runner.state = RunState::load(&runner.state.id).unwrap();
19338        runner.sync_to_base().await.unwrap();
19339        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
19340        assert_eq!(runner.state.base_sync_recovery.authorizations.len(), 1);
19341        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), fresh);
19342    }
19343
19344    #[cfg(unix)]
19345    #[tokio::test]
19346    async fn base_recovery_tally_skips_deliberation_and_voting_without_a_sync_stop() {
19347        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
19348        runner.state.base_sync = None;
19349        runner.state.status = RunStatus::Blocked;
19350        let mut second = runner.state.candidates[0].clone();
19351        second.label = 'B';
19352        runner.state.candidates.push(second);
19353        assert!(runner.state.votes.is_empty());
19354        assert!(runner.state.deliberation.is_empty());
19355        runner.deliberate().await.unwrap();
19356        runner.vote().await.unwrap();
19357        assert_eq!(runner.state.status, RunStatus::Blocked);
19358        assert!(runner.state.votes.is_empty());
19359        assert!(runner.state.deliberation.is_empty());
19360    }
19361
19362    /// A minimal, git-free `Runner` at a given status — `settle_questions`
19363    /// reads nothing else off it.
19364    fn runner_at(status: RunStatus) -> Runner {
19365        let mut state = RunState::new(
19366            PathBuf::from("/nonexistent/repo"),
19367            "main".to_owned(),
19368            "deadbeef".to_owned(),
19369            "task".to_owned(),
19370            Config::default(),
19371        );
19372        // These fixtures test execution flow, independent of host disk capacity.
19373        state.config.disk.min_free_bytes = 0;
19374        // These fixtures share one home and save concurrently. Short clock
19375        // IDs can collide, making an ownership test read another test's run.
19376        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
19377        state.id = format!(
19378            "20000101-000000-{:04x}",
19379            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
19380        );
19381        state.status = status;
19382        Runner {
19383            state,
19384            roles: ResolvedRoles {
19385                implementers: Vec::new(),
19386                judges: Vec::new(),
19387                reviewers: Vec::new(),
19388                fixer: None,
19389                conductor: conductor(),
19390                implementer_roster: Vec::new(),
19391                judge_roster: Vec::new(),
19392                reviewer_roster: Vec::new(),
19393            },
19394            sem: Arc::new(Semaphore::new(1)),
19395            pause: Pause::new(),
19396            interrupt: Pause::new(),
19397        }
19398    }
19399
19400    #[tokio::test]
19401    async fn targeted_fix_refuses_independent_ownership_conflicts() {
19402        crate::run::pin_test_home();
19403        let home = crate::run::home();
19404        let mut runner = runner_at(RunStatus::Ready);
19405        runner.state.driver_exited = true;
19406        runner.state.save().unwrap();
19407        let id = runner.state.id.clone();
19408        let path = runner.state.dir().join("run.json");
19409        let ids = ["R1-1-1".into()];
19410        let lease = crate::driver::maintenance(&home, &id).unwrap();
19411        for (guard, expected) in [
19412            (Some(lease), "currently being worked on"),
19413            (None, "ownership is being updated"),
19414        ] {
19415            let owner = if guard.is_none() {
19416                Some(crate::pr_head::owner_lock(&home, &id).unwrap())
19417            } else {
19418                None
19419            };
19420            let before = std::fs::read(&path).unwrap();
19421            let err = runner
19422                .fix_selected(&ids, "ownership conflict", false)
19423                .await
19424                .unwrap_err();
19425            assert!(format!("{err:#}").contains(expected), "{err:#}");
19426            assert_eq!(std::fs::read(&path).unwrap(), before);
19427            assert!(!runner.state.dir().join("fix.lock").exists());
19428            drop(owner);
19429            drop(guard);
19430        }
19431        let mut disk = RunState::load(&id).unwrap();
19432        disk.driver_exited = false;
19433        disk.driver_pid = Some(std::process::id());
19434        disk.driver_started_at = Some(crate::proc::process_started_at(std::process::id()).unwrap());
19435        disk.save().unwrap();
19436        assert_eq!(
19437            disk.liveness_under(&home, false),
19438            crate::run::Liveness::Live
19439        );
19440        let before = std::fs::read(&path).unwrap();
19441        let err = runner
19442            .fix_selected(&ids, "live driver", false)
19443            .await
19444            .unwrap_err();
19445        assert!(
19446            err.to_string().contains("currently being worked on"),
19447            "{err:#}"
19448        );
19449        assert_eq!(std::fs::read(&path).unwrap(), before);
19450        assert!(!runner.state.dir().join("fix.lock").exists());
19451        disk.driver_exited = true;
19452        disk.driver_pid = None;
19453        disk.driver_started_at = None;
19454        disk.status = RunStatus::Reviewing;
19455        disk.save().unwrap();
19456        let before = std::fs::read(&path).unwrap();
19457        let err = runner
19458            .fix_selected(&ids, "stale state", false)
19459            .await
19460            .unwrap_err();
19461        assert!(
19462            err.to_string().contains("run changed since it was loaded"),
19463            "{err:#}"
19464        );
19465        assert_eq!(std::fs::read(&path).unwrap(), before);
19466        assert!(!runner.state.dir().join("fix.lock").exists());
19467        assert!(runner.state.operator_fixes.is_empty());
19468    }
19469
19470    #[tokio::test]
19471    async fn targeted_fix_preflight_releases_owner_and_cancellation_releases_claims() {
19472        use std::future::Future;
19473        use std::task::Poll;
19474
19475        crate::run::pin_test_home();
19476        let home = crate::run::home();
19477        let repo = tempfile::tempdir().unwrap();
19478        let mut runner = runner_at(RunStatus::Ready);
19479        runner.state.repo = repo.path().to_path_buf();
19480        runner.state.driver_exited = true;
19481        runner.state.candidates.push(Candidate {
19482            index: 0,
19483            label: 'A',
19484            agent: "mock".into(),
19485            branch: "magi/test/A".into(),
19486            worktree: repo.path().join("wt"),
19487            summary: String::new(),
19488            stat: String::new(),
19489            files: 0,
19490            commits: 0,
19491            empty: false,
19492            failed: None,
19493            verified_noop: None,
19494            duration_ms: 0,
19495            folded: false,
19496        });
19497        runner.state.tally = Some(Tally {
19498            first_choice: BTreeMap::from([('A', 1)]),
19499            borda: BTreeMap::new(),
19500            winner: 'A',
19501            rankings: 1,
19502            unanimous_initial: true,
19503            deliberated: false,
19504            changed_votes: 0,
19505            unanimous_final: true,
19506            tie_break: None,
19507            judges: 1,
19508            present: 1,
19509            quorum: 1,
19510            met_quorum: true,
19511            uncontested: None,
19512        });
19513        runner.state.save().unwrap();
19514        let id = runner.state.id.clone();
19515        let dir = runner.state.dir();
19516        let before = std::fs::read(dir.join("run.json")).unwrap();
19517        let ids = ["R1-1-1".into()];
19518        let mut fix = Box::pin(runner.fix_selected(&ids, "preflight lock check", false));
19519        std::future::poll_fn(|cx| match fix.as_mut().poll(cx) {
19520            Poll::Pending => Poll::Ready(()),
19521            Poll::Ready(result) => panic!("preflight completed without yielding: {result:?}"),
19522        })
19523        .await;
19524        assert!(FixClaim::acquire(&dir).is_err());
19525        assert!(crate::driver::maintenance(&home, &id).is_err());
19526        drop(crate::pr_head::owner_lock(&home, &id).unwrap());
19527        drop(fix);
19528        assert!(FixClaim::acquire(&dir).is_ok());
19529        assert!(crate::driver::maintenance(&home, &id).is_ok());
19530        assert_eq!(std::fs::read(dir.join("run.json")).unwrap(), before);
19531    }
19532
19533    #[tokio::test]
19534    async fn source_eviction_resume_restores_before_graph_shortcuts_and_setup() {
19535        crate::run::pin_test_home();
19536        let temp = tempfile::tempdir().unwrap();
19537        let root = temp.path().canonicalize().unwrap();
19538        let repo = root.join("repo");
19539        std::fs::create_dir(&repo).unwrap();
19540        init_repo(&repo);
19541        git::git(&repo, &["config", "core.autocrlf", "false"])
19542            .await
19543            .unwrap();
19544        let mut runner = runner_at(RunStatus::Blocked);
19545        runner.state.repo = repo.clone();
19546        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
19547        runner.state.config.agents = vec![conductor()];
19548        runner.state.config.graph.selected_implementer = Some("conductor".into());
19549        runner.state.config.graph.worktree_root = Some(root.join("worktrees"));
19550        let (shell, command, setup_output) = if cfg!(windows) {
19551            (
19552                vec!["cmd".into(), "/C".into()],
19553                "echo ready>seat-ready",
19554                "ready\r\n",
19555            )
19556        } else {
19557            (
19558                vec!["sh".into(), "-c".into()],
19559                "printf ready > seat-ready",
19560                "ready",
19561            )
19562        };
19563        runner.state.config.verify.shell = Some(shell);
19564        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
19565            run: Some(command.into()),
19566            ..Default::default()
19567        }];
19568        runner.state.save().unwrap();
19569        let path = runner.state.worktree_root().join("judge-1");
19570        git::worktree_add_detached(&repo, &path, &runner.state.base_commit)
19571            .await
19572            .unwrap();
19573        std::fs::write(path.join("checkpoint"), "unrelated seat").unwrap();
19574        git::git(&path, &["add", "."]).await.unwrap();
19575        let tree = git::git(&path, &["write-tree"]).await.unwrap();
19576        let head = git::git(&path, &["commit-tree", &tree, "-m", "seat checkpoint"])
19577            .await
19578            .unwrap();
19579        git::git(&path, &["checkout", "--detach", &head])
19580            .await
19581            .unwrap();
19582        let evidence = crate::fold_evidence::snapshot(
19583            &runner.state,
19584            &crate::run::home().canonicalize().unwrap(),
19585            &head,
19586            64 * 1024 * 1024,
19587        )
19588        .await
19589        .unwrap();
19590        let mut contents = BTreeMap::new();
19591        contents.insert(
19592            repo.join("logs/HEAD"),
19593            format!("{head} {head} fixture\n").into_bytes(),
19594        );
19595        let record = serde_json::json!({
19596            "version":1, "run":runner.state.id, "source":path, "head":head,
19597            "evidence":evidence, "admin":{}, "admin_contents":contents,
19598            "history":{head.clone():evidence}, "phase":"evicted"
19599        });
19600        std::fs::write(
19601            runner.state.dir().join("artifacts/eviction-judge-1.json"),
19602            serde_json::to_vec(&record).unwrap(),
19603        )
19604        .unwrap();
19605        assert!(git::worktree_remove_clean(&repo, &path).await.unwrap());
19606        git::git(&repo, &["reflog", "expire", "--expire=now", "--all"])
19607            .await
19608            .unwrap();
19609        git::git(&repo, &["gc", "--prune=now"]).await.unwrap();
19610        assert!(
19611            !git::git_raw(&repo, &["cat-file", "-e", &head])
19612                .await
19613                .unwrap()
19614                .ok()
19615        );
19616        let mut resumed = Runner::resume(&runner.state.id).unwrap();
19617        let error = resumed.execute().await.unwrap_err();
19618        assert!(
19619            error
19620                .to_string()
19621                .contains("selected implementation is held"),
19622            "{error:#}"
19623        );
19624        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
19625        assert_eq!(
19626            std::fs::read_to_string(path.join("seat-ready")).unwrap(),
19627            setup_output
19628        );
19629        assert_eq!(
19630            std::fs::read_to_string(path.join("checkpoint")).unwrap(),
19631            "unrelated seat"
19632        );
19633        let error = resumed.execute().await.unwrap_err();
19634        assert!(
19635            error
19636                .to_string()
19637                .contains("selected implementation is held"),
19638            "{error:#}"
19639        );
19640        std::fs::write(path.join("checkpoint"), "next recorded review").unwrap();
19641        git::git(&path, &["add", "."]).await.unwrap();
19642        let next_tree = git::git(&path, &["write-tree"]).await.unwrap();
19643        let next = git::git(
19644            &path,
19645            &[
19646                "commit-tree",
19647                &next_tree,
19648                "-p",
19649                &head,
19650                "-m",
19651                "next review checkpoint",
19652            ],
19653        )
19654        .await
19655        .unwrap();
19656        git::git(&path, &["checkout", "--detach", &next])
19657            .await
19658            .unwrap();
19659        resumed.state.reviews.push(
19660            serde_json::from_value(serde_json::json!({
19661                "round":1, "head":next, "reviews":[]
19662            }))
19663            .unwrap(),
19664        );
19665        resumed.state.save().unwrap();
19666        let error = resumed.execute().await.unwrap_err();
19667        assert!(
19668            error
19669                .to_string()
19670                .contains("selected implementation is held"),
19671            "{error:#}"
19672        );
19673        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), next);
19674    }
19675
19676    #[tokio::test]
19677    async fn driver_claim_waits_for_maintenance_before_starting_a_pass() {
19678        crate::run::pin_test_home();
19679        let mut runner = runner_at(RunStatus::Gating);
19680        runner.state.save().unwrap();
19681        let id = runner.state.id.clone();
19682        let passes = runner.state.passes.len();
19683        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
19684        let mut claiming = Box::pin(runner.claim_driver(None));
19685        std::future::poll_fn(|cx| {
19686            assert!(std::future::Future::poll(claiming.as_mut(), cx).is_pending());
19687            std::task::Poll::Ready(())
19688        })
19689        .await;
19690        assert_eq!(RunState::load(&id).unwrap().passes.len(), passes);
19691        drop(owner);
19692        let execution = tokio::time::timeout(Duration::from_secs(2), claiming)
19693            .await
19694            .unwrap()
19695            .unwrap();
19696        assert_eq!(execution.runner.state.passes.len(), passes + 1);
19697        assert!(execution.runner.state.resource_block.is_none());
19698        assert_eq!(
19699            execution.runner.state.liveness(false),
19700            crate::run::Liveness::Live
19701        );
19702        drop(execution);
19703        assert!(RunState::load(&id).unwrap().driver_exited);
19704    }
19705
19706    #[tokio::test]
19707    async fn a_failed_driver_lease_record_releases_the_claim_and_retained_state() {
19708        crate::run::pin_test_home();
19709        let mut runner = runner_at(RunStatus::Gating);
19710        runner.state.save().unwrap();
19711        // run.json can commit, but the subsequent lease metadata write fails.
19712        // Cleanup must run after releasing the short ownership lock.
19713        std::fs::create_dir(runner.state.dir().join("driver.json.tmp")).unwrap();
19714        assert!(runner.claim_driver(None).await.is_err());
19715        assert!(runner.state.driver_exited);
19716        assert_eq!(runner.state.driver_pid, None);
19717        let disk = RunState::load(&runner.state.id).unwrap();
19718        assert!(disk.driver_exited);
19719        assert_eq!(disk.driver_pid, None);
19720        assert_eq!(disk.status, RunStatus::Gating);
19721    }
19722
19723    #[tokio::test]
19724    async fn an_early_graph_error_releases_its_driver() {
19725        crate::run::pin_test_home();
19726        let mut runner = runner_at(RunStatus::Blocked);
19727        runner.state.config.graph.selected_implementer = Some("selected".into());
19728        runner.state.save().unwrap();
19729        assert!(runner.execute().await.is_err());
19730        let disk = RunState::load(&runner.state.id).unwrap();
19731        assert!(disk.driver_exited);
19732        assert_eq!(disk.driver_pid, None);
19733        assert_eq!(disk.status, RunStatus::Blocked);
19734    }
19735
19736    fn merge_repair_request(phase: crate::run::MergeRepairPhase) -> crate::run::MergeRepair {
19737        crate::run::MergeRepair {
19738            question: "repair-question".into(),
19739            head: "old-head".into(),
19740            pr: "https://github.com/o/r/pull/42".into(),
19741            reviews: vec![review_round(false, 1, 1, 1, false, true)],
19742            gate: vec![outcome(Some(0), false)],
19743            gate_head: Some("old-head".into()),
19744            gate_fixes: Vec::new(),
19745            pre_gate: Vec::new(),
19746            phase,
19747            failure: None,
19748        }
19749    }
19750
19751    #[tokio::test]
19752    async fn merge_repair_claim_refuses_concurrent_and_obsolete_drivers() {
19753        crate::run::pin_test_home();
19754        let mut runner = runner_at(RunStatus::Landing);
19755        runner.state.merge_repairs.push(merge_repair_request(
19756            crate::run::MergeRepairPhase::Requested,
19757        ));
19758        runner.state.save().unwrap();
19759        let claim = FixClaim::acquire(&runner.state.dir()).unwrap();
19760        assert!(
19761            runner
19762                .execute()
19763                .await
19764                .unwrap_err()
19765                .to_string()
19766                .contains("already running")
19767        );
19768        assert_eq!(
19769            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
19770            crate::run::MergeRepairPhase::Requested
19771        );
19772        drop(claim);
19773        let mut disk = runner.state.clone();
19774        disk.merge_repairs[0].phase = crate::run::MergeRepairPhase::Complete;
19775        disk.save().unwrap();
19776        assert!(
19777            runner
19778                .execute()
19779                .await
19780                .unwrap_err()
19781                .to_string()
19782                .contains("decision changed")
19783        );
19784        assert_eq!(
19785            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
19786            crate::run::MergeRepairPhase::Complete
19787        );
19788    }
19789
19790    #[test]
19791    fn merge_repair_starts_a_real_new_budget_and_preserves_old_evidence() {
19792        crate::run::pin_test_home();
19793        let mut runner = runner_at(RunStatus::Landing);
19794        let request = merge_repair_request(crate::run::MergeRepairPhase::Fixing);
19795        runner.state.reviews = request.reviews.clone();
19796        runner.state.gate = request.gate.clone();
19797        runner.state.gate_ran = true;
19798        runner.state.land_approval = Some(crate::run::LandApproval {
19799            question: "old".into(),
19800            head: "old-head".into(),
19801        });
19802        runner.state.merge_repairs.push(request);
19803        runner.begin_merge_repair_review(0).unwrap();
19804        assert_eq!(review_conclusion(&runner.state.reviews, 2), None);
19805        assert!(!runner.state.gate_status().ok());
19806        assert!(runner.state.land_approval.is_none());
19807        let disk = RunState::load(&runner.state.id).unwrap();
19808        assert_eq!(disk.merge_repairs[0].reviews[0].blocking, 1);
19809        assert!(disk.merge_repairs[0].gate[0].ok());
19810        assert_eq!(
19811            disk.merge_repairs[0].phase,
19812            crate::run::MergeRepairPhase::Reviewing
19813        );
19814        assert_eq!(disk.merge_repairs[0].pr, "https://github.com/o/r/pull/42");
19815        assert!(disk.reviews.is_empty());
19816    }
19817
19818    #[tokio::test]
19819    async fn merge_repair_interrupted_fixer_and_exhausted_generation_hold_without_repeating_work() {
19820        crate::run::pin_test_home();
19821        for phase in [
19822            crate::run::MergeRepairPhase::Fixing,
19823            crate::run::MergeRepairPhase::Requested,
19824        ] {
19825            let mut runner = runner_at(RunStatus::Landing);
19826            runner.state.config.graph.land_rounds = 0;
19827            runner.state.merge_repairs.push(merge_repair_request(phase));
19828            runner.state.save().unwrap();
19829            assert!(!runner.repair_merge_review().await.unwrap());
19830            assert_eq!(runner.state.status, RunStatus::Blocked);
19831            assert_eq!(
19832                runner.state.merge_repairs[0].phase,
19833                crate::run::MergeRepairPhase::Failed
19834            );
19835            let reason = runner.state.merge_repairs[0].failure.as_ref().unwrap();
19836            assert!(
19837                reason.contains(if phase == crate::run::MergeRepairPhase::Fixing {
19838                    "interrupted"
19839                } else {
19840                    "budget exhausted"
19841                })
19842            );
19843            assert!(runner.state.merge.is_none());
19844        }
19845    }
19846
19847    /// `park_here` folding in the reason `Pause::park_because` recorded -
19848    /// this is what lets an operator reading a run's events tell an
19849    /// interrupt-driven park from an ordinary shutdown park.
19850    #[test]
19851    fn park_here_folds_the_interrupt_reason_into_the_park_event() {
19852        crate::run::pin_test_home();
19853        let mut runner = runner_at(RunStatus::Implementing);
19854        let interrupt = Pause::new();
19855        runner.watch_interrupt(interrupt.clone());
19856
19857        interrupt.park_because("task a1b2 asked to run first");
19858
19859        assert!(runner.park_here().expect("park_here"));
19860        assert!(runner.state.parked);
19861        let last = runner.state.events.last().expect("a park event");
19862        assert_eq!(last.node, "park");
19863        assert!(
19864            last.message.contains("task a1b2 asked to run first"),
19865            "expected the interrupt reason in {:?}",
19866            last.message
19867        );
19868    }
19869
19870    /// The cause is stored on the pass when it parks, and the first cause a
19871    /// shared pause was given is the one that stays.
19872    #[test]
19873    fn park_here_records_the_structured_cause_and_the_first_one_wins() {
19874        crate::run::pin_test_home();
19875        let mut runner = runner_at(RunStatus::Implementing);
19876        runner.state.begin_pass();
19877        let shutdown = Pause::new();
19878        runner.on_pause(shutdown.clone());
19879        let upgrade = ParkCause::Upgrade {
19880            from: "0.121.0".to_owned(),
19881            to: Some("0.121.1".to_owned()),
19882        };
19883        shutdown.park_for(upgrade.clone());
19884        shutdown.park_for(ParkCause::Operator);
19885
19886        assert!(runner.park_here().expect("park_here"));
19887        assert_eq!(
19888            runner.state.passes[0].end,
19889            Some(crate::run::PassEnd::Parked { cause: upgrade })
19890        );
19891        let last = runner.state.events.last().expect("a park event");
19892        assert!(last.message.contains("0.121.0"), "{}", last.message);
19893    }
19894
19895    #[tokio::test]
19896    async fn driver_admission_accepts_a_freshly_minted_record_under_its_lease() {
19897        crate::run::pin_test_home();
19898        let mut runner = runner_at(RunStatus::Reviewing);
19899        runner.state.save().unwrap();
19900        let mut execution = runner.claim_driver(None).await.expect("first execution");
19901        assert_eq!(execution.runner.state.passes.len(), 1);
19902        execution
19903            .driver
19904            .finish(&mut execution.runner.state)
19905            .await
19906            .unwrap();
19907    }
19908
19909    #[tokio::test]
19910    async fn driver_admission_resumes_a_record_saved_before_its_first_claim() {
19911        crate::run::pin_test_home();
19912        let mut runner = runner_at(RunStatus::Reviewing);
19913        runner.state.config.agents = vec![conductor()];
19914        runner.state.config.graph.timeout_resource_wait = 0;
19915        runner.state.save().unwrap();
19916        let id = runner.state.id.clone();
19917        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
19918        assert!(runner.claim_driver(None).await.is_err());
19919        drop(owner);
19920        drop(runner);
19921        let mut resumed = Runner::resume(&id).unwrap();
19922        assert_eq!(resumed.state.driver_claimed, Some(false));
19923        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Dead);
19924        assert_eq!(resumed.state.liveness(true), crate::run::Liveness::Live);
19925        let mut execution = resumed
19926            .claim_driver(None)
19927            .await
19928            .expect("retry initial claim after reload");
19929        assert_eq!(execution.runner.state.driver_claimed, Some(true));
19930        assert_eq!(execution.runner.state.passes.len(), 1);
19931        execution
19932            .driver
19933            .finish(&mut execution.runner.state)
19934            .await
19935            .unwrap();
19936    }
19937
19938    #[tokio::test]
19939    async fn driver_admission_preclaim_marker_does_not_bypass_an_execution_lease() {
19940        crate::run::pin_test_home();
19941        let mut runner = runner_at(RunStatus::Reviewing);
19942        runner.state.config.agents = vec![conductor()];
19943        runner.state.save().unwrap();
19944        let id = runner.state.id.clone();
19945        let lease = crate::driver::maintenance(&crate::run::home(), &id).unwrap();
19946        let mut resumed = Runner::resume(&id).unwrap();
19947        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Live);
19948        assert!(resumed.claim_driver(None).await.is_err());
19949        assert!(RunState::load(&id).unwrap().passes.is_empty());
19950        drop(lease);
19951        let mut execution = resumed.claim_driver(None).await.unwrap();
19952        execution
19953            .driver
19954            .finish(&mut execution.runner.state)
19955            .await
19956            .unwrap();
19957    }
19958
19959    #[tokio::test]
19960    async fn driver_admission_accepts_legacy_unknown_process_with_a_proven_free_pass_lease() {
19961        crate::run::pin_test_home();
19962        let mut runner = runner_at(RunStatus::Reviewing);
19963        let state = &mut runner.state;
19964        state.config.agents = vec![conductor()];
19965        state.driver_claimed = None;
19966        state.driver_pid = Some(std::process::id());
19967        state.driver_started_at = None;
19968        state.begin_pass();
19969        state.save().unwrap();
19970        let lease = crate::driver::maintenance(&crate::run::home(), &state.id).unwrap();
19971        std::fs::write(
19972            state.dir().join("driver.json"),
19973            serde_json::to_vec(&serde_json::json!({
19974                "pid": state.driver_pid, "started_at": null,
19975                "pass": state.passes[0].started_at, "pass_index": state.passes[0].index,
19976            }))
19977            .unwrap(),
19978        )
19979        .unwrap();
19980        assert_eq!(state.liveness(false), crate::run::Liveness::Live);
19981        drop(lease);
19982        assert_eq!(state.liveness(false), crate::run::Liveness::Dead);
19983        let mut resumed = Runner::resume(&state.id).unwrap();
19984        assert!(!resumed.state.driver_exited);
19985        let mut execution = resumed
19986            .claim_driver(None)
19987            .await
19988            .expect("lease proves previous execution ended");
19989        assert_eq!(execution.runner.state.passes.len(), 2);
19990        execution
19991            .driver
19992            .finish(&mut execution.runner.state)
19993            .await
19994            .unwrap();
19995    }
19996
19997    #[tokio::test]
19998    async fn driver_admission_admits_a_legacy_record_without_a_claim_marker() {
19999        crate::run::pin_test_home();
20000        let mut runner = runner_at(RunStatus::Reviewing);
20001        let mut json = serde_json::to_value(&runner.state).unwrap();
20002        json.as_object_mut().unwrap().remove("driver_claimed");
20003        runner.state = serde_json::from_value(json).unwrap();
20004        assert_eq!(runner.state.driver_claimed, None);
20005        runner.state.save().unwrap();
20006        let mut execution = runner
20007            .claim_driver(None)
20008            .await
20009            .expect("the execution lease, not a missing marker, excludes a second driver");
20010        assert_eq!(execution.runner.state.passes.len(), 1);
20011        execution
20012            .driver
20013            .finish(&mut execution.runner.state)
20014            .await
20015            .unwrap();
20016    }
20017
20018    #[tokio::test]
20019    async fn driver_admission_refuses_a_proven_live_driver() {
20020        crate::run::pin_test_home();
20021        let mut runner = runner_at(RunStatus::Reviewing);
20022        let pid = std::process::id();
20023        runner.state.driver_pid = Some(pid);
20024        runner.state.driver_started_at = crate::proc::process_started_at(pid);
20025        assert!(runner.state.driver_started_at.is_some());
20026        runner.state.save().unwrap();
20027        let error = runner
20028            .claim_driver(None)
20029            .await
20030            .err()
20031            .expect("a live driver must refuse");
20032        assert!(error.to_string().contains("live driver"), "{error:#}");
20033        let saved = RunState::load(&runner.state.id).unwrap();
20034        assert_eq!(saved.driver_pid, Some(pid));
20035        assert_eq!(saved.status, RunStatus::Reviewing);
20036        assert!(saved.passes.is_empty());
20037    }
20038
20039    #[test]
20040    fn parking_resource_halt_persists_the_pass_once() {
20041        crate::run::pin_test_home();
20042        let mut runner = runner_at(RunStatus::Reviewing);
20043        runner.state.begin_pass();
20044        runner.state.resource_block = Some(crate::run::ResourceBlock {
20045            node: "fix".into(),
20046            kind: "shared build cache".into(),
20047            detail: "cancelled".into(),
20048            at: Timestamp::now(),
20049            cause: crate::run::ResourceBlockCause::Cancelled { park: None },
20050        });
20051        let cause = ParkCause::Upgrade {
20052            from: "old".into(),
20053            to: Some("new".into()),
20054        };
20055        runner.pause.park_for(cause.clone());
20056        // Both direct fixer exits and graph resource boundaries must complete
20057        // parking, rather than returning a stale Reviewing record.
20058        runner.stop_for_resource().unwrap();
20059        assert!(runner.resource_halt().unwrap());
20060        assert!(runner.park_here().unwrap());
20061        let saved = RunState::load(&runner.state.id).unwrap();
20062        assert!(saved.parked);
20063        assert_eq!(saved.status, RunStatus::Reviewing);
20064        assert!(saved.passes[0].ended_at.is_some());
20065        assert_eq!(
20066            saved.passes[0].end,
20067            Some(crate::run::PassEnd::Parked {
20068                cause: cause.clone()
20069            })
20070        );
20071        assert_eq!(
20072            saved.resource_block.unwrap().cause,
20073            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
20074        );
20075        assert_eq!(
20076            saved
20077                .events
20078                .iter()
20079                .filter(|event| event.node == "park")
20080                .count(),
20081            1
20082        );
20083    }
20084
20085    /// `watch_interrupt` and `on_pause` are genuinely independent: an ordinary
20086    /// shutdown `Pause` (what `Stop::park` hands every run, shared and never
20087    /// cleared) must not make a *different* run - one only watching its own,
20088    /// unshared interrupt `Pause` - see itself as parked. If a future change
20089    /// ever collapsed these back into one handle, the interrupt scheduler
20090    /// would park every run for the rest of the daemon's life, not just the
20091    /// one it meant to interrupt.
20092    #[test]
20093    fn the_stop_level_pause_and_a_runs_interrupt_pause_do_not_leak_into_each_other() {
20094        crate::run::pin_test_home();
20095        let mut runner = runner_at(RunStatus::Implementing);
20096        let shutdown = Pause::new();
20097        runner.on_pause(shutdown.clone());
20098        let interrupt = Pause::new();
20099        runner.watch_interrupt(interrupt.clone());
20100
20101        // Nobody has asked for anything yet.
20102        assert!(!runner.park_here().expect("park_here"));
20103        assert!(!runner.state.parked);
20104
20105        // Only the interrupt handle fires; the shutdown handle stays clear.
20106        interrupt.park_because("test");
20107        assert!(!shutdown.parked());
20108        assert!(runner.park_here().expect("park_here"));
20109    }
20110
20111    /// The property every prior attempt at this feature failed to pin down:
20112    /// asking a run to park while one of its nodes has a real, in-flight
20113    /// async operation running (an agent call, in production) must not cut
20114    /// that operation short. `park_here` is only ever consulted *between*
20115    /// `execute`'s node calls - see its own doc - so nothing inside a node
20116    /// can observe a park request until the node itself returns. This proves
20117    /// that structurally, with real `tokio` concurrency and a channel
20118    /// handshake (never a sleep, which would only prove "usually", not
20119    /// "cannot"): the "node" below reports that it has genuinely started,
20120    /// and only then is the park requested; the node still has to be told to
20121    /// finish before `park_here` is ever called, exactly mirroring every
20122    /// `self.some_node().await; if self.park_here()? { return Ok(()); }` pair
20123    /// in `execute`.
20124    #[tokio::test]
20125    async fn a_park_request_made_mid_node_only_takes_effect_at_the_next_boundary() {
20126        crate::run::pin_test_home();
20127        let mut runner = runner_at(RunStatus::Implementing);
20128        let interrupt = Pause::new();
20129        runner.watch_interrupt(interrupt.clone());
20130
20131        let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>();
20132        let (finish_tx, finish_rx) = tokio::sync::oneshot::channel::<()>();
20133
20134        // Stands in for one node's in-flight agent call: it proves it has
20135        // genuinely started, then blocks - exactly as a spawned CLI process
20136        // does - until told to finish.
20137        let node = async move {
20138            started_tx.send(()).expect("send started");
20139            finish_rx.await.expect("recv finish");
20140            "node finished"
20141        };
20142
20143        let interrupter = async move {
20144            started_rx.await.expect("recv started");
20145            // The call is now genuinely in flight. Ask it to park.
20146            interrupt.park_because("higher-priority task waiting");
20147            // Nothing the node does can observe this yet - there is no
20148            // check inside it, by construction - so let the executor run
20149            // anything pending and then let the node finish on its own.
20150            tokio::task::yield_now().await;
20151            finish_tx.send(()).expect("send finish");
20152        };
20153
20154        let (node_result, ()) = tokio::join!(node, interrupter);
20155        assert_eq!(
20156            node_result, "node finished",
20157            "the in-flight call ran to completion"
20158        );
20159
20160        // Only now, at the boundary the real `execute` would check right
20161        // after this node, does the park take effect.
20162        assert!(runner.park_here().expect("park_here"));
20163        assert!(runner.state.parked);
20164    }
20165
20166    /// A run parked mid-competition carries every field it had accumulated
20167    /// through the exact same disk round-trip an ordinary resume uses -
20168    /// `RunState::save`/`RunState::load`, which is all `Runner::resume` is.
20169    /// Nothing about parking for an interrupt is a special case of that path;
20170    /// this is what proves it rather than assuming it.
20171    #[test]
20172    fn a_run_parked_for_an_interrupt_resumes_with_nothing_lost() {
20173        crate::run::pin_test_home();
20174        let mut runner = runner_at(RunStatus::Judging);
20175        // `Runner::resume` re-resolves roles from the saved config, which
20176        // refuses an empty roster - give it the same minimal one `conductor`
20177        // itself uses.
20178        runner.state.config.agents = vec![conductor()];
20179        runner.state.candidates = vec![Candidate {
20180            index: 0,
20181            label: 'A',
20182            agent: "alpha".to_owned(),
20183            branch: "magi/x/A".to_owned(),
20184            worktree: PathBuf::from("/nonexistent/worktree"),
20185            summary: "did the thing".to_owned(),
20186            stat: "1 file changed".to_owned(),
20187            files: 1,
20188            commits: 1,
20189            empty: false,
20190            failed: None,
20191            verified_noop: None,
20192            duration_ms: 1234,
20193            folded: false,
20194        }];
20195        let run_id = runner.state.id.clone();
20196
20197        let interrupt = Pause::new();
20198        runner.watch_interrupt(interrupt.clone());
20199        interrupt.park_because("task c3d4 asked to run first");
20200        assert!(runner.park_here().expect("park_here"));
20201
20202        let resumed = Runner::resume(&run_id).expect("resume");
20203        assert_eq!(resumed.state.candidates.len(), 1);
20204        assert_eq!(resumed.state.candidates[0].summary, "did the thing");
20205        assert_eq!(resumed.state.candidates[0].branch, "magi/x/A");
20206        assert_eq!(resumed.state.status, runner.state.status);
20207        assert!(
20208            resumed.state.parked,
20209            "still parked until `execute` actually walks the graph again"
20210        );
20211        assert!(resumed.state.events.iter().any(|e| e.node == "park"));
20212    }
20213
20214    /// A fresh open question on `run`, stored and handed back for assertions.
20215    fn ask_open_question(store: &ask::Questions, run: &str) -> ask::Question {
20216        let mut q = ask::Question::new(
20217            run.to_owned(),
20218            "implement".to_owned(),
20219            "impl-A".to_owned(),
20220            "Which storage backend should the cache use?".to_owned(),
20221            String::new(),
20222            vec!["SQLite".to_owned(), "Redis".to_owned()],
20223        );
20224        store.put(&mut q).unwrap();
20225        q
20226    }
20227
20228    #[test]
20229    fn a_failed_runs_open_question_is_abandoned() {
20230        ask_test_home();
20231        let store = ask::Questions::open();
20232        let mut runner = runner_at(RunStatus::Failed);
20233        let run = runner.state.id.clone();
20234        let q = ask_open_question(&store, &run);
20235
20236        runner.settle_questions();
20237
20238        let back = store.get(&q.id).unwrap();
20239        assert!(
20240            !back.status.open(),
20241            "the seat that asked died with the run; nobody is left to read an answer"
20242        );
20243        assert!(
20244            back.detail.contains(&run) && back.detail.contains("failed"),
20245            "the reason names what the run became, not just that it is gone: {}",
20246            back.detail
20247        );
20248    }
20249
20250    #[test]
20251    fn a_merged_runs_open_question_is_abandoned_too() {
20252        ask_test_home();
20253        let store = ask::Questions::open();
20254        // A run that finishes cleanly still leaves nobody to read an answer -
20255        // this is not only a failure-path cleanup.
20256        for status in [RunStatus::Merged, RunStatus::Ready] {
20257            let mut runner = runner_at(status);
20258            let run = runner.state.id.clone();
20259            let q = ask_open_question(&store, &run);
20260
20261            runner.settle_questions();
20262
20263            let back = store.get(&q.id).unwrap();
20264            assert!(
20265                !back.status.open(),
20266                "{status:?} run's question must not outlive the run"
20267            );
20268        }
20269    }
20270
20271    #[test]
20272    fn a_still_resumable_runs_open_question_is_left_alone() {
20273        ask_test_home();
20274        let store = ask::Questions::open();
20275        // `Blocked` and `Stalled` can still be resumed — the candidates, the
20276        // review round and the seat sessions are all still on disk — so a
20277        // question asked mid-round may yet get a real answer from a real
20278        // resume. Sweeping it here would be exactly the failure mode this
20279        // whole feature exists to avoid on the other side.
20280        for status in [RunStatus::Blocked, RunStatus::Stalled] {
20281            let mut runner = runner_at(status);
20282            let run = runner.state.id.clone();
20283            let q = ask_open_question(&store, &run);
20284
20285            runner.settle_questions();
20286
20287            let back = store.get(&q.id).unwrap();
20288            assert!(
20289                back.status.open(),
20290                "{status:?} is still alive; the question must still be waiting"
20291            );
20292        }
20293    }
20294
20295    #[test]
20296    fn settle_questions_never_touches_an_already_answered_question() {
20297        ask_test_home();
20298        let store = ask::Questions::open();
20299        let mut runner = runner_at(RunStatus::Failed);
20300        let run = runner.state.id.clone();
20301        let mut q = ask_open_question(&store, &run);
20302        q.answer(crate::ask::Answer::Choice("SQLite".to_owned()))
20303            .unwrap();
20304        store.put(&mut q).unwrap();
20305
20306        // Called twice, the way a crash-recovered daemon reclaim and the
20307        // graph's own cleanup both can for the same run — `abandon_for_run`
20308        // only ever touches what is still open, so this must be inert both
20309        // times, not merely the second.
20310        runner.settle_questions();
20311        runner.settle_questions();
20312
20313        let back = store.get(&q.id).unwrap();
20314        assert_eq!(
20315            back.status,
20316            ask::QuestionStatus::Answered,
20317            "a real answer is a decision on record, never overwritten by a sweep"
20318        );
20319    }
20320
20321    #[tokio::test]
20322    async fn fold_reclaims_only_proven_idle_isolated_outputs() {
20323        let tmp = tempfile::tempdir().unwrap();
20324        let home = tmp.path().join("home");
20325        let repo = tmp.path().join("repo");
20326        std::fs::create_dir(&home).unwrap();
20327        std::fs::create_dir(&repo).unwrap();
20328        init_repo(&repo);
20329
20330        let mut config = Config::default();
20331        config.graph.worktree_root = Some(tmp.path().join("wt"));
20332        config.verify.build_cache = crate::config::BuildCache::Isolated;
20333        let mut state = RunState::new(
20334            repo.clone(),
20335            "main".into(),
20336            "base".into(),
20337            "fold fixture".into(),
20338            config,
20339        );
20340        let root = state.worktree_root();
20341        let mut outputs = Vec::new();
20342        for name in ["idle", "busy"] {
20343            let checkout = root.join(name);
20344            git::worktree_add_detached(&repo, &checkout, "main")
20345                .await
20346                .unwrap();
20347            let target = crate::build_target::resolve(&home, &checkout).unwrap();
20348            let output = target.join("generated");
20349            std::fs::write(&output, name).unwrap();
20350            outputs.push((target, output));
20351        }
20352        let unknown = crate::build_target::root(&home)
20353            .join("00000000-0000-0000-0000-000000000000")
20354            .join("target");
20355        std::fs::create_dir_all(&unknown).unwrap();
20356        let unowned = unknown.join("generated");
20357        std::fs::write(&unowned, "keep").unwrap();
20358        let owner = crate::cache::Owner::here("fixture", "build", "busy", &root.join("busy"), "");
20359        let crate::cache::AcquireOutcome::Acquired(_lease) =
20360            crate::cache::try_acquire(&home, &outputs[1].0, &owner).unwrap()
20361        else {
20362            panic!("fixture target must be free");
20363        };
20364
20365        fold_run(&mut state, true, &home).await.unwrap();
20366        assert!(!root.exists());
20367        assert!(!outputs[0].1.exists());
20368        assert!(outputs[1].1.is_file());
20369        assert!(unowned.is_file());
20370    }
20371
20372    /// `fold_run(&mut state, drop_winner = false)` is exactly the call
20373    /// `clean::fold_due` makes for a `Ready`/`Failed` run - one that finished
20374    /// without merging, whose winner is still the operator's answer to read.
20375    /// Nothing previously called `fold_run` itself with a real `tally`, so
20376    /// this is the first test to pin down the one distinction the whole
20377    /// automatic-fold feature depends on: the winner's worktree and branch
20378    /// must survive, everything else sharing the run's worktree bay - a
20379    /// loser, standing in for a judge/review worktree too, since `fold_run`'s
20380    /// second sweep treats every non-winner directory under the bay alike -
20381    /// must not.
20382    #[tokio::test]
20383    async fn fold_run_keeps_only_the_winner_when_the_winner_is_not_dropped() {
20384        crate::run::pin_test_home();
20385        let tmp = tempfile::tempdir().expect("tempdir");
20386        let repo = tmp.path().join("repo");
20387        std::fs::create_dir_all(&repo).unwrap();
20388        init_repo(&repo);
20389
20390        let mut config = Config::default();
20391        config.graph.worktree_root = Some(tmp.path().join("wt"));
20392
20393        let mut state = RunState::new(
20394            repo.clone(),
20395            "main".to_owned(),
20396            "deadbeef".to_owned(),
20397            "task".to_owned(),
20398            config,
20399        );
20400        let root = state.worktree_root();
20401        let wt_a = root.join("cand-A");
20402        let wt_b = root.join("cand-B");
20403        git::worktree_add_branch(&repo, &wt_a, "magi/x/A", "main")
20404            .await
20405            .expect("worktree A");
20406        git::worktree_add_branch(&repo, &wt_b, "magi/x/B", "main")
20407            .await
20408            .expect("worktree B");
20409
20410        state.candidates = vec![
20411            Candidate {
20412                index: 0,
20413                label: 'A',
20414                agent: "alpha".to_owned(),
20415                branch: "magi/x/A".to_owned(),
20416                worktree: wt_a.clone(),
20417                summary: String::new(),
20418                stat: String::new(),
20419                files: 0,
20420                commits: 0,
20421                empty: false,
20422                failed: None,
20423                verified_noop: None,
20424                duration_ms: 0,
20425                folded: false,
20426            },
20427            Candidate {
20428                index: 1,
20429                label: 'B',
20430                agent: "beta".to_owned(),
20431                branch: "magi/x/B".to_owned(),
20432                worktree: wt_b.clone(),
20433                summary: String::new(),
20434                stat: String::new(),
20435                files: 0,
20436                commits: 0,
20437                empty: false,
20438                failed: None,
20439                verified_noop: None,
20440                duration_ms: 0,
20441                folded: false,
20442            },
20443        ];
20444        state.tally = Some(Tally {
20445            first_choice: BTreeMap::from([('A', 1)]),
20446            borda: BTreeMap::new(),
20447            winner: 'A',
20448            rankings: 1,
20449            unanimous_initial: true,
20450            deliberated: false,
20451            changed_votes: 0,
20452            unanimous_final: true,
20453            tie_break: None,
20454            judges: 1,
20455            present: 1,
20456            quorum: 1,
20457            met_quorum: true,
20458            uncontested: None,
20459        });
20460        state.status = RunStatus::Ready;
20461
20462        fold_run(&mut state, false, &crate::run::home())
20463            .await
20464            .expect("fold_run");
20465
20466        assert!(wt_a.exists(), "the unmerged winner's worktree survives");
20467        assert!(
20468            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
20469            "the unmerged winner's branch survives"
20470        );
20471        assert!(
20472            !state.candidates[0].folded,
20473            "the winner is not marked folded"
20474        );
20475
20476        assert!(!wt_b.exists(), "the loser's worktree is removed");
20477        assert!(
20478            !git::branch_exists(&repo, "magi/x/B").await.unwrap(),
20479            "the loser's branch is removed"
20480        );
20481        assert!(state.candidates[1].folded, "the loser is marked folded");
20482    }
20483
20484    #[tokio::test]
20485    #[cfg(unix)]
20486    async fn fold_run_waits_for_shared_lock_before_removing_worktrees_branches_or_config() {
20487        use std::os::fd::AsRawFd as _;
20488        use std::time::Duration;
20489
20490        let tmp = tempfile::tempdir().unwrap();
20491        let repo = tmp.path().join("repo");
20492        std::fs::create_dir_all(&repo).unwrap();
20493        init_repo(&repo);
20494        let common = repo.join(".git");
20495        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
20496        let home = tmp.path().join("home");
20497        let mut config = Config::default();
20498        config.coordination = crate::config::test_coordination();
20499        config.graph.worktree_root = Some(tmp.path().join("wt"));
20500        config.graph.timeout_resource_wait = 1;
20501        let mut state = RunState::new(
20502            repo.clone(),
20503            "main".into(),
20504            "deadbeef".into(),
20505            "task".into(),
20506            config,
20507        );
20508        let root = state.worktree_root();
20509        let candidate = root.join("cand-A");
20510        let reviewer = root.join("review-1");
20511        let branch = state.branch_for('A');
20512        git::worktree_add_branch(&repo, &candidate, &branch, "main")
20513            .await
20514            .unwrap();
20515        git::worktree_add_detached(&repo, &reviewer, "main")
20516            .await
20517            .unwrap();
20518        git::acquire_worktree_config(&repo).await.unwrap();
20519        state.enabled_worktree_config = true;
20520        state.status = RunStatus::Ready;
20521        state.candidates.push(Candidate {
20522            index: 0,
20523            label: 'A',
20524            agent: "implement".into(),
20525            branch: branch.clone(),
20526            worktree: candidate.clone(),
20527            summary: String::new(),
20528            stat: String::new(),
20529            files: 0,
20530            commits: 0,
20531            empty: false,
20532            failed: None,
20533            verified_noop: None,
20534            duration_ms: 0,
20535            folded: false,
20536        });
20537        state.save_under(&home).unwrap();
20538        let config_before = std::fs::read(common.join("config")).unwrap();
20539        let worktrees_before = git::git(&repo, &["worktree", "list", "--porcelain"])
20540            .await
20541            .unwrap();
20542        // A separate OS handle bypasses the launcher's local gate, exactly as
20543        // an external updater does, and must still prevent all folding work.
20544        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
20545        assert_eq!(
20546            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
20547            0
20548        );
20549        let mut fold = Box::pin(fold_run(&mut state, true, &home));
20550        assert!(
20551            tokio::time::timeout(Duration::from_millis(200), &mut fold)
20552                .await
20553                .is_err()
20554        );
20555        assert!(candidate.exists());
20556        assert!(reviewer.exists());
20557        assert!(git::branch_exists(&repo, &branch).await.unwrap());
20558        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
20559        assert_eq!(
20560            git::git(&repo, &["worktree", "list", "--porcelain"])
20561                .await
20562                .unwrap(),
20563            worktrees_before
20564        );
20565        let error = tokio::time::timeout(Duration::from_secs(3), &mut fold)
20566            .await
20567            .unwrap()
20568            .unwrap_err();
20569        assert!(error.is::<crate::repo_lock::ResourceBlocked>());
20570        drop(fold);
20571        assert!(candidate.exists() && reviewer.exists());
20572        assert!(!state.candidates[0].folded && state.enabled_worktree_config);
20573        assert_eq!(
20574            state.resource_block.as_ref().unwrap().kind,
20575            "repository coordination"
20576        );
20577        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
20578        drop(external);
20579        let mut fold = Box::pin(fold_run(&mut state, true, &home));
20580        let removed = tokio::time::timeout(Duration::from_secs(10), &mut fold)
20581            .await
20582            .unwrap()
20583            .unwrap();
20584        drop(fold);
20585        assert!(removed.contains(&branch));
20586        assert!(!root.exists());
20587        assert!(!git::branch_exists(&repo, &branch).await.unwrap());
20588        assert!(state.candidates[0].folded);
20589        assert!(!state.enabled_worktree_config);
20590        assert_ne!(std::fs::read(common.join("config")).unwrap(), config_before);
20591        let enabled = git::git_raw(
20592            &repo,
20593            &["config", "--local", "--get", "extensions.worktreeConfig"],
20594        )
20595        .await
20596        .unwrap();
20597        assert!(!enabled.ok(), "the last config reference was released");
20598    }
20599
20600    /// A branch handed to a later run is that run's (and its pull request's):
20601    /// folding the run that released it must not delete it.
20602    #[tokio::test]
20603    async fn fold_run_keeps_a_branch_that_was_handed_to_a_later_run() {
20604        let tmp = tempfile::tempdir().expect("tempdir");
20605        let repo = tmp.path().join("repo");
20606        std::fs::create_dir_all(&repo).unwrap();
20607        init_repo(&repo);
20608        let home = tmp.path().join("home");
20609
20610        let mut config = Config::default();
20611        config.graph.worktree_root = Some(tmp.path().join("wt"));
20612        let mut state = RunState::new(
20613            repo.clone(),
20614            "main".to_owned(),
20615            "deadbeef".to_owned(),
20616            "task".to_owned(),
20617            config,
20618        );
20619        // The worktree is already gone (released); the branch survives.
20620        git::git(&repo, &["branch", "magi/x/A", "main"])
20621            .await
20622            .expect("branch");
20623        state.candidates = vec![Candidate {
20624            index: 0,
20625            label: 'A',
20626            agent: "alpha".to_owned(),
20627            branch: "magi/x/A".to_owned(),
20628            worktree: state.worktree_root().join("cand-A"),
20629            summary: String::new(),
20630            stat: String::new(),
20631            files: 0,
20632            commits: 0,
20633            empty: false,
20634            failed: None,
20635            verified_noop: None,
20636            duration_ms: 0,
20637            folded: true,
20638        }];
20639        state.released_to = Some("20260901-000000-new1".to_owned());
20640        state.released_branches = vec!["magi/x/A".to_owned()];
20641
20642        fold_run(&mut state, true, &home).await.expect("fold_run");
20643        state.status = RunStatus::Merged;
20644        state.base_commit = git::rev_parse(&repo, "main").await.unwrap();
20645        state.merge = Some(crate::run::MergeOutcome {
20646            mode: MergeMode::Pr,
20647            ok: true,
20648            detail: "confirmed merged".into(),
20649            empty: false,
20650        });
20651        fold_run(&mut state, true, &home)
20652            .await
20653            .expect("merged fold");
20654
20655        assert!(
20656            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
20657            "the handed-over branch survives a fold"
20658        );
20659    }
20660
20661    /// A winner with nothing ahead of the base is caught before `gh` is ever
20662    /// asked for a pull request, and the message carries what the task's
20663    /// references resolved to.
20664    #[tokio::test]
20665    async fn an_empty_winner_is_detected_before_a_pull_request_is_attempted() {
20666        let tmp = tempfile::tempdir().expect("tempdir");
20667        let repo = tmp.path().join("repo");
20668        std::fs::create_dir_all(&repo).unwrap();
20669        init_repo(&repo);
20670        let run = |args: &[&str]| {
20671            let out = std::process::Command::new("git")
20672                .quiet()
20673                .args(args)
20674                .current_dir(&repo)
20675                .output()
20676                .expect("spawn git");
20677            assert!(out.status.success(), "git {args:?}");
20678        };
20679        run(&["branch", "magi/x/A"]);
20680        run(&["checkout", "-q", "-b", "magi/x/B"]);
20681        std::fs::write(repo.join("f.txt"), "x\n").unwrap();
20682        run(&["add", "-A"]);
20683        run(&["commit", "-q", "-m", "work"]);
20684        run(&["checkout", "-q", "main"]);
20685
20686        // A pull request is compared against the remote's base, so the
20687        // fixture needs one. Before it exists nothing can be read, and the
20688        // answer must be "not empty".
20689        let probe = RunState::new(
20690            repo.clone(),
20691            "main".to_owned(),
20692            "deadbeef".to_owned(),
20693            "task".to_owned(),
20694            Config::default(),
20695        );
20696        assert!(!merge_is_empty(&repo, &probe, "magi/x/A", MergeMode::Pr).await);
20697        let bare = tmp.path().join("origin.git");
20698        let out = std::process::Command::new("git")
20699            .quiet()
20700            .args(["init", "-q", "--bare"])
20701            .arg(&bare)
20702            .output()
20703            .expect("spawn git");
20704        assert!(out.status.success(), "git init --bare");
20705        run(&["remote", "add", "origin", bare.to_str().unwrap()]);
20706        run(&["push", "-q", "origin", "main"]);
20707
20708        let mut state = RunState::new(
20709            repo.clone(),
20710            "main".to_owned(),
20711            "deadbeef".to_owned(),
20712            "task".to_owned(),
20713            Config::default(),
20714        );
20715        state.seeds = vec![refs::Seed {
20716            token: "magi/27b2/A".to_owned(),
20717            kind: refs::SeedKind::Unresolved,
20718            sha: String::new(),
20719            branch: true,
20720            detail: "no branch or commit named magi/27b2/A".to_owned(),
20721        }];
20722
20723        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Pr).await);
20724        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Local).await);
20725        assert!(!merge_is_empty(&repo, &state, "magi/x/B", MergeMode::Pr).await);
20726        let detail = empty_candidate_detail(&state, "main");
20727        assert!(detail.starts_with("empty candidate"), "{detail}");
20728        assert!(!detail.contains("magi/27b2/A"), "{detail}");
20729        assert!(detail.contains("--start-from"), "{detail}");
20730    }
20731
20732    /// `status == Ready` used to be read as "this is the harmless
20733    /// `MergeMode::None` no-op path, nothing to guard" (graph.rs, prior to
20734    /// this test). But `land` sets the very same status when a `MergeMode::Pr`
20735    /// run's PR was closed without merging — and reentering `merge` with
20736    /// `mode` still `Pr` does not know the difference, so it pushed and
20737    /// opened a second pull request. `mode == Local` reproduces the same
20738    /// blind spot without a network call: reentry must not attempt another
20739    /// git merge once this node has already recorded an outcome.
20740    #[tokio::test]
20741    async fn merge_does_not_reattempt_once_a_run_has_concluded() {
20742        let tmp = tempfile::tempdir().expect("tempdir");
20743        let repo = tmp.path().join("repo");
20744        std::fs::create_dir_all(&repo).unwrap();
20745        init_repo(&repo);
20746
20747        let mut config = Config::default();
20748        config.merge.mode = MergeMode::Local;
20749
20750        let mut state = RunState::new(
20751            repo.clone(),
20752            "main".to_owned(),
20753            "deadbeef".to_owned(),
20754            "task".to_owned(),
20755            config,
20756        );
20757        state.candidates = vec![Candidate {
20758            index: 0,
20759            label: 'A',
20760            agent: "alpha".to_owned(),
20761            branch: "does-not-exist".to_owned(),
20762            worktree: repo.clone(),
20763            summary: String::new(),
20764            stat: String::new(),
20765            files: 0,
20766            commits: 0,
20767            empty: false,
20768            failed: None,
20769            verified_noop: None,
20770            duration_ms: 0,
20771            folded: false,
20772        }];
20773        state.tally = Some(Tally {
20774            first_choice: BTreeMap::from([('A', 1)]),
20775            borda: BTreeMap::new(),
20776            winner: 'A',
20777            rankings: 1,
20778            unanimous_initial: true,
20779            deliberated: false,
20780            changed_votes: 0,
20781            unanimous_final: true,
20782            tie_break: None,
20783            judges: 0,
20784            present: 0,
20785            quorum: 0,
20786            met_quorum: true,
20787            uncontested: Some("only candidate A produced a change".to_owned()),
20788        });
20789        state.reviews = vec![ReviewRound {
20790            round: 1,
20791            head: "deadbeef".to_owned(),
20792            verified_head: None,
20793            verified_at: None,
20794            reviews: Vec::new(),
20795            e2e: Vec::new(),
20796            fix: None,
20797            blocking: 0,
20798            answered: 0,
20799            expected: 0,
20800            clean: true,
20801            verify_retried: false,
20802            e2e_deferred: false,
20803            e2e_defer_reason: None,
20804            progressed: false,
20805            vote_split: false,
20806            reconsideration: Vec::new(),
20807            verdict: None,
20808        }];
20809        state.gate = vec![CommandOutcome {
20810            command: "test".to_owned(),
20811            code: Some(0),
20812            output_tail: String::new(),
20813            duration_ms: 0,
20814            resource_blocked: false,
20815        }];
20816        state.gate_ran = true;
20817        // Reached its conclusion already — e.g. `land` closing the PR without
20818        // merging it, which (like the honest `MergeMode::None` path) leaves
20819        // `status` at `Ready`. The recorded outcome is what actually marks
20820        // this node done.
20821        state.status = RunStatus::Ready;
20822        state.merge = Some(MergeOutcome {
20823            mode: MergeMode::Local,
20824            ok: false,
20825            detail: "already concluded".to_owned(),
20826            empty: false,
20827        });
20828
20829        let mut runner = Runner {
20830            state,
20831            roles: ResolvedRoles {
20832                implementers: Vec::new(),
20833                judges: Vec::new(),
20834                reviewers: Vec::new(),
20835                fixer: None,
20836                conductor: conductor(),
20837                implementer_roster: Vec::new(),
20838                judge_roster: Vec::new(),
20839                reviewer_roster: Vec::new(),
20840            },
20841            sem: Arc::new(Semaphore::new(1)),
20842            pause: Pause::new(),
20843            interrupt: Pause::new(),
20844        };
20845
20846        runner.merge().await.expect("merge");
20847
20848        assert_eq!(
20849            runner.state.status,
20850            RunStatus::Ready,
20851            "a concluded run's status must not change on reentry"
20852        );
20853        assert_eq!(
20854            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
20855            Some("already concluded"),
20856            "merge must not run again once the node already recorded an outcome"
20857        );
20858    }
20859
20860    /// `gate` leaves `state.gate_ran` false both before it has ever run and
20861    /// when its last attempt was resource-blocked (the shared build cache
20862    /// could not be acquired or confirmed fresh in time - see
20863    /// `CommandOutcome::resource_blocked`'s own doc). Trusting the empty
20864    /// `Vec` this also leaves behind used to read as "nothing failed" and let
20865    /// a run merge a tree the gate never actually checked - exactly the case
20866    /// a contended cache produces on every retry until it clears. `merge`
20867    /// must refuse until `gate` has actually recorded an attempt.
20868    #[tokio::test]
20869    async fn merge_refuses_a_gate_that_has_not_actually_run() {
20870        let tmp = tempfile::tempdir().expect("tempdir");
20871        let repo = tmp.path().join("repo");
20872        std::fs::create_dir_all(&repo).unwrap();
20873        init_repo(&repo);
20874
20875        let mut config = Config::default();
20876        config.merge.mode = MergeMode::Local;
20877
20878        let mut state = RunState::new(
20879            repo.clone(),
20880            "main".to_owned(),
20881            "deadbeef".to_owned(),
20882            "task".to_owned(),
20883            config,
20884        );
20885        state.candidates = vec![Candidate {
20886            index: 0,
20887            label: 'A',
20888            agent: "alpha".to_owned(),
20889            branch: "does-not-exist".to_owned(),
20890            worktree: repo.clone(),
20891            summary: String::new(),
20892            stat: String::new(),
20893            files: 0,
20894            commits: 0,
20895            empty: false,
20896            failed: None,
20897            verified_noop: None,
20898            duration_ms: 0,
20899            folded: false,
20900        }];
20901        state.tally = Some(Tally {
20902            first_choice: BTreeMap::from([('A', 1)]),
20903            borda: BTreeMap::new(),
20904            winner: 'A',
20905            rankings: 1,
20906            unanimous_initial: true,
20907            deliberated: false,
20908            changed_votes: 0,
20909            unanimous_final: true,
20910            tie_break: None,
20911            judges: 0,
20912            present: 0,
20913            quorum: 0,
20914            met_quorum: true,
20915            uncontested: Some("only candidate A produced a change".to_owned()),
20916        });
20917        state.reviews = vec![ReviewRound {
20918            round: 1,
20919            head: "deadbeef".to_owned(),
20920            verified_head: None,
20921            verified_at: None,
20922            reviews: Vec::new(),
20923            e2e: Vec::new(),
20924            fix: None,
20925            blocking: 0,
20926            answered: 0,
20927            expected: 0,
20928            clean: true,
20929            verify_retried: false,
20930            e2e_deferred: false,
20931            e2e_defer_reason: None,
20932            progressed: false,
20933            vote_split: false,
20934            reconsideration: Vec::new(),
20935            verdict: None,
20936        }];
20937        // The point: `gate` has not recorded anything yet.
20938        state.gate = Vec::new();
20939        state.gate_ran = false;
20940        state.status = RunStatus::Gating;
20941
20942        let mut runner = Runner {
20943            state,
20944            roles: ResolvedRoles {
20945                implementers: Vec::new(),
20946                judges: Vec::new(),
20947                reviewers: Vec::new(),
20948                fixer: None,
20949                conductor: conductor(),
20950                implementer_roster: Vec::new(),
20951                judge_roster: Vec::new(),
20952                reviewer_roster: Vec::new(),
20953            },
20954            sem: Arc::new(Semaphore::new(1)),
20955            pause: Pause::new(),
20956            interrupt: Pause::new(),
20957        };
20958
20959        runner.merge().await.expect("merge");
20960
20961        assert!(
20962            runner.state.merge.is_none(),
20963            "an empty gate must never be read as a passing one: {:?}",
20964            runner.state.merge
20965        );
20966    }
20967
20968    /// The `shoka` repro this schema bump exists for: `verify.gate` has no
20969    /// commands configured and `merge.mode` is `none` (a review-only run).
20970    /// `gate` must still record a real attempt — zero commands, vacuously
20971    /// passed — rather than leaving `state.gate` empty in a way `merge`
20972    /// cannot tell apart from "never ran"; otherwise the run reaches
20973    /// `Gating` and can never leave it. See `RunState::gate_ran`'s own doc.
20974    #[tokio::test]
20975    async fn gate_and_merge_reach_ready_when_no_gate_commands_are_configured() {
20976        let tmp = tempfile::tempdir().expect("tempdir");
20977        let repo = tmp.path().join("repo");
20978        std::fs::create_dir_all(&repo).unwrap();
20979        init_repo(&repo);
20980
20981        // Default config: `verify.gate` empty, `merge.mode` is `none`.
20982        let config = Config::default();
20983
20984        let mut state = RunState::new(
20985            repo.clone(),
20986            "main".to_owned(),
20987            "deadbeef".to_owned(),
20988            "task".to_owned(),
20989            config,
20990        );
20991        state.candidates = vec![Candidate {
20992            index: 0,
20993            label: 'A',
20994            agent: "alpha".to_owned(),
20995            branch: "does-not-exist".to_owned(),
20996            worktree: repo.clone(),
20997            summary: String::new(),
20998            stat: String::new(),
20999            files: 0,
21000            commits: 0,
21001            empty: false,
21002            failed: None,
21003            verified_noop: None,
21004            duration_ms: 0,
21005            folded: false,
21006        }];
21007        state.tally = Some(Tally {
21008            first_choice: BTreeMap::from([('A', 1)]),
21009            borda: BTreeMap::new(),
21010            winner: 'A',
21011            rankings: 1,
21012            unanimous_initial: true,
21013            deliberated: false,
21014            changed_votes: 0,
21015            unanimous_final: true,
21016            tie_break: None,
21017            judges: 0,
21018            present: 0,
21019            quorum: 0,
21020            met_quorum: true,
21021            uncontested: Some("only candidate A produced a change".to_owned()),
21022        });
21023        state.reviews = vec![ReviewRound {
21024            round: 1,
21025            head: "deadbeef".to_owned(),
21026            verified_head: None,
21027            verified_at: None,
21028            reviews: Vec::new(),
21029            e2e: Vec::new(),
21030            fix: None,
21031            blocking: 0,
21032            answered: 0,
21033            expected: 0,
21034            clean: true,
21035            verify_retried: false,
21036            e2e_deferred: false,
21037            e2e_defer_reason: None,
21038            progressed: false,
21039            vote_split: false,
21040            reconsideration: Vec::new(),
21041            verdict: None,
21042        }];
21043
21044        let mut runner = Runner {
21045            state,
21046            roles: ResolvedRoles {
21047                implementers: Vec::new(),
21048                judges: Vec::new(),
21049                reviewers: Vec::new(),
21050                fixer: None,
21051                conductor: conductor(),
21052                implementer_roster: Vec::new(),
21053                judge_roster: Vec::new(),
21054                reviewer_roster: Vec::new(),
21055            },
21056            sem: Arc::new(Semaphore::new(1)),
21057            pause: Pause::new(),
21058            interrupt: Pause::new(),
21059        };
21060
21061        runner.gate().await.expect("gate");
21062        assert!(
21063            runner.state.gate_ran,
21064            "zero configured commands is still a real attempt, not an unrun gate"
21065        );
21066        assert!(runner.state.gate.is_empty());
21067        assert_eq!(runner.state.gate_status(), GateStatus::NotConfigured);
21068        assert_ne!(
21069            runner.state.status,
21070            RunStatus::Blocked,
21071            "a gate with nothing to check must not read as failed"
21072        );
21073
21074        runner.merge().await.expect("merge");
21075        assert_eq!(
21076            runner.state.status,
21077            RunStatus::Ready,
21078            "a clean review-only run with no gate commands must reach Ready, not stay stuck in Gating"
21079        );
21080    }
21081
21082    /// `Config::cache_dir` is derived from `verify.e2e` as well as
21083    /// `verify.gate` (so the e2e leg and the final gate never build against
21084    /// different directories). With zero `verify.gate` commands but a
21085    /// `CARGO_TARGET_DIR`-using `verify.e2e`, `gate` used to still queue for
21086    /// that lease before discovering it had nothing to run - so a repo with
21087    /// no gate commands could come back `resource_blocked` (and therefore
21088    /// still `gate_ran == false`) on nothing but an unrelated run holding the
21089    /// cache, exactly the contention this run's own zero commands could
21090    /// never have touched. `gate` must recognise there is nothing to check
21091    /// before it ever asks for the lease.
21092    #[tokio::test]
21093    async fn gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run() {
21094        crate::run::pin_test_home();
21095        let home = crate::run::home();
21096
21097        let tmp = tempfile::tempdir().expect("tempdir");
21098        let repo = tmp.path().join("repo");
21099        std::fs::create_dir_all(&repo).unwrap();
21100        init_repo(&repo);
21101        // Unique to this test, so holding its lease cannot collide with
21102        // another test sharing the same process-wide `home`.
21103        let cache_dir = tmp.path().join("target");
21104
21105        let mut config = Config::default();
21106        config.verify.e2e = vec![format!("CARGO_TARGET_DIR='{}' true", cache_dir.display())];
21107        // `verify.gate` stays empty (the default). Any accidental cache
21108        // acquisition must report contention immediately, regardless of how
21109        // long unrelated Git subprocesses take under parallel test load.
21110        config.graph.timeout_verify = Some(2);
21111        config.graph.timeout_resource_wait = 0;
21112
21113        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
21114        let _held = match crate::cache::try_acquire(&home, &cache_dir, &other)
21115            .expect("no io error acquiring directly")
21116        {
21117            crate::cache::AcquireOutcome::Acquired(g) => g,
21118            crate::cache::AcquireOutcome::Busy(b) => {
21119                panic!("expected the direct acquire to win the lease first: {b:?}")
21120            }
21121        };
21122
21123        let mut state = RunState::new(
21124            repo.clone(),
21125            "main".to_owned(),
21126            "deadbeef".to_owned(),
21127            "task".to_owned(),
21128            config,
21129        );
21130        state.candidates = vec![Candidate {
21131            index: 0,
21132            label: 'A',
21133            agent: "alpha".to_owned(),
21134            branch: "does-not-exist".to_owned(),
21135            worktree: repo.clone(),
21136            summary: String::new(),
21137            stat: String::new(),
21138            files: 0,
21139            commits: 0,
21140            empty: false,
21141            failed: None,
21142            verified_noop: None,
21143            duration_ms: 0,
21144            folded: false,
21145        }];
21146        state.tally = Some(Tally {
21147            first_choice: BTreeMap::from([('A', 1)]),
21148            borda: BTreeMap::new(),
21149            winner: 'A',
21150            rankings: 1,
21151            unanimous_initial: true,
21152            deliberated: false,
21153            changed_votes: 0,
21154            unanimous_final: true,
21155            tie_break: None,
21156            judges: 0,
21157            present: 0,
21158            quorum: 0,
21159            met_quorum: true,
21160            uncontested: Some("only candidate A produced a change".to_owned()),
21161        });
21162        state.reviews = vec![ReviewRound {
21163            round: 1,
21164            head: "deadbeef".to_owned(),
21165            verified_head: None,
21166            verified_at: None,
21167            reviews: Vec::new(),
21168            e2e: Vec::new(),
21169            fix: None,
21170            blocking: 0,
21171            answered: 0,
21172            expected: 0,
21173            clean: true,
21174            verify_retried: false,
21175            e2e_deferred: false,
21176            e2e_defer_reason: None,
21177            progressed: false,
21178            vote_split: false,
21179            reconsideration: Vec::new(),
21180            verdict: None,
21181        }];
21182
21183        state.reviews[0].verified_head = Some(git::rev_parse(&repo, "HEAD").await.unwrap());
21184        state.reviews[0].e2e = vec![CommandOutcome {
21185            command: state.config.verify.e2e[0].clone(),
21186            code: Some(0),
21187            output_tail: String::new(),
21188            duration_ms: 0,
21189            resource_blocked: false,
21190        }];
21191        let mut runner = Runner {
21192            state,
21193            roles: ResolvedRoles {
21194                implementers: Vec::new(),
21195                judges: Vec::new(),
21196                reviewers: Vec::new(),
21197                fixer: None,
21198                conductor: conductor(),
21199                implementer_roster: Vec::new(),
21200                judge_roster: Vec::new(),
21201                reviewer_roster: Vec::new(),
21202            },
21203            sem: Arc::new(Semaphore::new(1)),
21204            pause: Pause::new(),
21205            interrupt: Pause::new(),
21206        };
21207
21208        runner.gate().await.expect("gate");
21209        assert!(runner.state.resource_block.is_none());
21210        assert!(
21211            !runner
21212                .state
21213                .events
21214                .iter()
21215                .any(|event| { event.message.contains("waiting for the shared build cache") }),
21216            "a gate with nothing to run must never request the held cache lease"
21217        );
21218        assert!(
21219            runner.state.gate_ran,
21220            "zero commands is still a real, immediate attempt"
21221        );
21222        assert!(runner.state.gate.is_empty());
21223        assert_ne!(
21224            runner.state.status,
21225            RunStatus::Blocked,
21226            "must not read as resource-blocked on a lease it never asked for"
21227        );
21228    }
21229
21230    /// A separate process carries a live worker's environment throughout all
21231    /// verification entry points; the parallel harness never changes its env.
21232    #[cfg(unix)]
21233    #[tokio::test]
21234    async fn verification_is_standalone_inside_a_live_worker() {
21235        const CHILD: &str = "MAGI_VERIFY_WORKER_TEST";
21236        if std::env::var_os(CHILD).is_none() {
21237            let home = tempfile::tempdir().unwrap();
21238            let generation = crate::worker::pin_current(home.path()).unwrap();
21239            let output = std::process::Command::new(std::env::current_exe().unwrap())
21240                .args([
21241                    "--exact",
21242                    "graph::tests::verification_is_standalone_inside_a_live_worker",
21243                    "--nocapture",
21244                ])
21245                .env(CHILD, "1")
21246                .env("MAGI_HOME", home.path())
21247                .env("MAGI_WORKER_HOME", home.path())
21248                .env("MAGI_WORKER_ID", "abcdef")
21249                .env("MAGI_WORKER_GENERATION", &generation.id)
21250                .env("MAGI_WORKER_EXE", &generation.executable)
21251                .env("MAGI_RUN", "verification-parent")
21252                .env("MAGI_NODE", "gate")
21253                .env("MAGI_SEAT", "worker-fixture")
21254                .env("MAGI_PROCESS_OWNER", "fixture-owner")
21255                .env("MAGI_NO_AUTOUPDATE", "0")
21256                .env("VERIFY_EXPECT_PATH", std::env::var_os("PATH").unwrap())
21257                .env("VERIFY_AUTH_TOKEN", "fixture-auth")
21258                .env(
21259                    "VERIFY_EXPECT_TOOLCHAIN",
21260                    std::env::var_os("RUSTUP_TOOLCHAIN").unwrap_or_default(),
21261                )
21262                .env(
21263                    "VERIFY_EXPECT_CACHE",
21264                    std::env::var_os("CARGO_TARGET_DIR").unwrap_or_default(),
21265                )
21266                .output()
21267                .unwrap();
21268            assert!(
21269                output.status.success()
21270                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
21271                "{}\n{}",
21272                String::from_utf8_lossy(&output.stdout),
21273                String::from_utf8_lossy(&output.stderr)
21274            );
21275            return;
21276        }
21277        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
21278        let home = crate::run::home();
21279        let directory = home.join("workers/jobs/abcdef");
21280        std::fs::create_dir_all(&directory).unwrap();
21281        let job = crate::worker::Job {
21282            id: "abcdef".into(),
21283            sequence: 1,
21284            kind: "task".into(),
21285            key: "task:verification".into(),
21286            payload: serde_json::json!({}),
21287            generation: std::env::var("MAGI_WORKER_GENERATION").unwrap(),
21288            version: Some(env!("CARGO_PKG_VERSION").into()),
21289            status: crate::worker::Status::Running,
21290            result: None,
21291            pid: Some(std::process::id()),
21292            created_at: 0,
21293            finished_at: None,
21294        };
21295        std::fs::write(
21296            directory.join("job.json"),
21297            serde_json::to_vec(&job).unwrap(),
21298        )
21299        .unwrap();
21300        let _lease = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
21301        let assert_worker = || {
21302            assert_eq!(
21303                crate::worker::current_job(&home).unwrap().unwrap().id,
21304                job.id
21305            );
21306            assert_eq!(crate::worker::active(&home).unwrap().len(), 1);
21307            assert_eq!(
21308                crate::worker::helper_executable(&home).unwrap(),
21309                PathBuf::from(std::env::var_os("MAGI_WORKER_EXE").unwrap())
21310            );
21311            assert!(
21312                crate::updater::Checker::new(&crate::config::Update {
21313                    mode: crate::config::UpdateMode::Notify,
21314                    interval: None,
21315                    auto_restart: false,
21316                })
21317                .is_none(),
21318                "the driver remains pinned, even while tests are standalone"
21319            );
21320        };
21321        assert_worker();
21322        let repo = home.join("repo");
21323        std::fs::create_dir_all(&repo).unwrap();
21324        init_repo(&repo);
21325        // Keep storage, seat/control context, containment and tool lookup.
21326        // No inherited values (or credentials) are printed on success.
21327        let probe = r#"test -z "${MAGI_WORKER_ID+x}" &&
21328            test -z "${MAGI_WORKER_GENERATION+x}" &&
21329            test -z "${MAGI_WORKER_HOME+x}" &&
21330            test -z "${MAGI_WORKER_EXE+x}" &&
21331            test "$MAGI_HOME/repo" -ef . &&
21332            test "$MAGI_RUN" = verification-parent &&
21333            test "$MAGI_NODE" = gate &&
21334            test "$MAGI_SEAT" = worker-fixture &&
21335            test -n "$MAGI_PROCESS_OWNER" &&
21336            test "$PATH" = "$VERIFY_EXPECT_PATH" &&
21337            test "$VERIFY_AUTH_TOKEN" = fixture-auth &&
21338            test "$RUSTUP_TOOLCHAIN" = "$VERIFY_EXPECT_TOOLCHAIN" &&
21339            test "$CARGO_TARGET_DIR" = "$VERIFY_EXPECT_CACHE""#;
21340        // Negative control: an ordinary child inherits the contamination.
21341        assert!(
21342            !std::process::Command::new("sh")
21343                .args(["-c", probe])
21344                .current_dir(&repo)
21345                .status()
21346                .unwrap()
21347                .success()
21348        );
21349        let unrelated_home = tempfile::tempdir().unwrap();
21350        assert!(
21351            crate::worker::current_job(unrelated_home.path()).is_err(),
21352            "an inherited worker id cannot be resolved in a unit fixture's home"
21353        );
21354        let mut runner = runner_at(RunStatus::Gating);
21355        runner.state.repo = repo.clone();
21356        runner.state.config.disk.min_free_bytes = 0;
21357        runner.state.config.coordination = crate::config::test_coordination();
21358        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
21359        runner.state.config.verify.e2e = vec![format!("{probe} && printf 'e2e\\n' >> phases")];
21360        runner.state.config.verify.pre_gate = vec![format!("{probe} && printf 'pre\\n' >> phases")];
21361        runner.state.config.verify.gate = vec![format!("{probe} && printf 'gate\\n' >> phases")];
21362        let winner = Candidate {
21363            index: 0,
21364            label: 'A',
21365            agent: "fixture".into(),
21366            branch: "main".into(),
21367            worktree: repo.clone(),
21368            summary: String::new(),
21369            stat: String::new(),
21370            files: 0,
21371            commits: 0,
21372            empty: false,
21373            failed: None,
21374            verified_noop: None,
21375            duration_ms: 0,
21376            folded: false,
21377        };
21378        let (e2e, retried, pids) = run_e2e_with_retry(
21379            &mut runner.state,
21380            &["sh".into(), "-c".into()],
21381            &[format!("{probe} && printf initial")],
21382            &repo,
21383            Duration::from_secs(10),
21384            "initial",
21385            None,
21386        )
21387        .await;
21388        assert!(!retried && pids.is_empty());
21389        assert_eq!(e2e[0].code, Some(0), "{e2e:?}");
21390        assert_eq!(e2e[0].output_tail, "initial");
21391        let gate = runner.run_gate(&winner).await.unwrap();
21392        assert!(gate.iter().all(CommandOutcome::ok), "{gate:?}");
21393        // An interrupted repair must recheck e2e from saved state. Landing
21394        // reuses that state and must run both pre-gate and gate again.
21395        runner.state.gate_repair_e2e = Some(crate::run::GateRepairE2e {
21396            head: git::rev_parse(&repo, "HEAD").await.unwrap(),
21397            passed: false,
21398            outcomes: Vec::new(),
21399        });
21400        runner.state.save().unwrap();
21401        let mut resumed = RunState::load(&runner.state.id).unwrap();
21402        let wait = crate::repo_lock::WaitPolicy::default();
21403        assert!(matches!(
21404            check_gate_repair_e2e(&mut resumed, &winner, &wait)
21405                .await
21406                .unwrap(),
21407            GateFix::Retry
21408        ));
21409        let saved = RunState::load(&resumed.id).unwrap();
21410        let repair = saved.gate_repair_e2e.unwrap();
21411        assert!(repair.passed);
21412        assert_eq!(repair.outcomes.len(), 1);
21413        assert!(repair.outcomes[0].ok());
21414        let landing = run_landing_gate(&mut resumed, &winner, &wait)
21415            .await
21416            .unwrap();
21417        assert_eq!(landing.len(), 1);
21418        assert!(landing[0].ok(), "{landing:?}");
21419        assert_eq!(
21420            std::fs::read_to_string(repo.join("phases")).unwrap(),
21421            "pre\ngate\ne2e\npre\ngate\n"
21422        );
21423        assert_worker();
21424    }
21425
21426    #[cfg(unix)]
21427    #[tokio::test]
21428    async fn verification_keeps_the_panic_and_the_full_output() {
21429        crate::run::pin_test_home();
21430        let tmp = tempfile::tempdir().unwrap();
21431        let mut config = Config::default();
21432        config.disk.min_free_bytes = 0;
21433        let mut state = RunState::new(
21434            tmp.path().to_owned(),
21435            "main".into(),
21436            "base".into(),
21437            "verification evidence".into(),
21438            config,
21439        );
21440        let script = "echo \"thread 'x' panicked at t.rs:1:1:\"; echo 'boom assertion'; \
21441                      i=0; while [ $i -lt 20000 ]; do echo \"  $i: 0xabc - <a::b>\"; \
21442                      echo '             at /x/y.rs:1:1'; i=$((i+1)); done; exit 101";
21443        let mut names = Vec::new();
21444        for _ in 0..2 {
21445            let (outcomes, _) = run_commands(
21446                &mut state,
21447                "gate",
21448                "gate",
21449                0,
21450                &["sh".into(), "-c".into()],
21451                &[script.into()],
21452                tmp.path(),
21453                Duration::from_secs(60),
21454            )
21455            .await;
21456            let tail = &outcomes[0].output_tail;
21457            assert!(tail.contains("panicked at t.rs:1:1"), "{tail}");
21458            assert!(tail.contains("boom assertion"));
21459            assert!(tail.len() <= crate::run::VERIFY_SUMMARY + 100);
21460            let line = tail.lines().next().unwrap();
21461            names.push(line.to_owned());
21462        }
21463        assert_ne!(names[0], names[1], "the second run must not overwrite");
21464        let full = crate::run::read_artifact(&state, "gate-1.out").unwrap();
21465        assert!(full.len() > 500_000 && full.contains("boom assertion"));
21466        assert!(crate::run::read_artifact(&state, "gate-2.out").is_some());
21467
21468        // Storage failures are evidence too; preserve the command's verdict.
21469        std::fs::remove_dir_all(state.dir().join("artifacts")).unwrap();
21470        std::fs::write(state.dir().join("artifacts"), "blocked").unwrap();
21471        let (outcomes, _) = run_commands(
21472            &mut state,
21473            "gate",
21474            "gate",
21475            0,
21476            &["sh".into(), "-c".into()],
21477            &["echo failure-output; exit 7".into()],
21478            tmp.path(),
21479            Duration::from_secs(10),
21480        )
21481        .await;
21482        assert_eq!(outcomes[0].code, Some(7));
21483        assert!(state.events.iter().any(|e| {
21484            e.node == "gate" && e.message.contains("could not save the full gate output:")
21485        }));
21486    }
21487
21488    #[cfg(unix)]
21489    #[tokio::test]
21490    async fn verification_commands_distinguish_timeouts_signals_and_exit_codes() {
21491        crate::run::pin_test_home();
21492        let tmp = tempfile::tempdir().unwrap();
21493        let mut config = Config::default();
21494        config.disk.min_free_bytes = 0;
21495        let mut state = RunState::new(
21496            tmp.path().to_owned(),
21497            "main".into(),
21498            "base".into(),
21499            "verification evidence".into(),
21500            config,
21501        );
21502        let (outcomes, pids) = run_commands(
21503            &mut state,
21504            "gate",
21505            "gate",
21506            1,
21507            &["sh".into(), "-c".into()],
21508            &[
21509                "printf before-timeout; exec sleep 30".into(),
21510                "kill -TERM $$".into(),
21511                "exit 7".into(),
21512                "printf success".into(),
21513            ],
21514            tmp.path(),
21515            Duration::from_secs(1),
21516        )
21517        .await;
21518        wait_for_timed_out_children_to_die(&pids).await;
21519        assert_eq!(
21520            pids.len(),
21521            1,
21522            "unleased timeout retains its death-check PID"
21523        );
21524        assert_eq!(outcomes.len(), 4);
21525        assert_eq!(outcomes[0].code, None);
21526        assert!(outcomes[0].output_tail.contains("before-timeout"));
21527        assert!(outcomes[0].output_tail.contains("timed out after 1s"));
21528        assert_eq!(outcomes[1].code, None);
21529        assert!(outcomes[1].output_tail.contains("command terminated:"));
21530        assert!(!outcomes[1].output_tail.contains("timed out"));
21531        assert_eq!(outcomes[2].code, Some(7));
21532        assert!(!outcomes[2].output_tail.contains("timed out"));
21533        assert_eq!(outcomes[3].code, Some(0));
21534        assert_eq!(outcomes[3].output_tail, "success");
21535        assert!(outcomes.iter().all(|outcome| !outcome.resource_blocked));
21536    }
21537
21538    /// The addendum's second gap: a `verify.gate` command running for real
21539    /// wall-clock time had nothing at all to show for it in `active` before
21540    /// `run_commands` learned to record it — a run could sit in `Gating` for
21541    /// minutes with `magi show` and `GET /api/runs/{id}` both silent about
21542    /// what was actually happening. Proven with a genuinely still-running
21543    /// command, not just a before/after check on the final state: a poller
21544    /// task reads the same `run.json` `gate()` is writing, the same way the
21545    /// phone or `magi show` would, while the shell command is still blocked
21546    /// on its own release marker.
21547    #[tokio::test]
21548    async fn gate_records_a_running_task_entry_while_its_command_is_still_in_flight() {
21549        crate::run::pin_test_home();
21550
21551        let tmp = tempfile::tempdir().expect("tempdir");
21552        let repo = tmp.path().join("repo");
21553        std::fs::create_dir_all(&repo).unwrap();
21554        init_repo(&repo);
21555
21556        let mut config = Config::default();
21557        config.disk.min_free_bytes = 0;
21558        config.verify.gate = vec![
21559            "printf started > started.marker; i=0; while [ ! -f release.marker ] && \
21560             [ \"$i\" -lt 100 ]; do i=$((i+1)); sleep 0.05; done; test -f release.marker"
21561                .to_owned(),
21562        ];
21563
21564        let mut state = RunState::new(
21565            repo.clone(),
21566            "main".to_owned(),
21567            "deadbeef".to_owned(),
21568            "task".to_owned(),
21569            config,
21570        );
21571        let run_id = state.id.clone();
21572        state.candidates = vec![Candidate {
21573            index: 0,
21574            label: 'A',
21575            agent: "alpha".to_owned(),
21576            branch: "does-not-exist".to_owned(),
21577            worktree: repo.clone(),
21578            summary: String::new(),
21579            stat: String::new(),
21580            files: 0,
21581            commits: 0,
21582            empty: false,
21583            failed: None,
21584            verified_noop: None,
21585            duration_ms: 0,
21586            folded: false,
21587        }];
21588        state.tally = Some(Tally {
21589            first_choice: BTreeMap::from([('A', 1)]),
21590            borda: BTreeMap::new(),
21591            winner: 'A',
21592            rankings: 1,
21593            unanimous_initial: true,
21594            deliberated: false,
21595            changed_votes: 0,
21596            unanimous_final: true,
21597            tie_break: None,
21598            judges: 0,
21599            present: 0,
21600            quorum: 0,
21601            met_quorum: true,
21602            uncontested: Some("only candidate A produced a change".to_owned()),
21603        });
21604        state.reviews = vec![ReviewRound {
21605            round: 1,
21606            head: "deadbeef".to_owned(),
21607            verified_head: None,
21608            verified_at: None,
21609            reviews: Vec::new(),
21610            e2e: Vec::new(),
21611            fix: None,
21612            blocking: 0,
21613            answered: 0,
21614            expected: 0,
21615            clean: true,
21616            verify_retried: false,
21617            e2e_deferred: false,
21618            e2e_defer_reason: None,
21619            progressed: false,
21620            vote_split: false,
21621            reconsideration: Vec::new(),
21622            verdict: None,
21623        }];
21624
21625        let mut runner = Runner {
21626            state,
21627            roles: ResolvedRoles {
21628                implementers: Vec::new(),
21629                judges: Vec::new(),
21630                reviewers: Vec::new(),
21631                fixer: None,
21632                conductor: conductor(),
21633                implementer_roster: Vec::new(),
21634                judge_roster: Vec::new(),
21635                reviewer_roster: Vec::new(),
21636            },
21637            sem: Arc::new(Semaphore::new(1)),
21638            pause: Pause::new(),
21639            interrupt: Pause::new(),
21640        };
21641
21642        let started_marker = repo.join("started.marker");
21643        let release_marker = repo.join("release.marker");
21644        let observe = async {
21645            loop {
21646                if started_marker.exists()
21647                    && let Ok(s) = crate::run::RunState::load(&run_id)
21648                    && let Some(a) = s.active.get("gate")
21649                {
21650                    std::fs::write(&release_marker, b"go").expect("release marker");
21651                    break a.clone();
21652                }
21653                tokio::time::sleep(Duration::from_millis(50)).await;
21654            }
21655        };
21656        let captured = {
21657            let gate = runner.gate();
21658            tokio::pin!(gate);
21659            let captured = tokio::select! {
21660                observed = observe => observed,
21661                result = &mut gate => panic!(
21662                    "gate exited before its in-flight entry was observed: {result:?}"
21663                ),
21664            };
21665            gate.await.expect("gate");
21666            captured
21667        };
21668
21669        assert_eq!(captured.task.as_deref(), Some("gate"));
21670        assert_eq!(captured.node, "gate");
21671        assert_eq!(captured.index, Some(1));
21672        assert_eq!(captured.total, Some(1));
21673        assert!(
21674            captured
21675                .command
21676                .as_deref()
21677                .is_some_and(|c| c.contains("started.marker")),
21678            "{captured:?}"
21679        );
21680
21681        assert!(
21682            runner.state.active.is_empty(),
21683            "the entry must be cleared once the command actually finished: {:?}",
21684            runner.state.active
21685        );
21686        assert!(runner.state.gate_ran);
21687        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
21688    }
21689
21690    /// The hand-off over a blocking finding a reviewer rejected on leaves a
21691    /// record for `land`; one with only a Minor, or no reject, leaves none.
21692    #[tokio::test]
21693    async fn stop_reviewing_records_a_contested_hand_off_only_for_major_plus_reject() {
21694        use crate::verdict::{Finding, ReviewVote, Severity};
21695        crate::run::pin_test_home();
21696        let tmp = tempfile::tempdir().expect("tempdir");
21697        let repo = tmp.path().join("repo");
21698        std::fs::create_dir_all(&repo).unwrap();
21699        init_repo(&repo);
21700
21701        for (severity, vote, expect) in [
21702            (Severity::Major, ReviewVote::Reject, true),
21703            (Severity::Minor, ReviewVote::Reject, false),
21704            (Severity::Major, ReviewVote::Approve, false),
21705        ] {
21706            let mut round = review_round(false, 1, 1, 1, false, true);
21707            round.reviews = vec![ReviewRecord {
21708                reviewer: 1,
21709                agent: "alpha".to_owned(),
21710                summary: String::new(),
21711                findings: vec![Finding {
21712                    id: "R1-1-1".to_owned(),
21713                    severity,
21714                    file: None,
21715                    line: None,
21716                    title: "t".to_owned(),
21717                    detail: String::new(),
21718                }],
21719                vote: Some(vote),
21720                failed: None,
21721                duration_ms: 0,
21722                attempts: 0,
21723            }];
21724            let mut state = RunState::new(
21725                repo.clone(),
21726                "main".to_owned(),
21727                "deadbeef".to_owned(),
21728                "task".to_owned(),
21729                Config::default(),
21730            );
21731            state.reviews = vec![round];
21732            let mut runner = Runner {
21733                state,
21734                roles: ResolvedRoles {
21735                    implementers: Vec::new(),
21736                    judges: Vec::new(),
21737                    reviewers: Vec::new(),
21738                    fixer: None,
21739                    conductor: conductor(),
21740                    implementer_roster: Vec::new(),
21741                    judge_roster: Vec::new(),
21742                    reviewer_roster: Vec::new(),
21743                },
21744                sem: Arc::new(Semaphore::new(1)),
21745                pause: Pause::new(),
21746                interrupt: Pause::new(),
21747            };
21748            let shell = runner.state.config.shell();
21749            runner
21750                .stop_reviewing("round budget spent", &shell, &repo)
21751                .await
21752                .expect("stop_reviewing");
21753            assert_eq!(runner.state.status, RunStatus::Gating);
21754            assert_eq!(
21755                runner.state.contested_handoff.is_some(),
21756                expect,
21757                "{severity:?} + {vote:?}"
21758            );
21759        }
21760    }
21761
21762    /// The shape the incident this whole fix responds to actually had: the
21763    /// round budget spent, the last round's own e2e blocked on the shared
21764    /// build cache (held here by a live pid — this test process — exactly
21765    /// `cache`'s own unit tests' pattern for "another owner, still alive"
21766    /// without forking a process). `stop_reviewing` must retry it — not
21767    /// silently leave the round looking untouched (the catch-up-only half of
21768    /// the bug), and not read the contention as a red `e2e` and block the
21769    /// run on it (the other half). Called directly, the same way
21770    /// `gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run`
21771    /// above exercises `gate`, so this never needs a real cargo build to
21772    /// reach: the lease is never released, so `with_cache_lease` never gets
21773    /// past acquiring it into anything that would need a real workspace.
21774    #[tokio::test]
21775    async fn stop_reviewing_retries_a_resource_blocked_e2e_instead_of_reading_it_as_red() {
21776        crate::run::pin_test_home();
21777        let home = crate::run::home();
21778
21779        let tmp = tempfile::tempdir().expect("tempdir");
21780        let repo = tmp.path().join("repo");
21781        std::fs::create_dir_all(&repo).unwrap();
21782        init_repo(&repo);
21783        let head = crate::git::rev_parse(&repo, "HEAD")
21784            .await
21785            .expect("rev-parse");
21786        // Unique to this test, so holding its lease cannot collide with
21787        // another test sharing the same process-wide `home`.
21788        let cache_dir = tmp.path().join("target");
21789
21790        let mut config = Config::default();
21791        config.verify.e2e = vec![format!(
21792            "CARGO_TARGET_DIR='{}' test -f README.md",
21793            cache_dir.display()
21794        )];
21795        config.graph.review_rounds = 1;
21796        // Bounded so a regression that does start waiting fails the test in
21797        // seconds, not hangs it.
21798        config.graph.timeout_verify = Some(2);
21799        config.graph.timeout_resource_wait = 2;
21800
21801        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
21802        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
21803            .expect("no io error acquiring directly")
21804        {
21805            crate::cache::AcquireOutcome::Acquired(g) => g,
21806            crate::cache::AcquireOutcome::Busy(b) => {
21807                panic!("expected the direct acquire to win the lease first: {b:?}")
21808            }
21809        };
21810
21811        let mut state = RunState::new(
21812            repo.clone(),
21813            "main".to_owned(),
21814            head.clone(),
21815            "task".to_owned(),
21816            config,
21817        );
21818        state.candidates = vec![Candidate {
21819            index: 0,
21820            label: 'A',
21821            agent: "alpha".to_owned(),
21822            branch: "does-not-exist".to_owned(),
21823            worktree: repo.clone(),
21824            summary: String::new(),
21825            stat: String::new(),
21826            files: 0,
21827            commits: 0,
21828            empty: false,
21829            failed: None,
21830            verified_noop: None,
21831            duration_ms: 0,
21832            folded: false,
21833        }];
21834        state.tally = Some(Tally {
21835            first_choice: BTreeMap::from([('A', 1)]),
21836            borda: BTreeMap::new(),
21837            winner: 'A',
21838            rankings: 1,
21839            unanimous_initial: true,
21840            deliberated: false,
21841            changed_votes: 0,
21842            unanimous_final: true,
21843            tie_break: None,
21844            judges: 0,
21845            present: 0,
21846            quorum: 0,
21847            met_quorum: true,
21848            uncontested: Some("only candidate A produced a change".to_owned()),
21849        });
21850        // The round budget's last round, deferred: `needs_catchup_run`'s
21851        // other trigger. `stop_reviewing`'s retry machinery must treat this
21852        // exactly like a resource-blocked attempt once it actually runs.
21853        state.reviews = vec![ReviewRound {
21854            round: 1,
21855            head: head.clone(),
21856            verified_head: None,
21857            verified_at: None,
21858            reviews: Vec::new(),
21859            e2e: Vec::new(),
21860            fix: None,
21861            blocking: 1,
21862            answered: 1,
21863            expected: 1,
21864            clean: false,
21865            verify_retried: false,
21866            e2e_deferred: true,
21867            e2e_defer_reason: Some("1 blocking finding(s) already required a fix".to_owned()),
21868            progressed: false,
21869            vote_split: false,
21870            reconsideration: Vec::new(),
21871            verdict: None,
21872        }];
21873
21874        let mut runner = Runner {
21875            state,
21876            roles: ResolvedRoles {
21877                implementers: Vec::new(),
21878                judges: Vec::new(),
21879                reviewers: Vec::new(),
21880                fixer: None,
21881                conductor: conductor(),
21882                implementer_roster: Vec::new(),
21883                judge_roster: Vec::new(),
21884                reviewer_roster: Vec::new(),
21885            },
21886            sem: Arc::new(Semaphore::new(1)),
21887            pause: Pause::new(),
21888            interrupt: Pause::new(),
21889        };
21890
21891        let shell = runner.state.config.shell();
21892        runner
21893            .stop_reviewing("round budget spent", &shell, &repo)
21894            .await
21895            .expect("stop_reviewing");
21896
21897        let last = runner.state.reviews.last().expect("round record");
21898        assert_eq!(
21899            last.e2e_status(),
21900            E2eStatus::ResourceBlocked,
21901            "the shared cache is still held; the attempt must read as blocked, not deferred or \
21902             failed: {last:?}"
21903        );
21904        assert_eq!(
21905            last.verified_head.as_deref(),
21906            Some(head.as_str()),
21907            "which commit this attempt targeted is known even though nothing finished checking \
21908             it"
21909        );
21910        let first_attempt_at = last
21911            .verified_at
21912            .expect("when this attempt ran is known too");
21913        assert_ne!(
21914            runner.state.status,
21915            RunStatus::Blocked,
21916            "contention is evidence about the machine, not the patch — it must not settle the \
21917             run as blocked: {:?}",
21918            runner.state.status
21919        );
21920        assert!(
21921            !runner
21922                .state
21923                .events
21924                .iter()
21925                .any(|e| e.node == "review" && e.message.contains("e2e failed")),
21926            "a resource-blocked attempt must never be logged as a failed e2e: {:?}",
21927            runner.state.events
21928        );
21929
21930        // The cache is still held: a later reentry must retry the same
21931        // round's verification again — not leave it looking exactly as
21932        // untouched as the first blocked attempt, which is indistinguishable
21933        // from never having tried again at all.
21934        runner
21935            .stop_reviewing("round budget spent", &shell, &repo)
21936            .await
21937            .expect("stop_reviewing retry");
21938        assert_eq!(
21939            runner.state.reviews.len(),
21940            1,
21941            "no new round was started: {:?}",
21942            runner.state.reviews
21943        );
21944        let last = runner.state.reviews.last().expect("round record");
21945        assert_eq!(last.e2e_status(), E2eStatus::ResourceBlocked, "{last:?}");
21946        assert!(
21947            last.verified_at.expect("still known") > first_attempt_at,
21948            "a second reentry must be a fresh attempt, not a stale copy of the first"
21949        );
21950        assert_ne!(runner.state.status, RunStatus::Blocked);
21951
21952        held.release();
21953    }
21954
21955    #[cfg(unix)]
21956    #[tokio::test]
21957    async fn catchup_compile_failure_after_clean_base_sync_uses_remaining_review_rounds() {
21958        ask_test_home();
21959        for (max_rounds, reentry) in [(2, false), (2, true), (1, false)] {
21960            let tmp = tempfile::tempdir().unwrap();
21961            let repo = tmp.path().join("repo");
21962            std::fs::create_dir(&repo).unwrap();
21963            init_repo(&repo);
21964            let run_git = |args: &[&str]| {
21965                let out = std::process::Command::new("git")
21966                    .args(args)
21967                    .current_dir(&repo)
21968                    .output()
21969                    .unwrap();
21970                assert!(
21971                    out.status.success(),
21972                    "{args:?}: {}",
21973                    String::from_utf8_lossy(&out.stderr)
21974                );
21975            };
21976            let origin = tmp.path().join("origin.git");
21977            run_git(&["init", "--bare", origin.to_str().unwrap()]);
21978            run_git(&["remote", "add", "origin", origin.to_str().unwrap()]);
21979            std::fs::write(repo.join("spec.rs"), "struct AgentSpec {}\n").unwrap();
21980            run_git(&["add", "spec.rs"]);
21981            run_git(&["commit", "-m", "initial spec"]);
21982            run_git(&["push", "origin", "main"]);
21983            let base = git::rev_parse(&repo, "HEAD").await.unwrap();
21984            run_git(&["checkout", "-b", "fix/review"]);
21985            std::fs::write(
21986                repo.join("check.rs"),
21987                "include!(\"spec.rs\"); fn main() { let _ = AgentSpec {}; }\n",
21988            )
21989            .unwrap();
21990            run_git(&["add", "check.rs"]);
21991            run_git(&["commit", "-m", "use spec"]);
21992            let reviewed = git::rev_parse(&repo, "HEAD").await.unwrap();
21993            run_git(&["checkout", "main"]);
21994            std::fs::write(
21995                repo.join("spec.rs"),
21996                "struct AgentSpec { max_turn_secs: u64 }\n",
21997            )
21998            .unwrap();
21999            run_git(&["add", "spec.rs"]);
22000            run_git(&["commit", "-m", "extend spec"]);
22001            run_git(&["push", "origin", "main"]);
22002            run_git(&["checkout", "fix/review"]);
22003
22004            let mut runner = runner_at(RunStatus::Reviewing);
22005            runner.state.repo = repo.clone();
22006            runner.state.base_commit = base;
22007            runner.state.pr_head = Some("fix/review".into());
22008            runner.state.config.graph.review_rounds = max_rounds;
22009            runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
22010            runner.state.config.graph.sessions = false;
22011            runner.state.config.disk.min_free_bytes = 0;
22012            runner.state.config.verify.e2e =
22013                vec!["rustc --emit=metadata -o ../check.rmeta check.rs || { echo 'error: could not compile fixture' >&2; exit 101; }".into()];
22014            runner.state.candidates = vec![Candidate {
22015                index: 0,
22016                label: 'A',
22017                agent: "fixture".into(),
22018                branch: "fix/review".into(),
22019                worktree: repo.clone(),
22020                summary: String::new(),
22021                stat: String::new(),
22022                files: 1,
22023                commits: 1,
22024                empty: false,
22025                failed: None,
22026                verified_noop: None,
22027                duration_ms: 0,
22028                folded: false,
22029            }];
22030            runner.state.tally = Some(Tally {
22031                first_choice: BTreeMap::new(),
22032                borda: BTreeMap::new(),
22033                winner: 'A',
22034                rankings: 0,
22035                unanimous_initial: true,
22036                deliberated: false,
22037                changed_votes: 0,
22038                unanimous_final: true,
22039                tie_break: None,
22040                judges: 0,
22041                present: 0,
22042                quorum: 0,
22043                met_quorum: true,
22044                uncontested: Some("review-only".into()),
22045            });
22046            let mut last = review_round(false, 0, 1, 1, false, false);
22047            last.head = reviewed.clone();
22048            last.e2e_deferred = true;
22049            last.e2e[0].resource_blocked = true;
22050            last.e2e[0].output_tail = "waiting for the shared build cache".into();
22051            if max_rounds == 1 {
22052                last.e2e.clear();
22053            }
22054            runner.state.reviews = vec![last];
22055            let calls = tmp.path().join("fix-calls");
22056            let mut fixer = spec("repair");
22057            fixer
22058                .env
22059                .insert("FIX_CALLS".into(), calls.display().to_string());
22060            fixer.command = vec!["sh".into(), "-c".into(), r#"
22061                echo fix >> "$FIX_CALLS"
22062                grep -q E0063 "$MAGI_PROMPT_FILE" || exit 1
22063                grep -q max_turn_secs "$MAGI_PROMPT_FILE" || exit 1
22064                printf 'include!("spec.rs"); fn main() { let _ = AgentSpec { max_turn_secs: 0 }; }\n' > check.rs
22065                printf '{"addressed":[],"rejected":[],"notes":"initialize the new field"}\n'
22066            "#.into()];
22067            let mut reviewer = spec("reviewer");
22068            reviewer.command = vec![
22069                "sh".into(),
22070                "-c".into(),
22071                "printf '%s\\n' '{\"summary\":\"clean\",\"vote\":\"approve\",\"findings\":[]}'"
22072                    .into(),
22073            ];
22074            runner.roles.fixer = Some(vec![fixer]);
22075            runner.roles.reviewers = vec![reviewer];
22076
22077            runner.sync_to_base().await.unwrap();
22078            let rebased = git::rev_parse(&repo, "HEAD").await.unwrap();
22079            assert_ne!(rebased, reviewed);
22080            assert!(runner.state.base_sync.as_ref().unwrap().conflict.is_none());
22081            if reentry {
22082                // Simulate a crash after catch-up evidence was saved but before
22083                // dispatching the fixer. No dedicated pending-repair field exists.
22084                let shell = runner.state.config.shell();
22085                runner
22086                    .stop_unresolved_review("deferred verification", &shell, &repo)
22087                    .await
22088                    .unwrap();
22089                assert!(runner.catchup_repairable());
22090                assert!(!calls.exists());
22091                runner.state = RunState::load(&runner.state.id).unwrap();
22092                assert!(runner.catchup_repairable());
22093            }
22094            runner.review_loop().await.unwrap();
22095            let first = &runner.state.reviews[0];
22096            assert_eq!(first.head, reviewed);
22097            assert_eq!(first.verified_head.as_deref(), Some(rebased.as_str()));
22098            assert!(
22099                first.verify_retried,
22100                "a reproduced build failure gets exactly one retry: {:?}",
22101                first.e2e
22102            );
22103            assert!(first.e2e[0].output_tail.contains("E0063"));
22104            assert!(!runner.catchup_repairable());
22105            if max_rounds == 2 {
22106                assert_eq!(
22107                    runner.state.status,
22108                    RunStatus::Gating,
22109                    "{}",
22110                    crate::report::run(&runner.state)
22111                );
22112                assert_eq!(runner.state.reviews.len(), 2);
22113                assert!(first.fix.as_ref().unwrap().committed);
22114                assert!(runner.state.reviews[1].clean);
22115                assert_eq!(
22116                    runner
22117                        .state
22118                        .reviews
22119                        .iter()
22120                        .filter(|r| r.fix.is_some())
22121                        .count(),
22122                    1
22123                );
22124                assert_eq!(std::fs::read_to_string(&calls).unwrap().lines().count(), 1);
22125                assert_eq!(runner.state.reviews[1].e2e_status(), E2eStatus::Passed);
22126            } else {
22127                assert_eq!(runner.state.status, RunStatus::Blocked);
22128                assert!(first.fix.is_none());
22129                assert!(!calls.exists());
22130                let recovery = crate::recovery::assess(
22131                    "prior",
22132                    Some(&runner.state),
22133                    &runner.landing_base(),
22134                    crate::recovery::Relation::Diverged,
22135                );
22136                assert_eq!(recovery.mode, crate::recovery::Mode::FullReview);
22137                let reasons = recovery.reasons.join("\n");
22138                assert!(
22139                    reasons.contains(&reviewed) && reasons.contains(&rebased),
22140                    "{reasons}"
22141                );
22142                assert!(
22143                    reasons.contains("base sync to")
22144                        && reasons.contains("additional review is required"),
22145                    "{reasons}"
22146                );
22147            }
22148        }
22149    }
22150
22151    /// A resumed run — a fresh `Runner`, `self.state.reviews` already
22152    /// holding the round `stop_reviewing` left `ResourceBlocked` from a
22153    /// prior process — must not sit at `Reviewing` forever: `review_loop`'s
22154    /// own top-of-function fast path (`review_conclusion`) correctly reads
22155    /// this shape as `None` rather than guessing `Blocked`, and the loop's
22156    /// own `for` range is empty once the round budget is spent, so
22157    /// `review_loop` must retry the check itself rather than silently doing
22158    /// nothing. Reaches the exact same retry `stop_reviewing_retries_a_*`
22159    /// above exercises directly, but through `review_loop`'s own entry point
22160    /// this time, proving the wiring between the two rather than just the
22161    /// retry logic in isolation.
22162    #[tokio::test]
22163    async fn a_resumed_review_loop_retries_a_last_round_left_resource_blocked() {
22164        crate::run::pin_test_home();
22165        let home = crate::run::home();
22166
22167        let tmp = tempfile::tempdir().expect("tempdir");
22168        let repo = tmp.path().join("repo");
22169        std::fs::create_dir_all(&repo).unwrap();
22170        init_repo(&repo);
22171        let head = crate::git::rev_parse(&repo, "HEAD")
22172            .await
22173            .expect("rev-parse");
22174        let cache_dir = tmp.path().join("target");
22175
22176        let mut config = Config::default();
22177        config.verify.e2e = vec![format!(
22178            "CARGO_TARGET_DIR='{}' test -f README.md",
22179            cache_dir.display()
22180        )];
22181        config.graph.review_rounds = 1;
22182        config.graph.timeout_verify = Some(2);
22183        config.graph.timeout_resource_wait = 2;
22184
22185        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
22186        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
22187            .expect("no io error acquiring directly")
22188        {
22189            crate::cache::AcquireOutcome::Acquired(g) => g,
22190            crate::cache::AcquireOutcome::Busy(b) => {
22191                panic!("expected the direct acquire to win the lease first: {b:?}")
22192            }
22193        };
22194
22195        let mut state = RunState::new(
22196            repo.clone(),
22197            "main".to_owned(),
22198            head.clone(),
22199            "task".to_owned(),
22200            config,
22201        );
22202        state.candidates = vec![Candidate {
22203            index: 0,
22204            label: 'A',
22205            agent: "alpha".to_owned(),
22206            branch: "does-not-exist".to_owned(),
22207            worktree: repo.clone(),
22208            summary: String::new(),
22209            stat: String::new(),
22210            files: 0,
22211            commits: 0,
22212            empty: false,
22213            failed: None,
22214            verified_noop: None,
22215            duration_ms: 0,
22216            folded: false,
22217        }];
22218        state.tally = Some(Tally {
22219            first_choice: BTreeMap::from([('A', 1)]),
22220            borda: BTreeMap::new(),
22221            winner: 'A',
22222            rankings: 1,
22223            unanimous_initial: true,
22224            deliberated: false,
22225            changed_votes: 0,
22226            unanimous_final: true,
22227            tie_break: None,
22228            judges: 0,
22229            present: 0,
22230            quorum: 0,
22231            met_quorum: true,
22232            uncontested: Some("only candidate A produced a change".to_owned()),
22233        });
22234        // The exact shape a prior process's `stop_reviewing` would have left
22235        // on disk: the round budget's last round, a real attempt already
22236        // made and already resource-blocked.
22237        state.reviews = vec![ReviewRound {
22238            round: 1,
22239            head: head.clone(),
22240            verified_head: Some(head.clone()),
22241            verified_at: Some(jiff::Timestamp::now()),
22242            reviews: Vec::new(),
22243            e2e: vec![CommandOutcome {
22244                command: format!(
22245                    "CARGO_TARGET_DIR='{}' test -f README.md",
22246                    cache_dir.display()
22247                ),
22248                code: None,
22249                output_tail: "waiting for the shared build cache".to_owned(),
22250                duration_ms: 0,
22251                resource_blocked: true,
22252            }],
22253            fix: None,
22254            blocking: 1,
22255            answered: 1,
22256            expected: 1,
22257            clean: false,
22258            verify_retried: false,
22259            e2e_deferred: false,
22260            e2e_defer_reason: None,
22261            progressed: false,
22262            vote_split: false,
22263            reconsideration: Vec::new(),
22264            verdict: None,
22265        }];
22266
22267        let first_attempt_at = state.reviews[0].verified_at.expect("set above");
22268        let mut runner = Runner {
22269            state,
22270            roles: ResolvedRoles {
22271                implementers: Vec::new(),
22272                judges: Vec::new(),
22273                reviewers: Vec::new(),
22274                fixer: None,
22275                conductor: conductor(),
22276                implementer_roster: Vec::new(),
22277                judge_roster: Vec::new(),
22278                reviewer_roster: Vec::new(),
22279            },
22280            sem: Arc::new(Semaphore::new(1)),
22281            pause: Pause::new(),
22282            interrupt: Pause::new(),
22283        };
22284
22285        // The lease is still held throughout, so this reentry's own retry is
22286        // also contended — proving `review_loop` actually tried again (not
22287        // that it happened to succeed) is what the timestamp comparison
22288        // below is for.
22289        runner.review_loop().await.expect("review_loop");
22290
22291        assert_eq!(
22292            runner.state.reviews.len(),
22293            1,
22294            "no new round was started on top of the unresolved one: {:?}",
22295            runner.state.reviews
22296        );
22297        let last = &runner.state.reviews[0];
22298        assert_eq!(
22299            last.e2e_status(),
22300            E2eStatus::ResourceBlocked,
22301            "still contended: {last:?}"
22302        );
22303        assert!(
22304            last.verified_at.expect("still known") > first_attempt_at,
22305            "review_loop must have actually retried the check, not left it exactly as found"
22306        );
22307        assert_ne!(
22308            runner.state.status,
22309            RunStatus::Blocked,
22310            "a resumed run must not read leftover contention as a verdict on the patch: {:?}",
22311            runner.state.status
22312        );
22313
22314        held.release();
22315    }
22316
22317    #[tokio::test]
22318    async fn stopped_landing_resumes_from_structured_pr_even_with_legacy_gating_status() {
22319        crate::run::pin_test_home();
22320        for status in [RunStatus::Blocked, RunStatus::Gating] {
22321            let mut runner = runner_at(status);
22322            runner.state.config.graph.land = true;
22323            runner.state.gate_ran = true;
22324            runner.state.merge = Some(MergeOutcome {
22325                mode: MergeMode::Pr,
22326                ok: false,
22327                detail: "the fixer produced no commit".into(),
22328                empty: false,
22329            });
22330            let url = "https://example.invalid/o/r/pull/1";
22331            runner.state.pr = Some(crate::run::PrRecord {
22332                url: url.into(),
22333                number: 1,
22334                state: "open".into(),
22335                checks: "red".into(),
22336                round: 1,
22337                rounds: 1,
22338                red_at_merge: Vec::new(),
22339            });
22340            runner.state.save().unwrap();
22341            // The nonexistent repository makes observation fail before a forge
22342            // command can run. We still must reach land, rather than silently
22343            // return from the graph with its old gate and merge records.
22344            runner.execute_graph().await.unwrap();
22345            assert_eq!(runner.state.status, RunStatus::Blocked);
22346            assert!(runner.state.land_sync_pending);
22347            assert!(runner.state.events.iter().any(|event|
22348                event.node == "land" && event.message == format!("watching {url}")));
22349            assert_eq!(
22350                runner.state.merge.as_ref().unwrap().detail,
22351                "the fixer produced no commit"
22352            );
22353        }
22354    }
22355
22356    #[tokio::test]
22357    async fn a_run_resumed_mid_landing_reenters_land_instead_of_opening_a_second_pull_request() {
22358        crate::run::pin_test_home();
22359        let tmp = tempfile::tempdir().expect("tempdir");
22360        let repo = tmp.path().join("repo");
22361        std::fs::create_dir_all(&repo).unwrap();
22362        init_repo(&repo);
22363
22364        let mut config = Config::default();
22365        config.merge.mode = MergeMode::Pr;
22366        config.graph.land = true;
22367        config.graph.land_approval = false;
22368
22369        let mut state = RunState::new(
22370            repo.clone(),
22371            "main".to_owned(),
22372            "deadbeef".to_owned(),
22373            "task".to_owned(),
22374            config,
22375        );
22376        state.candidates = vec![Candidate {
22377            index: 0,
22378            label: 'A',
22379            agent: "alpha".to_owned(),
22380            branch: "does-not-exist".to_owned(),
22381            worktree: repo.clone(),
22382            summary: String::new(),
22383            stat: String::new(),
22384            files: 0,
22385            commits: 0,
22386            empty: false,
22387            failed: None,
22388            verified_noop: None,
22389            duration_ms: 0,
22390            folded: false,
22391        }];
22392        state.tally = Some(Tally {
22393            first_choice: BTreeMap::from([('A', 1)]),
22394            borda: BTreeMap::new(),
22395            winner: 'A',
22396            rankings: 1,
22397            unanimous_initial: true,
22398            deliberated: false,
22399            changed_votes: 0,
22400            unanimous_final: true,
22401            tie_break: None,
22402            judges: 0,
22403            present: 0,
22404            quorum: 0,
22405            met_quorum: true,
22406            uncontested: Some("only candidate A produced a change".to_owned()),
22407        });
22408        state.reviews = vec![ReviewRound {
22409            round: 1,
22410            head: "deadbeef".to_owned(),
22411            verified_head: None,
22412            verified_at: None,
22413            reviews: Vec::new(),
22414            e2e: Vec::new(),
22415            fix: None,
22416            blocking: 0,
22417            answered: 0,
22418            expected: 0,
22419            clean: true,
22420            verify_retried: false,
22421            e2e_deferred: false,
22422            e2e_defer_reason: None,
22423            progressed: false,
22424            vote_split: false,
22425            reconsideration: Vec::new(),
22426            verdict: None,
22427        }];
22428        state.gate = vec![CommandOutcome {
22429            command: "test".to_owned(),
22430            code: Some(0),
22431            output_tail: String::new(),
22432            duration_ms: 0,
22433            resource_blocked: false,
22434        }];
22435        state.gate_ran = true;
22436        // A first pass through `merge` already pushed and opened this pull
22437        // request; `status` is `Landing` because a previous call into `land`
22438        // parked or was interrupted before it reached a terminal outcome.
22439        state.status = RunStatus::Landing;
22440        state.merge = Some(MergeOutcome {
22441            mode: MergeMode::Pr,
22442            ok: true,
22443            detail: "https://example.invalid/x/y/pull/1".to_owned(),
22444            empty: false,
22445        });
22446
22447        // The Landing-resume shortcut calls `run_land` directly rather than
22448        // through `merge`, which is exactly the call site that used to skip
22449        // `settle_questions` - see the fixture below.
22450        ask_test_home();
22451        // A real resume loads a persisted run; driver ownership is checked
22452        // against that record before the Landing shortcut is entered.
22453        state.save().expect("save landing run");
22454        let store = ask::Questions::open();
22455        let q = ask_open_question(&store, &state.id);
22456
22457        let mut runner = Runner {
22458            state,
22459            roles: ResolvedRoles {
22460                implementers: Vec::new(),
22461                judges: Vec::new(),
22462                reviewers: Vec::new(),
22463                fixer: None,
22464                conductor: conductor(),
22465                implementer_roster: Vec::new(),
22466                judge_roster: Vec::new(),
22467                reviewer_roster: Vec::new(),
22468            },
22469            sem: Arc::new(Semaphore::new(1)),
22470            pause: Pause::new(),
22471            interrupt: Pause::new(),
22472        };
22473
22474        // `execute`, not `merge` directly: the Landing-resume shortcut lives
22475        // at the top of `execute`, not inside `merge` (see `execute`'s doc)
22476        // exactly because `review_loop` would otherwise clobber the marker
22477        // first.
22478        runner.execute().await.expect("execute");
22479
22480        assert_eq!(
22481            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
22482            Some("https://example.invalid/x/y/pull/1"),
22483            "reentry must not push again or open a second pull request over the \
22484             one `land` is already watching"
22485        );
22486        assert_ne!(
22487            runner.state.status,
22488            RunStatus::Landing,
22489            "land could not actually reach the fake pull request, so it must \
22490             have given up rather than left the run silently parked forever"
22491        );
22492        // `land` could not reach the fake pull request, so it gave up into
22493        // `Blocked` - still resumable, so the question must not have been
22494        // swept just because this branch now also calls `settle_questions`.
22495        assert_eq!(runner.state.status, RunStatus::Blocked);
22496        assert!(
22497            store.get(&q.id).unwrap().status.open(),
22498            "Blocked is still alive; settle_questions must have been a no-op here"
22499        );
22500    }
22501
22502    fn state_with_round(round: ReviewRound) -> RunState {
22503        let mut s = RunState::new(
22504            PathBuf::from("/repo"),
22505            "main".to_owned(),
22506            "abc1234".to_owned(),
22507            "add retries".to_owned(),
22508            Config::default(),
22509        );
22510        s.reviews = vec![round];
22511        s
22512    }
22513
22514    fn finding(id: &str, severity: Severity, title: &str) -> crate::verdict::Finding {
22515        crate::verdict::Finding {
22516            id: id.to_owned(),
22517            severity,
22518            file: None,
22519            line: None,
22520            title: title.to_owned(),
22521            detail: String::new(),
22522        }
22523    }
22524
22525    #[test]
22526    fn pr_body_names_open_findings_and_declined_ones() {
22527        let round = ReviewRound {
22528            round: 2,
22529            head: "deadbee".to_owned(),
22530            verified_head: None,
22531            verified_at: None,
22532            reviews: vec![ReviewRecord {
22533                attempts: 0,
22534                reviewer: 1,
22535                agent: "alpha".to_owned(),
22536                summary: String::new(),
22537                findings: vec![finding("R2-1-1", Severity::Minor, "unused import")],
22538                vote: None,
22539                failed: None,
22540                duration_ms: 0,
22541            }],
22542            e2e: vec![CommandOutcome {
22543                command: "cargo test".to_owned(),
22544                code: Some(0),
22545                output_tail: String::new(),
22546                duration_ms: 0,
22547                resource_blocked: false,
22548            }],
22549            verify_retried: false,
22550            e2e_deferred: false,
22551            e2e_defer_reason: None,
22552            fix: Some(FixRecord {
22553                agent: "alpha".to_owned(),
22554                addressed: Vec::new(),
22555                rejected: vec![crate::verdict::Rejection {
22556                    id: "R1-1-1".to_owned(),
22557                    why: "not reachable from any caller".to_owned(),
22558                }],
22559                notes: String::new(),
22560                committed: true,
22561                failed: None,
22562                duration_ms: 0,
22563                continuation: None,
22564            }),
22565            blocking: 0,
22566            answered: 1,
22567            expected: 1,
22568            clean: false,
22569            progressed: true,
22570            vote_split: false,
22571            reconsideration: Vec::new(),
22572            verdict: None,
22573        };
22574        let state = state_with_round(round);
22575        let body = pr_message(&state, 'A').body;
22576
22577        assert!(body.contains("add retries"), "the task must still be there");
22578        assert!(body.contains("R2-1-1"), "{body}");
22579        assert!(!body.contains("unused import"), "{body}");
22580        assert!(body.contains("R1-1-1"), "the declined finding: {body}");
22581        assert!(
22582            !body.contains("not reachable from any caller"),
22583            "the reason it was declined: {body}"
22584        );
22585    }
22586
22587    #[test]
22588    fn pr_body_says_nothing_extra_when_the_round_was_clean() {
22589        let round = ReviewRound {
22590            round: 1,
22591            head: "deadbee".to_owned(),
22592            verified_head: None,
22593            verified_at: None,
22594            reviews: vec![ReviewRecord {
22595                attempts: 0,
22596                reviewer: 1,
22597                agent: "alpha".to_owned(),
22598                summary: String::new(),
22599                findings: Vec::new(),
22600                vote: None,
22601                failed: None,
22602                duration_ms: 0,
22603            }],
22604            e2e: Vec::new(),
22605            verify_retried: false,
22606            e2e_deferred: false,
22607            e2e_defer_reason: None,
22608            fix: None,
22609            blocking: 0,
22610            answered: 1,
22611            expected: 1,
22612            clean: true,
22613            progressed: false,
22614            vote_split: false,
22615            reconsideration: Vec::new(),
22616            verdict: None,
22617        };
22618        let state = state_with_round(round);
22619        let body = pr_message(&state, 'A').body;
22620        assert!(!body.contains("Open review findings"), "{body}");
22621        assert!(!body.contains("Declined"), "{body}");
22622    }
22623
22624    fn state_with_summary(instruction: &str, summary: &str) -> RunState {
22625        let mut state = RunState::new(
22626            PathBuf::from("/repo"),
22627            "main".to_owned(),
22628            "abc1234".to_owned(),
22629            instruction.to_owned(),
22630            Config::default(),
22631        );
22632        // These fixtures test execution flow, independent of host disk capacity.
22633        state.config.disk.min_free_bytes = 0;
22634        state.candidates.push(Candidate {
22635            index: 0,
22636            label: 'A',
22637            agent: "alpha".to_owned(),
22638            branch: "magi/x/A".to_owned(),
22639            worktree: PathBuf::from("/wt"),
22640            summary: summary.to_owned(),
22641            stat: String::new(),
22642            files: 1,
22643            commits: 1,
22644            empty: false,
22645            failed: None,
22646            verified_noop: None,
22647            folded: false,
22648            duration_ms: 0,
22649        });
22650        state
22651    }
22652
22653    fn review_state(subjects: &[&str]) -> RunState {
22654        let mut state = state_with_summary(
22655            "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",
22656            "",
22657        );
22658        state.candidates[0].agent = EXISTING_BRANCH.to_owned();
22659        state.reviewed_commits = Some(subjects.iter().map(|s| (*s).to_owned()).collect());
22660        state
22661    }
22662
22663    /// A branch rebased onto a main that moved past the recorded
22664    /// `base_commit` is titled from its own first commit, never main's.
22665    #[tokio::test]
22666    async fn a_rebased_review_branch_is_titled_from_its_own_commits() {
22667        ask_test_home();
22668        let tmp = tempfile::tempdir().unwrap();
22669        let repo = tmp.path().join("repo");
22670        std::fs::create_dir_all(&repo).unwrap();
22671        init_repo(&repo);
22672        let origin = tmp.path().join("origin.git");
22673        let g = |dir: &Path, args: &[&str]| {
22674            let out = std::process::Command::new("git")
22675                .args(args)
22676                .current_dir(dir)
22677                .quiet()
22678                .output()
22679                .expect("spawn git");
22680            assert!(
22681                out.status.success(),
22682                "git {args:?}: {}",
22683                String::from_utf8_lossy(&out.stderr)
22684            );
22685        };
22686        g(
22687            tmp.path(),
22688            &[
22689                "clone",
22690                "--bare",
22691                "-q",
22692                repo.to_str().unwrap(),
22693                origin.to_str().unwrap(),
22694            ],
22695        );
22696        g(
22697            &repo,
22698            &["remote", "add", "origin", origin.to_str().unwrap()],
22699        );
22700        let c1 = git::rev_parse(&repo, "main").await.unwrap();
22701
22702        // Main moves on; the branch is built on top of the new main.
22703        std::fs::write(repo.join("dep.txt"), "bump\n").unwrap();
22704        g(&repo, &["add", "-A"]);
22705        g(
22706            &repo,
22707            &["commit", "-q", "-m", "chore(deps): update a crate"],
22708        );
22709        g(&repo, &["push", "-q", "origin", "main"]);
22710        g(&repo, &["checkout", "-q", "-b", "feat/own"]);
22711        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
22712        g(&repo, &["add", "-A"]);
22713        g(
22714            &repo,
22715            &["commit", "-q", "-m", "fix(daemon): apply a chosen action"],
22716        );
22717        g(&repo, &["checkout", "-q", "main"]);
22718
22719        let start = review_base(&repo, "origin", "main", &c1, "feat/own").await;
22720        assert_eq!(start, git::rev_parse(&repo, "main").await.unwrap());
22721        // Without a readable tracking ref the recorded base's merge base is used.
22722        let fallback = review_base(&repo, "nowhere", "main", &c1, "feat/own").await;
22723        assert_eq!(fallback, c1);
22724
22725        let mut state = review_state(&[
22726            "chore(deps): update a crate",
22727            "fix(daemon): apply a chosen action",
22728        ]);
22729        state.repo = repo.clone();
22730        state.base_branch = "main".to_owned();
22731        state.base_commit = c1;
22732        refresh_reviewed_commits(&mut state, "feat/own").await;
22733        assert_eq!(
22734            state.reviewed_commits,
22735            Some(vec!["fix(daemon): apply a chosen action".to_owned()])
22736        );
22737        assert_eq!(
22738            review_title(&state).as_deref(),
22739            Some("fix(daemon): apply a chosen action")
22740        );
22741        assert_eq!(
22742            leaked_subjects(&state, "feat/own").await,
22743            Some(vec!["chore(deps): update a crate".to_owned()])
22744        );
22745        // A stale tracking ref is still used when the fetch fails, but the
22746        // leak list is withheld.
22747        state.config.merge.remote = "nowhere".to_owned();
22748        assert_eq!(leaked_subjects(&state, "feat/own").await, None);
22749    }
22750
22751    /// A review-only run whose winner is `feat/own`, checked out in `repo`,
22752    /// with `origin/main` one commit behind it, and a summarizing agent that
22753    /// prints whatever `reply` holds.
22754    struct SummaryFixture {
22755        _tmp: tempfile::TempDir,
22756        repo: PathBuf,
22757        reply: PathBuf,
22758        runner: Runner,
22759    }
22760
22761    fn summary_fixture() -> SummaryFixture {
22762        ask_test_home();
22763        let tmp = tempfile::tempdir().unwrap();
22764        let repo = tmp.path().join("repo");
22765        std::fs::create_dir_all(&repo).unwrap();
22766        init_repo(&repo);
22767        let origin = tmp.path().join("origin.git");
22768        let g = |args: &[&str]| {
22769            let out = std::process::Command::new("git")
22770                .args(args)
22771                .current_dir(&repo)
22772                .quiet()
22773                .output()
22774                .expect("spawn git");
22775            assert!(
22776                out.status.success(),
22777                "git {args:?}: {}",
22778                String::from_utf8_lossy(&out.stderr)
22779            );
22780        };
22781        g(&["init", "-q", "--bare", origin.to_str().unwrap()]);
22782        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
22783        g(&["push", "-q", "origin", "main"]);
22784        g(&["checkout", "-q", "-b", "feat/own"]);
22785        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
22786        g(&["add", "-A"]);
22787        g(&["commit", "-q", "-m", "feat(own): add the own file"]);
22788        let reply = tmp.path().join("reply.txt");
22789        std::fs::write(
22790            &reply,
22791            "TITLE: feat(own): add the own file\nAdds `own.txt` so the first summary is read.",
22792        )
22793        .unwrap();
22794        let mut runner = runner_at(RunStatus::Gating);
22795        let mut state = review_state(&["feat(own): add the own file"]);
22796        state.repo = repo.clone();
22797        state.base_branch = "main".to_owned();
22798        state.candidates[0].branch = "feat/own".to_owned();
22799        state.candidates[0].worktree = repo.clone();
22800        let mut author = spec("alpha");
22801        author.command = vec!["sh".into(), "-c".into(), "cat \"$REPLY_FILE\"".into()];
22802        author
22803            .env
22804            .insert("REPLY_FILE".into(), reply.to_string_lossy().into_owned());
22805        state.config.agents = vec![author];
22806        runner.state = state;
22807        SummaryFixture {
22808            _tmp: tmp,
22809            repo,
22810            reply,
22811            runner,
22812        }
22813    }
22814
22815    async fn posted(f: &mut SummaryFixture) -> PrMessage {
22816        let winner = f.runner.state.candidates[0].clone();
22817        f.runner
22818            .guarded_pr_message(&winner, None, true)
22819            .await
22820            .unwrap()
22821            .expect("an English description never parks")
22822    }
22823
22824    fn clean_round_with_minor_findings() -> ReviewRound {
22825        let mut round = passing_round(2, None);
22826        round.verdict = Some(crate::verdict::ReviewVote::ApproveWithFindings);
22827        round.reviews = vec![ReviewRecord {
22828            attempts: 0,
22829            reviewer: 1,
22830            agent: "alpha".into(),
22831            summary: "内部レビュー".into(),
22832            findings: vec![
22833                finding("R2-1-1", Severity::Minor, "未修正の懸念その一"),
22834                finding("R2-1-2", Severity::Minor, "未修正の懸念その二"),
22835            ],
22836            vote: Some(crate::verdict::ReviewVote::ApproveWithFindings),
22837            failed: None,
22838            duration_ms: 0,
22839        }];
22840        round
22841    }
22842
22843    #[tokio::test]
22844    async fn public_descriptions_cover_minor_findings_from_clean_rounds_in_both_modes() {
22845        for review_only in [false, true] {
22846            let mut f = summary_fixture();
22847            if !review_only {
22848                f.runner.state.candidates[0].agent = "alpha".into();
22849            }
22850            f.runner.state.reviews = vec![clean_round_with_minor_findings()];
22851            assert!(f.runner.state.reviews[0].clean);
22852            assert!(f.runner.state.reviews[0].fix.is_none());
22853            assert!(f.runner.state.open_findings().is_empty());
22854            assert_eq!(
22855                crate::pr_outcome::required_finding_ids(&f.runner.state),
22856                ["R2-1-1", "R2-1-2"]
22857            );
22858            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
22859            let evidence = crate::pr_outcome::summary_evidence(
22860                &f.runner.state,
22861                crate::pr_outcome::FinalHead::At(&head),
22862            );
22863            assert!(
22864                evidence.contains("未修正の懸念その一") && evidence.contains("未修正の懸念その二")
22865            );
22866            // The ordinary reply omits both IDs: no cached description is adopted.
22867            let omitted = posted(&mut f).await;
22868            assert!(omitted.body.contains("No description"));
22869            assert!(omitted.body.contains("`R2-1-1` [Minor]"));
22870            assert!(omitted.body.contains("`R2-1-2` [Minor]"));
22871            assert!(f.runner.state.change_summary.is_none());
22872            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();
22873            let described = posted(&mut f).await;
22874            assert!(described.body.contains("improve documentation for callers"));
22875            assert!(described.body.contains("remaining edge case"));
22876            assert!(described.body.contains("## Open review findings"));
22877            assert!(!described.body.contains("未修正"));
22878        }
22879    }
22880
22881    async fn rewrite_fixture_with_findings(review_only: bool, reply: &str) -> SummaryFixture {
22882        let mut f = summary_fixture();
22883        if !review_only {
22884            f.runner.state.candidates[0].agent = "alpha".into();
22885        }
22886        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
22887        let mut fixed = round_with_notes(1, Some("日本語の内部修正報告"));
22888        fixed
22889            .fix
22890            .as_mut()
22891            .unwrap()
22892            .rejected
22893            .push(crate::verdict::Rejection {
22894                id: "R1-1-1".into(),
22895                why: "呼び出されないコードのため辞退".into(),
22896            });
22897        let mut clean = clean_round_with_minor_findings();
22898        clean.verified_head = Some(head.clone());
22899        f.runner.state.reviews = vec![fixed, clean];
22900        ok_gate(&mut f.runner.state, Some(&head));
22901        std::fs::write(&f.reply, "TITLE: fix: public description\n日本語の公開用説明です。R1-1-1 は辞退。R2-1-1 と R2-1-2 の懸念が残ります。").unwrap();
22902        f.runner.state.config.agents.push(scripted("beta", reply));
22903        f.runner.state.config.roles.language_judge =
22904            Some(crate::config::AgentChoice::One("beta".into()));
22905        f
22906    }
22907
22908    #[tokio::test]
22909    async fn posting_rewrite_retains_structured_evidence_and_finding_explanations() {
22910        for review_only in [false, true] {
22911            let mut f = rewrite_fixture_with_findings(review_only,
22912                "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;
22913            let m = posted(&mut f).await;
22914            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
22915            let expected =
22916                public_pr_evidence(&f.runner.state, crate::pr_outcome::FinalHead::At(&head));
22917            assert!(m.body.contains(&expected));
22918            assert!(m.body.contains("## Review rounds"));
22919            assert!(
22920                m.body
22921                    .contains("Gate (`verify.gate`): passed on the final commit")
22922            );
22923            assert!(
22924                m.body
22925                    .contains("Tests (`verify.e2e`): passed on the final commit")
22926            );
22927            let c = f.runner.state.change_summary.as_ref().unwrap();
22928            assert!(
22929                m.body
22930                    .contains(&format!("Evidence: final diff `{}`..`{}`", c.base, head))
22931            );
22932            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
22933            assert!(crate::pr_outcome::covers_required_findings(
22934                &f.runner.state,
22935                &m.body
22936            ));
22937            assert!(m.body.contains("documentation remains incomplete"));
22938            assert!(!m.body.contains("内部") && !m.body.contains("辞退"));
22939            assert_eq!(f.runner.state.seats["github-text-rewrite"].turns, 1);
22940            assert!(f.runner.state.github_text.is_none());
22941        }
22942    }
22943
22944    #[tokio::test]
22945    async fn posting_rewrite_missing_required_finding_context_is_not_offered_or_published() {
22946        for review_only in [false, true] {
22947            for reply in [
22948                "TITLE: fix: public description\nA short English description.",
22949                "TITLE: fix: public description\nR1-1-1 and R2-1-2 remain; R2-1-1-extra is a different ID.",
22950            ] {
22951                let mut f = rewrite_fixture_with_findings(review_only, reply).await;
22952                let winner = f.runner.state.candidates[0].clone();
22953                let posted = f
22954                    .runner
22955                    .guarded_pr_message(&winner, None, true)
22956                    .await
22957                    .unwrap();
22958                assert!(posted.is_none());
22959                assert!(f.runner.state.parked);
22960                let withheld = f.runner.state.github_text.as_ref().unwrap();
22961                assert!(
22962                    withheld.rewrite.is_none(),
22963                    "an incomplete rewrite must not be selectable"
22964                );
22965                let q = ask::Questions::open()
22966                    .get(withheld.question.as_ref().unwrap())
22967                    .unwrap();
22968                assert!(
22969                    !q.choices
22970                        .contains(&crate::github_text::USE_REWRITE.to_owned())
22971                );
22972                assert!(
22973                    q.detail.contains("R1-1-1")
22974                        && q.detail.contains("R2-1-1")
22975                        && q.detail.contains("R2-1-2")
22976                );
22977            }
22978        }
22979    }
22980
22981    #[tokio::test]
22982    async fn japanese_reports_stay_local_in_both_public_run_modes() {
22983        for review_only in [false, true] {
22984            let mut f = summary_fixture();
22985            if !review_only {
22986                f.runner.state.candidates[0].agent = "alpha".into();
22987            }
22988            f.runner.state.instruction = "内部タスクの説明".into();
22989            f.runner.state.candidates[0].summary = "内部の候補報告".into();
22990            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
22991            f.runner.state.reviews = vec![
22992                round_with_notes(1, Some("コミットできません。テストは実行できません。")),
22993                round_with_notes(2, Some("二回目の内部修正報告です。")),
22994                passing_round(3, Some(&head)),
22995            ];
22996            f.runner.state.reviews[0].fix.as_mut().unwrap().addressed = vec!["R1-1-1".into()];
22997            ok_gate(&mut f.runner.state, Some(&head));
22998            let captured = f.repo.join("public-prompt.txt");
22999            let author = &mut f.runner.state.config.agents[0];
23000            author.command = vec![
23001                "sh".into(),
23002                "-c".into(),
23003                "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
23004            ];
23005            author.env.insert(
23006                "PROMPT_FILE".into(),
23007                captured.to_string_lossy().into_owned(),
23008            );
23009            let m = posted(&mut f).await;
23010            assert!(m.body.contains("Adds `own.txt`"));
23011            assert!(m.body.contains("Round 1") && m.body.contains("Round 2"));
23012            assert!(m.body.contains("R1-1-1"));
23013            assert!(
23014                m.body
23015                    .contains("Gate (`verify.gate`): passed on the final commit")
23016            );
23017            assert!(
23018                m.body
23019                    .contains("Tests (`verify.e2e`): passed on the final commit")
23020            );
23021            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
23022            assert!(!m.body.contains("内部") && !m.body.contains("できません"));
23023            let prompt = std::fs::read_to_string(captured).unwrap();
23024            assert!(prompt.contains(&format!(
23025                "git diff {} {head}",
23026                f.runner.state.change_summary.as_ref().unwrap().base
23027            )));
23028            assert!(!prompt.contains("二回目") && !prompt.contains("コミットできません"));
23029            assert_eq!(
23030                f.runner.state.reviews[1].fix.as_ref().unwrap().notes,
23031                "二回目の内部修正報告です。"
23032            );
23033        }
23034    }
23035
23036    #[tokio::test]
23037    async fn public_generation_failure_never_falls_back_to_internal_notes_and_resume_retries() {
23038        for review_only in [false, true] {
23039            let mut f = summary_fixture();
23040            if !review_only {
23041                f.runner.state.candidates[0].agent = "alpha".into();
23042            }
23043            f.runner.state.candidates[0].summary = "内部報告を公開しない".into();
23044            f.runner.state.reviews = vec![round_with_notes(1, Some("日本語の修正報告"))];
23045            std::fs::write(&f.reply, "no usable description").unwrap();
23046            let failed = posted(&mut f).await;
23047            assert!(
23048                failed
23049                    .body
23050                    .contains("No description of what this change does could be generated")
23051            );
23052            assert!(failed.body.is_ascii());
23053            assert!(f.runner.state.github_text.is_none());
23054            assert!(f.runner.state.change_summary.is_none());
23055            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23056            let evidence = crate::pr_outcome::summary_evidence(
23057                &f.runner.state,
23058                crate::pr_outcome::FinalHead::At(&head),
23059            );
23060            let fp = crate::pr_outcome::summary_fingerprint(&f.runner.state, &evidence);
23061            assert!(
23062                crate::run::artifact_path(&f.runner.state, &format!("public-description-{fp}.md"))
23063                    .exists()
23064            );
23065            f.runner.state =
23066                serde_json::from_str(&serde_json::to_string(&f.runner.state).unwrap()).unwrap();
23067            std::fs::write(
23068                &f.reply,
23069                "TITLE: feat(own): add the own file\nAdds the committed own file.",
23070            )
23071            .unwrap();
23072            let retried = posted(&mut f).await;
23073            assert!(retried.body.contains("Adds the committed own file."));
23074            assert_eq!(
23075                f.runner.state.reviews[0].fix.as_ref().unwrap().notes,
23076                "日本語の修正報告"
23077            );
23078        }
23079    }
23080
23081    #[tokio::test]
23082    async fn same_head_verification_and_findings_invalidate_public_prose() {
23083        let mut f = summary_fixture();
23084        posted(&mut f).await;
23085        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23086        let original = f
23087            .runner
23088            .state
23089            .change_summary
23090            .as_ref()
23091            .unwrap()
23092            .evidence
23093            .clone();
23094        ok_gate(&mut f.runner.state, Some(&head));
23095        std::fs::write(
23096            &f.reply,
23097            "TITLE: feat(own): add the own file\nDescribes the now verified final change.",
23098        )
23099        .unwrap();
23100        let verified = posted(&mut f).await;
23101        assert!(verified.body.contains("now verified"));
23102        assert_ne!(
23103            f.runner.state.change_summary.as_ref().unwrap().evidence,
23104            original
23105        );
23106        let mut round = round_with_notes(1, Some("内部報告"));
23107        round.reviews.push(ReviewRecord {
23108            attempts: 0,
23109            reviewer: 1,
23110            agent: "alpha".into(),
23111            summary: "内部レビュー".into(),
23112            findings: vec![finding("R1-1-1", Severity::Minor, "残っている懸念")],
23113            vote: None,
23114            failed: None,
23115            duration_ms: 0,
23116        });
23117        round
23118            .fix
23119            .as_mut()
23120            .unwrap()
23121            .rejected
23122            .push(crate::verdict::Rejection {
23123                id: "R1-1-1".into(),
23124                why: "呼び出し元から到達できない".into(),
23125            });
23126        f.runner.state.reviews = vec![round];
23127        // A description omitting the required ID is unusable, even with a title.
23128        let omitted = posted(&mut f).await;
23129        assert!(omitted.body.contains("No description"));
23130        assert!(omitted.body.contains("R1-1-1"));
23131        assert!(!omitted.body.contains("到達"));
23132        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();
23133        let described = posted(&mut f).await;
23134        assert!(described.body.contains("unreachable from callers"));
23135        assert!(described.body.contains("R1-1-1"));
23136        assert!(!described.body.contains("到達"));
23137        let evidence = f
23138            .runner
23139            .state
23140            .change_summary
23141            .as_ref()
23142            .unwrap()
23143            .evidence
23144            .clone();
23145        f.runner.state.reviews[0].fix.as_mut().unwrap().rejected[0].why = "別の根拠".into();
23146        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: decline rationale updated after review.").unwrap();
23147        assert!(posted(&mut f).await.body.contains("rationale updated"));
23148        assert_ne!(
23149            f.runner.state.change_summary.as_ref().unwrap().evidence,
23150            evidence
23151        );
23152        // Old serialized summaries have no evidence fingerprint and must regenerate.
23153        f.runner
23154            .state
23155            .change_summary
23156            .as_mut()
23157            .unwrap()
23158            .evidence
23159            .clear();
23160        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: regenerated under the current specification.").unwrap();
23161        assert!(posted(&mut f).await.body.contains("current specification"));
23162    }
23163
23164    #[tokio::test]
23165    async fn a_review_only_run_with_no_fixer_gets_a_summary_of_the_final_diff() {
23166        let mut f = summary_fixture();
23167        let m = posted(&mut f).await;
23168        assert_eq!(m.title, "feat(own): add the own file");
23169        assert!(
23170            m.body
23171                .contains("## Summary\n\nAdds `own.txt` so the first summary is read."),
23172            "{}",
23173            m.body
23174        );
23175        assert!(!m.body.contains("## Review fixes"), "{}", m.body);
23176        assert!(m.body.contains("Evidence: final diff"), "{}", m.body);
23177        assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
23178        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23179        let base = git::rev_parse(&f.repo, "origin/main").await.unwrap();
23180        let kept = f.runner.state.change_summary.as_ref().unwrap();
23181        assert_eq!(
23182            (kept.head.as_str(), kept.base.as_str()),
23183            (head.as_str(), base.as_str())
23184        );
23185        assert!(!f.runner.state.seats["change-summary"].key.is_empty());
23186    }
23187
23188    #[tokio::test]
23189    async fn review_only_summary_receives_the_configured_github_language() {
23190        let mut f = summary_fixture();
23191        f.runner.state.config.graph.github_language = "ja".into();
23192        let captured = f.repo.join("summary-prompt.txt");
23193        let author = &mut f.runner.state.config.agents[0];
23194        author.command = vec![
23195            "sh".into(),
23196            "-c".into(),
23197            "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
23198        ];
23199        author.env.insert(
23200            "PROMPT_FILE".into(),
23201            captured.to_string_lossy().into_owned(),
23202        );
23203        std::fs::write(
23204            &f.reply,
23205            "TITLE: feat(own): ファイルを追加\nown.txt を追加します。",
23206        )
23207        .unwrap();
23208        let m = posted(&mut f).await;
23209        let prompt = std::fs::read_to_string(captured).unwrap();
23210        assert!(prompt.contains("Write the TITLE line and the Markdown description in Japanese."));
23211        assert!(!prompt.contains("in English"));
23212        assert_eq!(m.title, "feat(own): ファイルを追加");
23213        assert!(m.body.contains("own.txt を追加します。"));
23214    }
23215
23216    #[tokio::test]
23217    async fn review_fixes_come_after_the_whole_change_summary() {
23218        let mut f = summary_fixture();
23219        f.runner.state.reviews = vec![
23220            round_with_notes(1, Some("handled the PATH case")),
23221            round_with_notes(2, None),
23222        ];
23223        let m = posted(&mut f).await;
23224        let summary = m.body.find("## Summary").expect("summary");
23225        let fixes = m.body.find("## Review rounds").expect("review rounds");
23226        assert!(summary < fixes, "{}", m.body);
23227        assert!(!m.body.contains("handled the PATH case"), "{}", m.body);
23228        assert!(m.body.contains("## Final verification"), "{}", m.body);
23229    }
23230
23231    #[tokio::test]
23232    async fn a_changed_final_diff_invalidates_the_earlier_summary() {
23233        let mut f = summary_fixture();
23234        let first = posted(&mut f).await;
23235        let first_head = f.runner.state.change_summary.clone().unwrap().head;
23236        // The same head reuses the record: a different reply is not read.
23237        std::fs::write(&f.reply, "TITLE: feat(own): other\nNot read yet.").unwrap();
23238        let again = posted(&mut f).await;
23239        assert_eq!((again.title, again.body), (first.title, first.body));
23240
23241        let g = |args: &[&str]| {
23242            let out = std::process::Command::new("git")
23243                .args(args)
23244                .current_dir(&f.repo)
23245                .quiet()
23246                .output()
23247                .expect("spawn git");
23248            assert!(out.status.success(), "git {args:?}");
23249        };
23250        std::fs::write(f.repo.join("more.txt"), "more\n").unwrap();
23251        g(&["add", "-A"]);
23252        g(&["commit", "-q", "-m", "fix(own): handle more"]);
23253        let second = posted(&mut f).await;
23254        let kept = f.runner.state.change_summary.clone().unwrap();
23255        assert_ne!(kept.head, first_head);
23256        assert!(second.body.contains("Not read yet."), "{}", second.body);
23257        assert!(!second.body.contains("so the first summary is read"));
23258        assert_eq!(second.title, "feat(own): other");
23259    }
23260
23261    #[tokio::test]
23262    async fn an_unavailable_summary_is_stated_and_never_invented() {
23263        let mut f = summary_fixture();
23264        std::fs::write(&f.reply, "no title line here").unwrap();
23265        let m = posted(&mut f).await;
23266        assert!(
23267            m.body
23268                .contains("No description of what this change does could be generated"),
23269            "{}",
23270            m.body
23271        );
23272        assert!(m.body.contains("internal reports remain in local records"));
23273        assert!(f.runner.state.change_summary.is_none());
23274        assert!(!m.body.contains("## Commits under review"), "{}", m.body);
23275        // A preview asks nobody and claims nothing.
23276        let winner = f.runner.state.candidates[0].clone();
23277        let preview = f
23278            .runner
23279            .guarded_pr_message(&winner, None, false)
23280            .await
23281            .unwrap()
23282            .unwrap();
23283        assert!(!preview.body.contains("## Summary"), "{}", preview.body);
23284    }
23285
23286    #[test]
23287    fn pr_message_review_single_commit_uses_its_subject() {
23288        let state = review_state(&["feat(nats): per-role user"]);
23289        let m = pr_message(&state, 'A');
23290        assert_eq!(m.title, "feat(nats): per-role user");
23291        assert!(!m.body.contains("Review the work already"), "{}", m.body);
23292        assert!(m.body.contains("## Commits under review"), "{}", m.body);
23293    }
23294
23295    #[test]
23296    fn pr_message_review_multi_commit_takes_the_oldest() {
23297        let state = review_state(&["feat: the change", "fix: typo", "fix: again"]);
23298        let m = pr_message(&state, 'A');
23299        assert_eq!(m.title, "feat: the change");
23300        for s in ["feat: the change", "fix: typo", "fix: again"] {
23301            assert!(m.body.contains(&format!("- {s}\n")), "{}", m.body);
23302        }
23303    }
23304
23305    #[test]
23306    fn pr_message_review_without_a_usable_first_subject_is_neutral() {
23307        for first in ["日本語の件名", "", "magi: candidate A (uncommitted work)"] {
23308            let mut state = review_state(&[first, "fix: later fixup"]);
23309            state.candidates[0].branch = "機能/ログイン".to_owned();
23310            let m = pr_message(&state, 'A');
23311            assert!(
23312                m.title.starts_with("chore: land candidate A of run"),
23313                "{}",
23314                m.title
23315            );
23316        }
23317    }
23318
23319    fn facts(commits: &[(&str, &str)], stat: &str) -> BranchFacts {
23320        BranchFacts {
23321            commits: commits
23322                .iter()
23323                .map(|(s, b)| ((*s).to_owned(), (*b).to_owned()))
23324                .collect(),
23325            stat: stat.to_owned(),
23326        }
23327    }
23328
23329    fn round_with_notes(round: usize, notes: Option<&str>) -> ReviewRound {
23330        let mut r = review_round(true, 0, 1, 1, true, true);
23331        r.round = round;
23332        r.fix = notes.map(|n| FixRecord {
23333            agent: "fixer".to_owned(),
23334            addressed: Vec::new(),
23335            rejected: Vec::new(),
23336            notes: n.to_owned(),
23337            committed: true,
23338            failed: None,
23339            duration_ms: 0,
23340            continuation: None,
23341        });
23342        r
23343    }
23344
23345    #[test]
23346    fn pr_message_review_with_branch_facts_uses_commits_and_stat() {
23347        let state = review_state(&["ignored"]);
23348        let f = facts(
23349            &[
23350                (
23351                    "fix(login): resolve PATH on macOS",
23352                    "Login shells skip rc files.",
23353                ),
23354                ("fix: address review", ""),
23355            ],
23356            " src/a.rs | 2 +-\n 1 file changed, 1 insertion(+), 1 deletion(-)",
23357        );
23358        let m = pr_message_with(&state, 'A', Some(&f));
23359        assert_eq!(m.title, "fix(login): resolve PATH on macOS");
23360        assert!(
23361            m.body
23362                .contains("- fix(login): resolve PATH on macOS\n  Login shells skip rc files.\n"),
23363            "{}",
23364            m.body
23365        );
23366        assert!(m.body.contains("- fix: address review\n"), "{}", m.body);
23367        assert!(m.body.contains("## Diff stat"), "{}", m.body);
23368        assert!(m.body.contains("src/a.rs | 2 +-"), "{}", m.body);
23369        for banned in [
23370            "Review the work already",
23371            "no task statement",
23372            "Original task",
23373        ] {
23374            assert!(!m.body.contains(banned), "{banned}: {}", m.body);
23375        }
23376        assert!(m.body.ends_with("magi:candidate-a\n"), "{}", m.body);
23377    }
23378
23379    #[test]
23380    fn pr_message_review_truncates_a_huge_first_commit_body() {
23381        let state = review_state(&["ignored"]);
23382        let f = facts(
23383            &[("feat: big", &"x".repeat(70_000)), ("fix: later", "")],
23384            "s",
23385        );
23386        let m = pr_message_with(&state, 'A', Some(&f));
23387        assert!(m.body.len() < 30_000, "{}", m.body.len());
23388        assert!(m.body.contains("(truncated)"), "{}", m.body.len());
23389        assert!(
23390            m.body.contains("- ... 1 more commit(s)"),
23391            "{}",
23392            m.body.len()
23393        );
23394        assert!(m.body.ends_with("magi:candidate-a\n"));
23395    }
23396
23397    #[test]
23398    fn pr_message_review_without_facts_falls_back_to_recorded_subjects() {
23399        let m = pr_message_with(&review_state(&["feat: x", "fix: y"]), 'A', None);
23400        assert_eq!(m.title, "feat: x");
23401        assert!(m.body.contains("- fix: y\n"), "{}", m.body);
23402        assert!(!m.body.contains("Diff stat"), "{}", m.body);
23403        assert!(!m.body.contains("no task statement"), "{}", m.body);
23404    }
23405
23406    #[test]
23407    fn pr_message_review_titles_from_the_branch_name_when_subjects_are_unusable() {
23408        let mut state = review_state(&["日本語の件名"]);
23409        state.candidates[0].branch = "fix/macos-login-path".to_owned();
23410        assert_eq!(pr_message(&state, 'A').title, "fix/macos-login-path");
23411        state.candidates[0].branch = "機能/ログイン".to_owned();
23412        assert!(
23413            pr_message(&state, 'A')
23414                .title
23415                .starts_with("chore: land candidate A")
23416        );
23417    }
23418
23419    #[test]
23420    fn pr_message_review_fixes_survive_a_clean_final_round() {
23421        let mut state = review_state(&["feat: x"]);
23422        state.reviews = vec![
23423            round_with_notes(1, Some("handled the PATH case")),
23424            round_with_notes(2, None),
23425        ];
23426        let body = pr_message(&state, 'A').body;
23427        assert!(
23428            body.contains("## Review rounds") && !body.contains("handled the PATH case"),
23429            "{body}"
23430        );
23431        assert!(body.contains("### Round 1"), "{body}");
23432
23433        state.reviews = vec![
23434            round_with_notes(1, Some("first fix")),
23435            round_with_notes(2, Some("")),
23436            round_with_notes(3, Some("second fix")),
23437            round_with_notes(4, None),
23438        ];
23439        let body = pr_message(&state, 'A').body;
23440        assert!(
23441            body.contains("### Round 1") && !body.contains("first fix"),
23442            "{body}"
23443        );
23444        assert!(
23445            body.contains("### Round 3") && !body.contains("second fix"),
23446            "{body}"
23447        );
23448        assert!(body.contains("### Round 2"), "{body}");
23449    }
23450
23451    const FINAL: &str = "abcdef1234567890";
23452
23453    fn passing_round(round: usize, verified: Option<&str>) -> ReviewRound {
23454        let mut r = round_with_notes(round, None);
23455        r.verified_head = verified.map(str::to_owned);
23456        r
23457    }
23458
23459    fn ok_gate(state: &mut RunState, head: Option<&str>) {
23460        state.gate = vec![CommandOutcome {
23461            command: "gate".to_owned(),
23462            code: Some(0),
23463            output_tail: String::new(),
23464            duration_ms: 0,
23465            resource_blocked: false,
23466        }];
23467        state.gate_ran = true;
23468        state.gate_head = head.map(str::to_owned);
23469    }
23470
23471    fn body_at(state: &RunState) -> String {
23472        pr_message_raw(
23473            state,
23474            'A',
23475            None,
23476            crate::pr_outcome::FinalHead::At(FINAL),
23477            ChangeNote::NotAsked,
23478        )
23479        .body
23480    }
23481
23482    const SANDBOXED: &str = "Handled the PATH case.\nI could not commit because of the sandbox. HTTP tests could not run in the sandbox.";
23483
23484    #[test]
23485    fn rescued_commit_and_later_verification_override_the_fixers_limits() {
23486        let mut state = review_state(&["feat: x"]);
23487        state.reviews = vec![
23488            round_with_notes(1, Some(SANDBOXED)),
23489            passing_round(2, Some(FINAL)),
23490        ];
23491        ok_gate(&mut state, Some(FINAL));
23492        let body = body_at(&state);
23493        assert!(!body.contains("Handled the PATH case."), "{body}");
23494        assert!(!body.contains("could not commit"), "{body}");
23495        assert!(!body.contains("could not run"), "{body}");
23496        assert!(
23497            body.contains("The fix is committed on the branch"),
23498            "{body}"
23499        );
23500        assert!(!body.contains("sandbox"), "{body}");
23501        assert!(
23502            body.contains("Tests (`verify.e2e`): passed on the final commit"),
23503            "{body}"
23504        );
23505        assert!(
23506            body.contains("Gate (`verify.gate`): passed on the final commit"),
23507            "{body}"
23508        );
23509        // The raw report is untouched in the record.
23510        assert!(
23511            state.reviews[0]
23512                .fix
23513                .as_ref()
23514                .unwrap()
23515                .notes
23516                .contains("could not commit")
23517        );
23518    }
23519
23520    #[test]
23521    fn unresolved_commit_and_test_limits_stay_and_nothing_claims_success() {
23522        let mut state = review_state(&["feat: x"]);
23523        let mut r1 = round_with_notes(1, Some(SANDBOXED));
23524        r1.fix.as_mut().unwrap().committed = false;
23525        let mut r2 = passing_round(2, Some(FINAL));
23526        r2.e2e[0].code = Some(1);
23527        state.reviews = vec![r1, r2];
23528        let body = body_at(&state);
23529        assert!(!body.contains("could not commit"), "{body}");
23530        assert!(!body.contains("could not run"), "{body}");
23531        assert!(body.contains("This round produced no commit"), "{body}");
23532        assert!(body.contains("Tests (`verify.e2e`): FAILED"), "{body}");
23533        assert!(body.contains("Gate (`verify.gate`): not run"), "{body}");
23534        assert!(!body.contains("passed"), "{body}");
23535    }
23536
23537    #[test]
23538    fn verification_on_an_earlier_commit_does_not_supersede_test_limits() {
23539        let mut state = review_state(&["feat: x"]);
23540        state.reviews = vec![
23541            round_with_notes(1, Some(SANDBOXED)),
23542            passing_round(2, Some("0123456789abcdef")),
23543        ];
23544        ok_gate(&mut state, Some("0123456789abcdef"));
23545        let body = body_at(&state);
23546        assert!(!body.contains("HTTP tests could not run"), "{body}");
23547        // The commit claim is still settled by the structured record.
23548        assert!(!body.contains("could not commit"), "{body}");
23549        assert!(
23550            body.contains("passed on an earlier commit (`0123456`)"),
23551            "{body}"
23552        );
23553        assert!(!body.contains("passed on the final commit"), "{body}");
23554
23555        // A gate recorded before `gate_head` existed is "not recorded".
23556        ok_gate(&mut state, None);
23557        let body = body_at(&state);
23558        assert!(
23559            body.contains("passed on a commit that was not recorded"),
23560            "{body}"
23561        );
23562    }
23563
23564    #[test]
23565    fn pr_message_implementation_run_keeps_its_shape_and_marker() {
23566        let state = state_with_summary(
23567            "add retries to the client",
23568            "TITLE: feat: retries\n\nDid it.",
23569        );
23570        let m = pr_message_with(&state, 'A', Some(&facts(&[("x", "")], "s")));
23571        assert_eq!(m.title, "feat: retries");
23572        assert!(
23573            m.body.contains("<summary>Original task</summary>"),
23574            "{}",
23575            m.body
23576        );
23577        assert!(!m.body.contains("Commits under review"), "{}", m.body);
23578        assert!(
23579            m.body
23580                .ends_with(&format!("magi:run/{} magi:candidate-a\n", state.id)),
23581            "{}",
23582            m.body
23583        );
23584    }
23585
23586    #[test]
23587    fn pr_message_review_bounds_a_long_english_subject() {
23588        let long = format!("feat: {}", "word ".repeat(100));
23589        let m = pr_message(&review_state(&[&long]), 'A');
23590        assert!(m.title.starts_with("feat: word"), "{}", m.title);
23591        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
23592    }
23593
23594    #[test]
23595    fn pr_message_implementation_run_is_unchanged_by_review_support() {
23596        let state = state_with_summary("add retries\n\ndetails", "- did some things");
23597        let m = pr_message(&state, 'A');
23598        assert_eq!(m.title, "add retries");
23599        assert!(m.body.contains("<summary>Original task</summary>"));
23600        assert!(!m.body.contains("Commits under review"));
23601        assert_eq!(landing_subject_source(&state), state.instruction);
23602    }
23603
23604    #[test]
23605    fn review_run_squash_subject_is_the_change_not_the_prompt() {
23606        let state = review_state(&["feat: the change", "fix: typo"]);
23607        let source = landing_subject_source(&state);
23608        assert_eq!(land::merge_subject("", &source), "feat: the change");
23609        assert_eq!(
23610            land::merge_subject("magi: candidate A (uncommitted work)", &source),
23611            "feat: the change"
23612        );
23613        // An operator's rename still wins.
23614        assert_eq!(
23615            land::merge_subject("feat: renamed by hand", &source),
23616            "feat: renamed by hand"
23617        );
23618        let blank = review_state(&["日本語"]);
23619        assert!(
23620            land::merge_subject("", &landing_subject_source(&blank)).starts_with("chore: land")
23621        );
23622    }
23623
23624    #[test]
23625    fn review_run_drops_a_prompt_shaped_pr_title_at_landing() {
23626        let state = review_state(&["feat: the change"]);
23627        let source = landing_subject_source(&state);
23628        let old = "Review the work already on branch `magi/x/A`. There is no task statement";
23629        assert_eq!(
23630            land::merge_subject(landing_title(&state, old), &source),
23631            "feat: the change"
23632        );
23633        assert_eq!(landing_title(&state, "feat: renamed"), "feat: renamed");
23634        let task = state_with_summary("add retries", "");
23635        assert_eq!(landing_title(&task, old), old);
23636    }
23637
23638    #[test]
23639    fn pr_message_describes_the_change_not_the_task() {
23640        let state = state_with_summary(
23641            "今回やってほしいこと: results projector を直す",
23642            "TITLE: fix(web): batch the runs list reads\n- reads run.json once\n- risk: none",
23643        );
23644        let m = pr_message(&state, 'A');
23645        assert_eq!(m.title, "fix(web): batch the runs list reads");
23646        assert!(
23647            m.body.starts_with("## Summary\n\n- reads run.json once"),
23648            "{}",
23649            m.body
23650        );
23651        assert!(!m.body.contains("TITLE:"), "{}", m.body);
23652        let task_at = m.body.find("今回やってほしいこと").unwrap();
23653        let details_at = m.body.find("<details>").unwrap();
23654        assert!(
23655            details_at < task_at,
23656            "the task lives inside <details>: {}",
23657            m.body
23658        );
23659        assert!(m.body.contains(&format!("magi:run/{}", state.id)));
23660        assert!(m.body.contains("magi:candidate-a"));
23661    }
23662
23663    #[test]
23664    fn pr_message_falls_back_to_the_task_without_a_title_line() {
23665        let state = state_with_summary("\n\nadd retries\n\ndetails", "- did some things");
23666        let m = pr_message(&state, 'A');
23667        assert_eq!(m.title, "add retries");
23668        assert!(
23669            m.body.contains("## Summary\n\n- did some things"),
23670            "{}",
23671            m.body
23672        );
23673
23674        let none = RunState::new(
23675            PathBuf::from("/repo"),
23676            "main".to_owned(),
23677            "abc1234".to_owned(),
23678            "add retries".to_owned(),
23679            Config::default(),
23680        );
23681        let m = pr_message(&none, 'A');
23682        assert_eq!(m.title, "add retries");
23683        assert!(!m.body.contains("## Summary"), "{}", m.body);
23684    }
23685
23686    #[test]
23687    fn pr_message_refuses_the_candidate_commit_subject() {
23688        for bad in [
23689            "TITLE: magi: candidate A (uncommitted work)",
23690            "TITLE: chore: stuff (uncommitted work)",
23691            "TITLE:   ",
23692        ] {
23693            let state = state_with_summary("add retries", bad);
23694            assert_eq!(pr_message(&state, 'A').title, "add retries", "{bad}");
23695        }
23696    }
23697
23698    #[test]
23699    fn pr_message_bounds_a_very_long_task_and_title() {
23700        let long = format!("fix the thing 🎉 {}", "x".repeat(5000));
23701        let state = state_with_summary(&long, "- nothing");
23702        let m = pr_message(&state, 'A');
23703        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
23704        assert!(!m.title.contains('\n'));
23705
23706        let state = state_with_summary("task", &format!("TITLE: feat: {}", "y".repeat(5000)));
23707        let m = pr_message(&state, 'A');
23708        assert!(m.title.starts_with("feat: "));
23709        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
23710        assert_eq!(m.commit_message().lines().next(), Some(m.title.as_str()));
23711    }
23712
23713    fn long_title_of(instruction: &str) -> String {
23714        pr_message(&state_with_summary(instruction, "- nothing"), 'A').title
23715    }
23716
23717    #[test]
23718    fn pr_message_cuts_a_long_english_line_at_its_first_sentence() {
23719        let first = "Make the landing path keep a readable title for long tasks";
23720        let line = format!(
23721            "{first}. {}",
23722            "And then keep going with more words ".repeat(20)
23723        );
23724        let t = long_title_of(&line);
23725        assert_eq!(t, first);
23726        assert!(!t.starts_with("chore: land"));
23727    }
23728
23729    #[test]
23730    fn pr_message_cuts_a_sentenceless_long_line_at_a_word() {
23731        let line = "word ".repeat(200);
23732        let t = long_title_of(&line);
23733        assert!(t.ends_with("word..."), "{t}");
23734        assert!(t.is_ascii() && t.chars().count() <= PR_TITLE_MAX, "{t}");
23735    }
23736
23737    #[test]
23738    fn pr_message_long_non_english_or_letterless_line_is_neutral() {
23739        for line in ["日本語のタスク ".repeat(80), "1234 ".repeat(100)] {
23740            assert!(long_title_of(&line).starts_with("chore: land"), "{line}");
23741        }
23742    }
23743
23744    #[test]
23745    fn pr_message_keeps_a_japanese_title_when_github_language_is_japanese() {
23746        let mut state = state_with_summary("再試行を追加する", "- nothing");
23747        assert!(pr_message(&state, 'A').title.starts_with("chore: land"));
23748        state.config.graph.github_language = "ja".into();
23749        assert_eq!(pr_message(&state, 'A').title, "再試行を追加する");
23750    }
23751
23752    #[test]
23753    fn pr_message_title_limit_is_exact() {
23754        let at = "a".repeat(PR_TITLE_MAX);
23755        assert_eq!(long_title_of(&at), at);
23756        let over = long_title_of(&"a".repeat(PR_TITLE_MAX + 1));
23757        assert!(over.ends_with("..."), "{over}");
23758        assert_eq!(over.chars().count(), PR_TITLE_MAX);
23759    }
23760
23761    #[test]
23762    fn pr_message_judges_the_kept_text_not_what_follows_the_cut() {
23763        let line = format!("{} \u{2014} tail", "alpha beta ".repeat(40));
23764        let t = long_title_of(&line);
23765        assert!(t.ends_with("..."), "{t}");
23766        assert!(t.is_ascii(), "{t}");
23767    }
23768
23769    #[test]
23770    fn pr_message_sentence_cut_skips_abbreviations_and_decimals() {
23771        let line = format!(
23772            "Support several shells, e.g. bash and zsh, at version 1.5 or newer when it matters {}",
23773            "plus more filler words ".repeat(20)
23774        );
23775        let t = long_title_of(&line);
23776        assert!(t.contains("e.g. bash") && t.contains("1.5 or newer"), "{t}");
23777    }
23778
23779    #[test]
23780    fn pr_message_long_title_survives_a_blank_first_line_and_the_squash_subject() {
23781        let line = format!("\n\n# {}", "title words ".repeat(40));
23782        let state = state_with_summary(&line, "- nothing");
23783        let m = pr_message(&state, 'A');
23784        assert!(m.title.starts_with("title words"), "{}", m.title);
23785        assert_eq!(
23786            land::merge_subject(&m.title, &landing_subject_source(&state)),
23787            m.title
23788        );
23789        // An operator's rename wins untouched.
23790        assert_eq!(
23791            land::merge_subject("feat: renamed by hand", &landing_subject_source(&state)),
23792            "feat: renamed by hand"
23793        );
23794    }
23795
23796    #[tokio::test]
23797    async fn github_text_rewrite_is_bounded_and_falls_back() {
23798        crate::run::pin_test_home();
23799        for (reply, accepted) in [
23800            (
23801                "TITLE: fix: retries\nAdd retries for failed requests.",
23802                true,
23803            ),
23804            (
23805                "TITLE: fix: retries\n日本語の説明をもう一度書きます。",
23806                false,
23807            ),
23808            (
23809                "TITLE: fix: retries\nAdd retries for failed requests. Use token=secret",
23810                true,
23811            ),
23812            (
23813                "TITLE: fix: retries\nAdd retries for failed requests. Example: password=\"prefix\\\"secret tail\"",
23814                true,
23815            ),
23816            (
23817                "TITLE: fix: retries token=secret\nAdd retries for failed requests. Example: password=\"日本語の秘密secret\"",
23818                true,
23819            ),
23820            (
23821                "TITLE: fix: retries\n日本語の説明です。 token=secret",
23822                false,
23823            ),
23824            ("TITLE: fix: retries\n", false),
23825        ] {
23826            let dir = tempfile::tempdir().unwrap();
23827            let mut runner = runner_at(RunStatus::Gating);
23828            runner.state = state_with_summary(
23829                "add retries",
23830                "TITLE: fix: retries\n日本語の説明を書きます。",
23831            );
23832            runner.state.repo = dir.path().to_owned();
23833            runner.state.candidates[0].worktree = dir.path().to_owned();
23834            let mut author = spec("alpha");
23835            author.command = vec![
23836                "sh".into(),
23837                "-c".into(),
23838                "printf '%s' \"$REWRITE_REPLY\"".into(),
23839            ];
23840            author.env.insert("REWRITE_REPLY".into(), reply.into());
23841            runner.state.config.agents = vec![author];
23842            seed_public_summary(&mut runner);
23843            let winner = runner.state.candidates[0].clone();
23844            let first = runner
23845                .guarded_pr_message(&winner, None, true)
23846                .await
23847                .unwrap();
23848            let message = if accepted {
23849                first.expect("a passing rewrite never asks")
23850            } else {
23851                // Withheld: the run parks on a question and posts nothing yet.
23852                assert!(first.is_none());
23853                assert!(runner.state.parked);
23854                let store = ask::Questions::open();
23855                let asked: Vec<_> = store
23856                    .list()
23857                    .into_iter()
23858                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
23859                    .collect();
23860                assert_eq!(asked.len(), 1);
23861                assert!(!asked[0].detail.contains("secret"));
23862                let rewrite = runner.state.github_text.as_ref().unwrap().rewrite.as_ref();
23863                assert_eq!(rewrite.is_some(), !reply.ends_with('\n'));
23864                assert_eq!(
23865                    asked[0]
23866                        .choices
23867                        .contains(&crate::github_text::USE_REWRITE.to_owned()),
23868                    rewrite.is_some()
23869                );
23870                // Silence: the question lapses and the neutral text is used,
23871                // without a second rewrite call or a second question.
23872                store
23873                    .update(&asked[0].id, |q| {
23874                        q.abandon("test");
23875                        Ok(())
23876                    })
23877                    .unwrap();
23878                let again = runner
23879                    .guarded_pr_message(&winner, None, true)
23880                    .await
23881                    .unwrap()
23882                    .expect("an abandoned question falls back");
23883                let n = store
23884                    .list()
23885                    .into_iter()
23886                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
23887                    .count();
23888                assert_eq!(n, 1, "asked once per rejected text");
23889                again
23890            };
23891            assert!(crate::github_text::check(&message.title, &message.body).is_empty());
23892            assert!(!message.body.contains("secret"));
23893            assert!(!message.body.contains("prefix"));
23894            assert!(!message.title.contains("secret"));
23895            assert_eq!(
23896                message.body.contains("Add retries for failed requests."),
23897                accepted
23898            );
23899            assert_eq!(
23900                runner.state.seats["github-text-rewrite"].turns, 1,
23901                "only one rewrite invocation"
23902            );
23903            assert!(runner.state.events.iter().any(|e| e.node == "github-text"));
23904            if accepted {
23905                assert!(runner.state.github_text.is_none());
23906                assert!(!runner.state.parked);
23907                assert!(!message.body.contains(crate::github_text::NEUTRAL_BODY));
23908                assert!(message.body.contains("## Final verification"));
23909                assert!(message.body.contains("Evidence: final diff"));
23910                assert!(
23911                    message
23912                        .body
23913                        .contains(&format!("magi:run/{}", runner.state.id))
23914                );
23915            }
23916            if !accepted {
23917                assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
23918                assert!(
23919                    message
23920                        .body
23921                        .contains(&format!("magi:run/{}", runner.state.id))
23922                );
23923            }
23924        }
23925    }
23926
23927    fn scripted(id: &str, reply: &str) -> AgentSpec {
23928        let mut a = spec(id);
23929        a.command = vec![
23930            "sh".into(),
23931            "-c".into(),
23932            "printf '%s' \"$REWRITE_REPLY\"".into(),
23933        ];
23934        a.env.insert("REWRITE_REPLY".into(), reply.into());
23935        a
23936    }
23937
23938    const JA_SUMMARY: &str = "TITLE: fix: retries\n日本語の説明を書きます。";
23939    const EN_REWRITE: &str = "TITLE: fix: retries\nAdd retries in `src/net.rs` for 3 failed requests.\n\n<details>kept</details>";
23940
23941    /// Gate tests inject generated public output, not internal reports.
23942    fn seed_public_summary(runner: &mut Runner) {
23943        let repo = &runner.state.repo;
23944        let g = |args: &[&str]| {
23945            let out = std::process::Command::new("git")
23946                .args(args)
23947                .current_dir(repo)
23948                .quiet()
23949                .output()
23950                .unwrap();
23951            assert!(out.status.success(), "git {args:?}");
23952            String::from_utf8_lossy(&out.stdout).trim().to_owned()
23953        };
23954        g(&["init", "-q", "-b", "main"]);
23955        g(&[
23956            "-c",
23957            "user.name=Test",
23958            "-c",
23959            "user.email=test@example.invalid",
23960            "commit",
23961            "-q",
23962            "--allow-empty",
23963            "-m",
23964            "feat: fixture",
23965        ]);
23966        let head = g(&["rev-parse", "HEAD"]);
23967        g(&["update-ref", "refs/remotes/origin/main", &head]);
23968        let evidence = crate::pr_outcome::summary_evidence(
23969            &runner.state,
23970            crate::pr_outcome::FinalHead::At(&head),
23971        );
23972        let generated = &runner.state.candidates[0].summary;
23973        runner.state.change_summary = Some(crate::run::ChangeSummary {
23974            base: head.clone(),
23975            head,
23976            evidence: crate::pr_outcome::summary_fingerprint(&runner.state, &evidence),
23977            title: summary_title(generated).unwrap(),
23978            body: summary_without_title(generated),
23979        });
23980    }
23981
23982    fn rewrite_runner(dir: &Path, review_only: bool, agents: Vec<AgentSpec>) -> Runner {
23983        let mut runner = runner_at(RunStatus::Gating);
23984        runner.state = state_with_summary("add retries", JA_SUMMARY);
23985        if review_only {
23986            runner.state.candidates[0].agent = EXISTING_BRANCH.to_owned();
23987        }
23988        runner.state.repo = dir.to_owned();
23989        runner.state.candidates[0].worktree = dir.to_owned();
23990        runner.state.config.agents = agents;
23991        seed_public_summary(&mut runner);
23992        runner
23993    }
23994
23995    fn gate_questions(runner: &Runner) -> usize {
23996        ask::Questions::open()
23997            .list()
23998            .into_iter()
23999            .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
24000            .count()
24001    }
24002
24003    #[tokio::test]
24004    async fn review_only_description_is_rewritten_by_the_language_judge_role() {
24005        crate::run::pin_test_home();
24006        let dir = tempfile::tempdir().unwrap();
24007        let mut runner = rewrite_runner(
24008            dir.path(),
24009            true,
24010            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
24011        );
24012        runner.state.config.roles.language_judge =
24013            Some(crate::config::AgentChoice::Chain(vec!["beta".into()]));
24014        let winner = runner.state.candidates[0].clone();
24015        let msg = runner
24016            .guarded_pr_message(&winner, None, true)
24017            .await
24018            .unwrap()
24019            .expect("an English rewrite posts without asking");
24020        assert!(msg.body.contains("`src/net.rs` for 3 failed requests"));
24021        assert!(msg.body.contains("<details>kept</details>"));
24022        assert!(msg.body.contains(&format!("magi:run/{}", runner.state.id)));
24023        assert_eq!(gate_questions(&runner), 0);
24024        assert!(runner.state.github_text.is_none());
24025        assert!(!runner.state.seats.contains_key("impl-A"));
24026        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24027    }
24028
24029    #[tokio::test]
24030    async fn rewrite_without_an_implementer_session_uses_the_role_not_the_seat() {
24031        crate::run::pin_test_home();
24032        let dir = tempfile::tempdir().unwrap();
24033        let mut runner = rewrite_runner(
24034            dir.path(),
24035            false,
24036            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
24037        );
24038        runner.state.config.roles.language_judge =
24039            Some(crate::config::AgentChoice::One("beta".into()));
24040        runner.state.seats.insert(
24041            "impl-A".into(),
24042            SeatState::new("impl-A", "alpha", runner.state.seed),
24043        );
24044        let winner = runner.state.candidates[0].clone();
24045        let msg = runner
24046            .guarded_pr_message(&winner, None, true)
24047            .await
24048            .unwrap()
24049            .expect("rewritten");
24050        assert!(msg.body.contains("<details>kept</details>"));
24051        assert_eq!(runner.state.seats["impl-A"].turns, 0);
24052        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24053        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
24054    }
24055
24056    #[tokio::test]
24057    async fn rewrite_reuses_a_resumable_implementer_session() {
24058        crate::run::pin_test_home();
24059        let dir = tempfile::tempdir().unwrap();
24060        let mut runner = rewrite_runner(
24061            dir.path(),
24062            false,
24063            vec![scripted("alpha", EN_REWRITE), scripted("beta", "nope")],
24064        );
24065        runner.state.config.roles.language_judge =
24066            Some(crate::config::AgentChoice::One("beta".into()));
24067        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
24068        seat.turns = 1;
24069        runner.state.seats.insert("impl-A".into(), seat);
24070        let winner = runner.state.candidates[0].clone();
24071        runner
24072            .guarded_pr_message(&winner, None, true)
24073            .await
24074            .unwrap()
24075            .expect("rewritten");
24076        assert_eq!(runner.state.seats["impl-A"].turns, 2);
24077        assert!(!runner.state.seats.contains_key("github-text-rewrite"));
24078    }
24079
24080    #[tokio::test]
24081    async fn a_failing_resumed_implementer_falls_back_to_the_language_judge_role() {
24082        // Runs 7861 / 344a: the winning implementer (agy) had a resumable
24083        // session, was out of quota, and nothing else was asked.
24084        crate::run::pin_test_home();
24085        let dir = tempfile::tempdir().unwrap();
24086        let mut exhausted = spec("alpha");
24087        exhausted.command = vec!["false".into()];
24088        let mut runner = rewrite_runner(
24089            dir.path(),
24090            false,
24091            vec![exhausted, scripted("beta", EN_REWRITE)],
24092        );
24093        // The implementer's own agent is in the role too: it is not asked twice.
24094        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
24095            "alpha".into(),
24096            "beta".into(),
24097        ]));
24098        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
24099        seat.turns = 1;
24100        runner.state.seats.insert("impl-A".into(), seat);
24101        let winner = runner.state.candidates[0].clone();
24102        let msg = runner
24103            .guarded_pr_message(&winner, None, true)
24104            .await
24105            .unwrap()
24106            .expect("the role rewrites after the implementer fails");
24107        assert!(msg.body.contains("`src/net.rs`"));
24108        assert_eq!(
24109            runner.state.seats["impl-A"].turns, 2,
24110            "the implementer was tried once"
24111        );
24112        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
24113        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24114    }
24115
24116    #[tokio::test]
24117    async fn rewrite_chain_advances_past_a_failing_or_unparsable_agent() {
24118        crate::run::pin_test_home();
24119        let dir = tempfile::tempdir().unwrap();
24120        let mut broken = spec("bad");
24121        broken.command = vec!["false".into()];
24122        let mut runner = rewrite_runner(
24123            dir.path(),
24124            true,
24125            vec![
24126                broken,
24127                scripted("noformat", "Add retries."),
24128                scripted("good", EN_REWRITE),
24129            ],
24130        );
24131        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
24132            "bad".into(),
24133            "noformat".into(),
24134            "good".into(),
24135        ]));
24136        let winner = runner.state.candidates[0].clone();
24137        let msg = runner
24138            .guarded_pr_message(&winner, None, true)
24139            .await
24140            .unwrap()
24141            .expect("the third agent rewrites");
24142        assert!(msg.body.contains("`src/net.rs`"));
24143        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "good");
24144        assert!(runner.state.handovers.is_empty(), "no handover is recorded");
24145    }
24146
24147    #[tokio::test]
24148    async fn unsuccessful_review_only_rewrites_ask_the_owner_and_never_post_the_original() {
24149        crate::run::pin_test_home();
24150        // (agents, role): still Japanese; no TITLE; nothing resolvable.
24151        for (agents, role, saved) in [
24152            (
24153                vec![scripted("beta", "TITLE: fix: retries\n日本語の説明です。")],
24154                Some("beta"),
24155                true,
24156            ),
24157            (vec![scripted("beta", "Add retries.")], Some("beta"), false),
24158            (Vec::new(), None, false),
24159        ] {
24160            let dir = tempfile::tempdir().unwrap();
24161            let mut runner = rewrite_runner(dir.path(), true, agents);
24162            runner.state.config.roles.language_judge =
24163                role.map(|r| crate::config::AgentChoice::One(r.into()));
24164            let winner = runner.state.candidates[0].clone();
24165            let first = runner
24166                .guarded_pr_message(&winner, None, true)
24167                .await
24168                .unwrap();
24169            assert!(first.is_none(), "withheld text parks the run");
24170            assert!(runner.state.parked);
24171            assert_eq!(gate_questions(&runner), 1);
24172            let g = runner.state.github_text.as_ref().unwrap();
24173            assert_eq!(g.rewrite.is_some(), saved);
24174            assert!(g.choice.is_none() && !g.resolved, "nothing posts unasked");
24175        }
24176    }
24177
24178    #[tokio::test]
24179    async fn github_text_rejected_rewrite_survives_retry_and_posts_verbatim() {
24180        crate::run::pin_test_home();
24181        let dir = tempfile::tempdir().unwrap();
24182        let mut runner = runner_at(RunStatus::Gating);
24183        runner.state =
24184            state_with_summary("add retries", "TITLE: 日本語のタイトル\n日本語の説明です。");
24185        runner.state.repo = dir.path().to_owned();
24186        runner.state.candidates[0].worktree = dir.path().to_owned();
24187        let mut author = spec("alpha");
24188        author.command = vec![
24189            "sh".into(),
24190            "-c".into(),
24191            "printf '%s' \"$REWRITE_REPLY\"".into(),
24192        ];
24193        author.env.insert(
24194            "REWRITE_REPLY".into(),
24195            format!(
24196                "TITLE: fix: rewritten title\n{}\n日本語の説明です。",
24197                "English sentence. ".repeat(600)
24198            ),
24199        );
24200        runner.state.config.agents = vec![author];
24201        seed_public_summary(&mut runner);
24202        let winner = runner.state.candidates[0].clone();
24203        assert!(
24204            runner
24205                .guarded_pr_message(&winner, None, true)
24206                .await
24207                .unwrap()
24208                .is_none()
24209        );
24210        let record = runner.state.github_text.clone().unwrap();
24211        let rewrite = record.rewrite.clone().unwrap();
24212        assert_eq!(rewrite.failed, ["body-language"]);
24213        assert!(
24214            rewrite
24215                .body
24216                .ends_with(&format!("magi:run/{}", runner.state.id))
24217        );
24218        let store = ask::Questions::open();
24219        let q = store.get(record.question.as_ref().unwrap()).unwrap();
24220        assert!(
24221            q.choices
24222                .contains(&crate::github_text::USE_REWRITE.to_owned())
24223        );
24224        for label in [
24225            "ORIGINAL",
24226            "FALLBACK",
24227            "REWRITE",
24228            "Rules still failed: body-language",
24229            "truncated",
24230        ] {
24231            assert!(q.detail.contains(label), "{label}");
24232        }
24233        let artifact = std::fs::read_to_string(crate::run::artifact_path(
24234            &runner.state,
24235            &crate::github_text::artifact_name(&record.fingerprint),
24236        ))
24237        .unwrap();
24238        assert!(artifact.contains(&rewrite.title) && artifact.contains(&rewrite.body));
24239        // Restart from serialized state, then retry after a bad owner title.
24240        runner.state =
24241            serde_json::from_str(&serde_json::to_string(&runner.state).unwrap()).unwrap();
24242        store
24243            .update(&q.id, |q| {
24244                q.say("まだ日本語")?;
24245                q.answer(ask::Answer::Choice(crate::github_text::USE_MY_TEXT.into()))
24246            })
24247            .unwrap();
24248        assert!(
24249            runner
24250                .guarded_pr_message(&winner, None, true)
24251                .await
24252                .unwrap()
24253                .is_none()
24254        );
24255        let retry = runner.state.github_text.as_ref().unwrap();
24256        assert_eq!(retry.rewrite.as_ref(), Some(&rewrite));
24257        let q = store.get(retry.question.as_ref().unwrap()).unwrap();
24258        assert!(q.detail.contains("REWRITE") && q.detail.contains(&rewrite.title));
24259        assert!(
24260            q.posting_comparison
24261                .as_ref()
24262                .unwrap()
24263                .matches_detail(&q.detail)
24264        );
24265        store
24266            .update(&q.id, |q| {
24267                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
24268            })
24269            .unwrap();
24270        let message = runner
24271            .guarded_pr_message(&winner, None, true)
24272            .await
24273            .unwrap()
24274            .unwrap();
24275        assert_eq!(message.title, rewrite.title);
24276        assert_eq!(message.body, rewrite.body);
24277        assert_eq!(
24278            runner.state.github_text.as_ref().unwrap().choice,
24279            Some(GithubTextChoice::Rewrite)
24280        );
24281        let again = runner
24282            .guarded_pr_message(&winner, None, true)
24283            .await
24284            .unwrap()
24285            .unwrap();
24286        assert_eq!(again.title, message.title);
24287        assert_eq!(again.body, message.body);
24288        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24289        assert!(
24290            !runner
24291                .state
24292                .events
24293                .iter()
24294                .any(|e| e.message.contains(&rewrite.title)
24295                    || e.message.contains("English sentence."))
24296        );
24297    }
24298
24299    #[tokio::test]
24300    async fn historical_posting_reply_never_expires_into_fallback() {
24301        crate::run::pin_test_home();
24302        let dir = tempfile::tempdir().unwrap();
24303        let mut runner = runner_at(RunStatus::Gating);
24304        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
24305        runner.state.repo = dir.path().to_owned();
24306        runner.state.candidates[0].worktree = dir.path().to_owned();
24307        seed_public_summary(&mut runner);
24308        let winner = runner.state.candidates[0].clone();
24309        assert!(
24310            runner
24311                .guarded_pr_message(&winner, None, true)
24312                .await
24313                .unwrap()
24314                .is_none()
24315        );
24316        let id = runner
24317            .state
24318            .github_text
24319            .as_ref()
24320            .unwrap()
24321            .question
24322            .clone()
24323            .unwrap();
24324        let store = ask::Questions::open();
24325        let mut q = store.get(&id).unwrap();
24326        q.asked_at = "2020-01-01T00:00:00Z".parse().unwrap();
24327        q.answer(ask::Answer::Choice(
24328            crate::github_text::POST_ORIGINAL.into(),
24329        ))
24330        .unwrap();
24331        q.answer_delivered = true;
24332        store.put(&mut q).unwrap();
24333        let source = std::fs::read(store.path_of(&id)).unwrap();
24334        let migration = crate::run::home().join("notifications/task-chat-migration-v1");
24335        std::fs::create_dir_all(&migration).unwrap();
24336        std::fs::write(
24337            migration.join("state.json"),
24338            serde_json::to_vec(&serde_json::json!({
24339                "schema": 1, "sources": [id], "pending": [id]
24340            }))
24341            .unwrap(),
24342        )
24343        .unwrap();
24344        for _ in 0..2 {
24345            assert!(
24346                runner
24347                    .guarded_pr_message(&winner, None, true)
24348                    .await
24349                    .unwrap()
24350                    .is_none()
24351            );
24352            assert!(!runner.state.github_text.as_ref().unwrap().resolved);
24353            assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
24354        }
24355        let home = crate::run::home();
24356        crate::task_chat::sweep(
24357            &crate::queue::Queue::at(home.join("queue")),
24358            &crate::talk::Talks::at(home.join("talks")),
24359            &store,
24360            &home,
24361        );
24362        let outbox = crate::task_inquiry::Outbox::at(&home);
24363        outbox
24364            .update_decision(&id, |d| {
24365                d.accept(&format!("decision: {}", crate::github_text::POST_ORIGINAL))?;
24366                d.source_answer_at = q.answered_at;
24367                Ok(true)
24368            })
24369            .unwrap();
24370        outbox
24371            .settle(
24372                &id,
24373                "owner-chat",
24374                "Owner confirms no publication remains necessary",
24375                None,
24376            )
24377            .unwrap();
24378        assert!(
24379            runner
24380                .guarded_pr_message(&winner, None, true)
24381                .await
24382                .unwrap()
24383                .is_none()
24384        );
24385        assert!(!runner.state.github_text.as_ref().unwrap().resolved);
24386        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
24387    }
24388
24389    #[tokio::test]
24390    async fn github_text_rewrite_choice_without_saved_text_falls_back() {
24391        crate::run::pin_test_home();
24392        let dir = tempfile::tempdir().unwrap();
24393        let mut runner = runner_at(RunStatus::Gating);
24394        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
24395        runner.state.repo = dir.path().to_owned();
24396        runner.state.candidates[0].worktree = dir.path().to_owned();
24397        seed_public_summary(&mut runner);
24398        let winner = runner.state.candidates[0].clone();
24399        assert!(
24400            runner
24401                .guarded_pr_message(&winner, None, true)
24402                .await
24403                .unwrap()
24404                .is_none()
24405        );
24406        let record = runner.state.github_text.as_ref().unwrap();
24407        assert!(record.rewrite.is_none());
24408        // Records written before the additive field deserialize with no rewrite.
24409        let mut old = serde_json::to_value(record).unwrap();
24410        old.as_object_mut().unwrap().remove("rewrite");
24411        let old: crate::run::GithubTextAsk = serde_json::from_value(old).unwrap();
24412        assert!(old.rewrite.is_none());
24413        let id = record.question.clone().unwrap();
24414        ask::Questions::open()
24415            .update(&id, |q| {
24416                q.choices.push(crate::github_text::USE_REWRITE.into());
24417                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
24418            })
24419            .unwrap();
24420        let message = runner
24421            .guarded_pr_message(&winner, None, true)
24422            .await
24423            .unwrap()
24424            .unwrap();
24425        assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
24426        assert_eq!(
24427            runner.state.github_text.as_ref().unwrap().choice,
24428            Some(GithubTextChoice::Fallback)
24429        );
24430    }
24431
24432    #[tokio::test]
24433    async fn withheld_title_takes_the_owner_replacement_and_rechecks_it() {
24434        crate::run::pin_test_home();
24435        let dir = tempfile::tempdir().unwrap();
24436        let mut runner = runner_at(RunStatus::Gating);
24437        runner.state = state_with_summary("add retries", "TITLE: 日本語のタイトル\nAdd retries.");
24438        runner.state.repo = dir.path().to_owned();
24439        runner.state.candidates[0].worktree = dir.path().to_owned();
24440        seed_public_summary(&mut runner);
24441        let winner = runner.state.candidates[0].clone();
24442        assert!(
24443            runner
24444                .guarded_pr_message(&winner, None, true)
24445                .await
24446                .unwrap()
24447                .is_none()
24448        );
24449        let store = ask::Questions::open();
24450        let find = |run: &str| {
24451            store
24452                .list()
24453                .into_iter()
24454                .find(|q| q.run == run && q.node == crate::github_text::ASK_NODE && q.status.open())
24455                .unwrap()
24456        };
24457        let run = runner.state.id.clone();
24458        let q = find(&run);
24459        let fp = runner
24460            .state
24461            .github_text
24462            .as_ref()
24463            .unwrap()
24464            .fingerprint
24465            .clone();
24466        let name = crate::github_text::artifact_name(&fp);
24467        let path = crate::run::artifact_path(&runner.state, &name);
24468        assert!(q.detail.contains(&path.display().to_string()));
24469        assert!(q.detail.contains("title-language: title"));
24470        let saved = std::fs::read_to_string(&path).expect("artifact written");
24471        assert!(saved.contains("日本語のタイトル"));
24472        assert!(q.cwd.is_none());
24473        assert_eq!(q.choices, ["use fallback", "post original", "use my text"]);
24474        // A bad replacement is refused and asked about once more.
24475        let say = |id: &str, text: &str, choice: &str| {
24476            store
24477                .update(id, |q| {
24478                    q.thread.push(ask::Turn {
24479                        who: ask::Who::Operator,
24480                        body: text.to_owned(),
24481                        at: jiff::Timestamp::now(),
24482                        note: None,
24483                    });
24484                    q.answer(ask::Answer::Choice(choice.to_owned()))
24485                })
24486                .unwrap();
24487        };
24488        say(&q.id, "まだ日本語", "use my text");
24489        assert!(
24490            runner
24491                .guarded_pr_message(&winner, None, true)
24492                .await
24493                .unwrap()
24494                .is_none()
24495        );
24496        let second = find(&run);
24497        assert_ne!(second.id, q.id);
24498        assert!(second.detail.contains("did not pass"));
24499        // The retry still compares the original text; the rejected
24500        // replacement is named by category only.
24501        assert!(second.detail.contains("日本語のタイトル"));
24502        assert!(!second.detail.contains("まだ日本語"));
24503        assert!(second.detail.contains(&path.display().to_string()));
24504        say(&second.id, "fix: retry failed requests", "use my text");
24505        let message = runner
24506            .guarded_pr_message(&winner, None, true)
24507            .await
24508            .unwrap()
24509            .expect("a vetted replacement is posted");
24510        assert_eq!(message.title, "fix: retry failed requests");
24511        assert_eq!(
24512            runner
24513                .state
24514                .github_text
24515                .as_ref()
24516                .unwrap()
24517                .chosen_title
24518                .as_deref(),
24519            Some("fix: retry failed requests")
24520        );
24521        assert!(runner.state.github_text.as_ref().unwrap().resolved);
24522        // Resumed again: the saved decision is applied, nothing is re-asked.
24523        let again = runner
24524            .guarded_pr_message(&winner, None, true)
24525            .await
24526            .unwrap()
24527            .unwrap();
24528        assert_eq!(again.title, message.title);
24529        assert_eq!(
24530            store
24531                .list()
24532                .into_iter()
24533                .filter(|q| q.run == run && q.node == crate::github_text::ASK_NODE)
24534                .count(),
24535            2
24536        );
24537    }
24538
24539    #[test]
24540    fn pr_message_magi_text_is_english_and_the_task_is_verbatim() {
24541        // What magi itself writes stays English under any configured language,
24542        // so a future localisation of these headings fails here. (The agents'
24543        // own text is also checked by the posting gate.)
24544        let mut state = state_with_summary(
24545            "add retries",
24546            "TITLE: fix(web): batch reads\n- reads run.json once",
24547        );
24548        state.config.graph.language = "ja".to_owned();
24549        let m = pr_message(&state, 'A');
24550        assert!(crate::github_text::check(&m.title, &m.body).is_empty());
24551        assert!(m.title.is_ascii() && m.body.is_ascii(), "{}", m.body);
24552
24553        // The task is the operator's own text: it goes in untouched, and the
24554        // fallback title (no summary) may be in its language too.
24555        let task = "今回やってほしいこと: results projector を直す";
24556        let mut state = state_with_summary(task, "- no title line");
24557        state.config.graph.language = "ja".to_owned();
24558        let m = pr_message(&state, 'A');
24559        assert_eq!(
24560            m.title,
24561            format!("chore: land candidate A of run {}", state.id)
24562        );
24563        assert!(
24564            m.body.contains(&format!(
24565                "<summary>Original task</summary>\n\n{task}\n\n</details>"
24566            )),
24567            "{}",
24568            m.body
24569        );
24570    }
24571
24572    #[test]
24573    fn pr_message_scrubs_home_paths_and_addresses() {
24574        let state = state_with_summary(
24575            "fix it in /Users/someone/src/x",
24576            "TITLE: fix(x): y\n- edited /home/someone/repo/src/a.rs on 10.1.2.3",
24577        );
24578        let m = pr_message(&state, 'A');
24579        for leak in ["/Users/someone", "/home/someone", "10.1.2.3"] {
24580            assert!(!m.body.contains(leak), "{}", m.body);
24581        }
24582        assert!(m.body.contains("~/repo/src/a.rs"), "{}", m.body);
24583    }
24584
24585    #[test]
24586    fn pr_message_survives_a_task_that_closes_details() {
24587        let state = state_with_summary("a </details> b", "TITLE: fix: x");
24588        let m = pr_message(&state, 'A');
24589        assert_eq!(m.body.matches("</details>").count(), 1, "{}", m.body);
24590    }
24591
24592    #[test]
24593    fn manual_squash_subject_cannot_break_out_of_its_quotes() {
24594        let cmd = manual_merge_command(
24595            MergeStyle::Squash,
24596            Path::new("/repo"),
24597            "b",
24598            "fix: \"quoted\" $(x) `y`\n\nbody",
24599        );
24600        assert!(cmd.ends_with("commit -m \"fix: quoted (x) y\""), "{cmd}");
24601    }
24602
24603    #[test]
24604    fn manual_merge_command_matches_the_configured_style() {
24605        let repo = Path::new("/repo");
24606        let message = "Merge magi run 0832 (candidate A)\n\nadd retries";
24607
24608        let merge = manual_merge_command(MergeStyle::Merge, repo, "magi/0832/A", message);
24609        assert_eq!(merge, "git -C /repo merge --no-ff magi/0832/A");
24610
24611        let squash = manual_merge_command(MergeStyle::Squash, repo, "magi/0832/A", message);
24612        assert_eq!(
24613            squash,
24614            "git -C /repo merge --squash magi/0832/A && git -C /repo commit -m \
24615             \"Merge magi run 0832 (candidate A)\""
24616        );
24617
24618        let rebase = manual_merge_command(MergeStyle::Rebase, repo, "magi/0832/A", message);
24619        assert_eq!(rebase, "git -C /repo merge --ff-only magi/0832/A");
24620    }
24621
24622    #[test]
24623    fn a_nudge_gets_a_quarter_of_the_budget() {
24624        // The judge and implement budgets magi ships with.
24625        assert_eq!(retry_budget(secs(1200), true), secs(300));
24626        assert_eq!(retry_budget(secs(3600), true), secs(900));
24627    }
24628
24629    #[test]
24630    fn a_resent_prompt_keeps_the_whole_budget() {
24631        // The seat kept no context, so the retry is the original job again and
24632        // shortening it would only guarantee a second failure.
24633        assert_eq!(retry_budget(secs(1200), false), secs(1200));
24634        assert_eq!(retry_budget(secs(60), false), secs(60));
24635    }
24636
24637    #[test]
24638    fn the_floor_never_exceeds_the_original_budget() {
24639        // A short configured timeout must not be *raised* by the floor: the
24640        // operator asked for a bound, and a retry may not outlast the attempt
24641        // it is retrying.
24642        assert_eq!(retry_budget(secs(60), true), secs(60));
24643        assert_eq!(retry_budget(secs(480), true), secs(120));
24644        assert_eq!(retry_budget(secs(0), true), secs(0));
24645    }
24646
24647    fn evidence(exit_code: Option<i32>) -> agent::CommandEvidence {
24648        agent::CommandEvidence {
24649            id: "item1".to_owned(),
24650            description: "cargo test".to_owned(),
24651            exit_code,
24652            result_summary: String::new(),
24653            source: "codex".to_owned(),
24654        }
24655    }
24656
24657    #[test]
24658    fn a_reply_with_no_commands_at_all_is_not_unconfirmed() {
24659        // No evidence is not the same fact as unconfirmed evidence: a
24660        // backend with no adapter, or a reply that ran no commands at all,
24661        // must not be misread as carrying a dangling job.
24662        assert!(!has_unconfirmed_command(&[]));
24663    }
24664
24665    #[test]
24666    fn a_command_with_a_real_exit_code_is_confirmed_whatever_its_value() {
24667        // Deliberately not a check on the exit code's *value*: a fixer
24668        // legitimately runs something that fails mid-iteration before it
24669        // succeeds, and that must never by itself reopen a valid report.
24670        assert!(!has_unconfirmed_command(&[evidence(Some(0))]));
24671        assert!(!has_unconfirmed_command(&[evidence(Some(1))]));
24672        assert!(!has_unconfirmed_command(&[
24673            evidence(Some(0)),
24674            evidence(Some(101))
24675        ]));
24676    }
24677
24678    #[test]
24679    fn one_command_with_no_readable_exit_code_is_enough_to_flag_the_reply() {
24680        assert!(has_unconfirmed_command(&[
24681            evidence(Some(0)),
24682            evidence(None)
24683        ]));
24684    }
24685
24686    #[test]
24687    fn a_clean_usable_reply_with_the_marker_is_a_verified_claim() {
24688        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
24689        assert_eq!(
24690            verified_noop_claim(true, &[], text).as_deref(),
24691            Some("already fixed by b32cfc4, on main.")
24692        );
24693    }
24694
24695    #[test]
24696    fn an_unusable_reply_never_earns_the_benefit_of_the_doubt() {
24697        // A timeout or a bad exit code reads as the ordinary loss it is,
24698        // whatever the reply's own prose claims.
24699        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
24700        assert!(verified_noop_claim(false, &[], text).is_none());
24701    }
24702
24703    #[test]
24704    fn an_unconfirmed_command_disqualifies_the_claim_even_on_a_usable_reply() {
24705        let text = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
24706        assert!(verified_noop_claim(true, &[evidence(None)], text).is_none());
24707        // A confirmed command alongside the marker is fine.
24708        assert!(verified_noop_claim(true, &[evidence(Some(0))], text).is_some());
24709    }
24710
24711    #[test]
24712    fn an_ordinary_reply_with_no_marker_is_never_a_claim() {
24713        assert!(verified_noop_claim(true, &[], "- did the thing\n- tested it").is_none());
24714    }
24715
24716    /// Sets `runner.state.candidates` to one candidate per `(empty, verified)`
24717    /// pair, in order, labelled A, B, C, ...
24718    fn set_candidates(runner: &mut Runner, shape: &[(bool, Option<&str>)]) {
24719        runner.state.candidates = shape
24720            .iter()
24721            .enumerate()
24722            .map(|(i, &(empty, verified))| Candidate {
24723                index: i,
24724                label: (b'A' + i as u8) as char,
24725                agent: "sonnet".to_owned(),
24726                branch: format!("magi/x/{}", (b'A' + i as u8) as char),
24727                worktree: PathBuf::from(format!("/wt/{i}")),
24728                summary: String::new(),
24729                stat: String::new(),
24730                files: 0,
24731                commits: 0,
24732                empty,
24733                failed: None,
24734                verified_noop: verified.map(str::to_owned),
24735                duration_ms: 0,
24736                folded: false,
24737            })
24738            .collect();
24739    }
24740
24741    #[test]
24742    fn after_implement_reads_all_candidates_verified_as_a_noop_not_a_failure() {
24743        ask_test_home();
24744        let mut runner = runner_at(RunStatus::Implementing);
24745        set_candidates(
24746            &mut runner,
24747            &[
24748                (true, Some("already on main at b32cfc4")),
24749                (true, Some("same fix, see the existing test")),
24750            ],
24751        );
24752
24753        runner
24754            .after_implement()
24755            .expect("a verified no-op is not an error");
24756
24757        assert_eq!(runner.state.status, RunStatus::VerifiedNoop);
24758    }
24759
24760    #[test]
24761    fn after_implement_does_not_accept_one_candidates_claim_next_to_an_ordinary_loss() {
24762        ask_test_home();
24763        let mut runner = runner_at(RunStatus::Implementing);
24764        // Candidate A declares a verified no-op; candidate B simply wrote
24765        // nothing and said nothing about why. One candidate's claim is not
24766        // the whole run's agreement.
24767        set_candidates(
24768            &mut runner,
24769            &[(true, Some("already on main at b32cfc4")), (true, None)],
24770        );
24771
24772        let err = runner
24773            .after_implement()
24774            .expect_err("an unverified empty candidate must still fail the run");
24775
24776        assert!(
24777            err.to_string().contains("no candidate produced a change"),
24778            "{err}"
24779        );
24780        assert_eq!(runner.state.status, RunStatus::Failed);
24781    }
24782
24783    #[test]
24784    fn after_implement_still_fails_an_ordinary_all_empty_run() {
24785        ask_test_home();
24786        let mut runner = runner_at(RunStatus::Implementing);
24787        set_candidates(&mut runner, &[(true, None), (true, None)]);
24788
24789        let err = runner
24790            .after_implement()
24791            .expect_err("no candidate declared anything; this is an ordinary failure");
24792
24793        assert!(
24794            err.to_string().contains("no candidate produced a change"),
24795            "{err}"
24796        );
24797        assert_eq!(runner.state.status, RunStatus::Failed);
24798    }
24799}
24800
24801/// A graft rollback whose restore could not be confirmed (see
24802/// [`Runner::graft`]).
24803#[derive(Debug)]
24804struct GraftRestoreFailed(String);
24805
24806impl std::fmt::Display for GraftRestoreFailed {
24807    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24808        write!(
24809            f,
24810            "could not restore the winner to its pre-graft commit: {}",
24811            self.0
24812        )
24813    }
24814}
24815
24816impl std::error::Error for GraftRestoreFailed {}
24817
24818/// The pre-spawn waits (shared build cache, parallelism slot) are infrastructure,
24819/// not the agent: they never draw on an agent's own timeout, and running out of
24820/// them never reads as an agent failure.
24821#[cfg(test)]
24822mod resource_wait_tests {
24823    use super::*;
24824    use std::collections::BTreeMap;
24825
24826    fn sh(id: &str, script: &str) -> AgentSpec {
24827        AgentSpec {
24828            id: id.to_owned(),
24829            kind: crate::config::AgentKind::Command,
24830            model: None,
24831            command: vec!["sh".to_owned(), "-c".to_owned(), script.to_owned()],
24832            extra_args: Vec::new(),
24833            env: BTreeMap::new(),
24834            prompt_delivery: None,
24835            max_turn_secs: None,
24836        }
24837    }
24838
24839    fn job(spec: AgentSpec, dir: &Path, timeout: Duration) -> SeatJob {
24840        SeatJob {
24841            seat: SeatState::new("impl-A", &spec.id, 1),
24842            spec,
24843            cwd: dir.to_path_buf(),
24844            prompt: "do it".to_owned(),
24845            timeout,
24846            allow_write: true,
24847            sessions: false,
24848            artifacts: dir.join("art"),
24849            stem: "impl-A".to_owned(),
24850            handover: None,
24851        }
24852    }
24853
24854    fn state(resource_wait_secs: u64) -> RunState {
24855        let mut config = Config::default();
24856        config.graph.timeout_resource_wait = resource_wait_secs;
24857        RunState::new(
24858            PathBuf::from("/repo"),
24859            "main".to_owned(),
24860            "abc1234".to_owned(),
24861            "task".to_owned(),
24862            config,
24863        )
24864    }
24865
24866    fn hold(cache: &Path) -> crate::cache::Guard {
24867        let owner = crate::cache::Owner::here("other-run", "e2e", "e2e", cache, "deadbeef");
24868        match crate::cache::try_acquire(&crate::run::home(), cache, &owner).expect("io") {
24869            crate::cache::AcquireOutcome::Acquired(g) => g,
24870            crate::cache::AcquireOutcome::Busy(b) => panic!("lease was not free: {b:?}"),
24871        }
24872    }
24873
24874    async fn run(
24875        jobs: Vec<SeatJob>,
24876        sem: Arc<Semaphore>,
24877        cache: Option<&Path>,
24878        st: &mut RunState,
24879    ) -> Vec<(usize, SeatState, AgentOutcome)> {
24880        let prompts = Prompts::default();
24881        let ctx = WaveCtx {
24882            run: "r",
24883            node: "implement",
24884            prompts: &prompts,
24885            cache,
24886            round: None,
24887            carry_seats: false,
24888            pauses: None,
24889        };
24890        wave(jobs, sem, &ctx, st, 0).await
24891    }
24892
24893    #[tokio::test]
24894    async fn isolated_editing_seat_wait_releases_only_after_its_own_target_is_free() {
24895        crate::run::pin_test_home();
24896        let home = crate::run::home();
24897        let tmp = tempfile::tempdir().unwrap();
24898        let repo = tmp.path().join("repo");
24899        let checkout = tmp.path().join("checkout");
24900        std::fs::create_dir(&repo).unwrap();
24901        git::git(&repo, &["init"]).await.unwrap();
24902        git::git(
24903            &repo,
24904            &[
24905                "-c",
24906                "user.name=Fixture",
24907                "-c",
24908                "user.email=fixture@example.invalid",
24909                "commit",
24910                "--allow-empty",
24911                "-m",
24912                "initial",
24913            ],
24914        )
24915        .await
24916        .unwrap();
24917        git::worktree_add_detached(&repo, &checkout, "HEAD")
24918            .await
24919            .unwrap();
24920        let target = crate::build_target::resolve(&home, &checkout).unwrap();
24921        let target_lease = hold(&target);
24922        let shared = tmp.path().join("unrelated");
24923        let _shared_lease = hold(&shared);
24924        let mut st = state(0);
24925        st.repo = repo.clone();
24926        st.config.verify.build_cache = crate::config::BuildCache::Isolated;
24927        st.config.verify.e2e = vec![format!(
24928            "CARGO_TARGET_DIR='{}' cargo test",
24929            git::path_arg(&shared)
24930        )];
24931        let config = tmp.path().join("config.toml");
24932        std::fs::write(&config, toml::to_string(&st.config).unwrap()).unwrap();
24933        let prompts = Prompts::default();
24934        let run_id = st.id.clone();
24935        let ctx = WaveCtx {
24936            run: &run_id,
24937            node: "implement",
24938            prompts: &prompts,
24939            cache: None,
24940            round: None,
24941            carry_seats: false,
24942            pauses: None,
24943        };
24944        let writer = job(sh("writer", "exit 99"), &checkout, Duration::from_secs(30));
24945        let results = wave(vec![writer], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0).await;
24946        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
24947        assert_eq!(results[0].1.turns, 0);
24948        let saved = RunState::load_under(&run_id, &home).unwrap();
24949        let block = saved.resource_block.unwrap();
24950        assert!(matches!(
24951            block.cause,
24952            crate::run::ResourceBlockCause::IsolatedCacheTimeout { target: ref actual, .. }
24953                if actual == &target
24954        ));
24955        let queue = crate::queue::Queue::at(tmp.path().join("queue"));
24956        let mut task = crate::queue::Task::new(
24957            "build".into(),
24958            "build".into(),
24959            repo,
24960            crate::queue::Source::Human,
24961        );
24962        task.runs.push(run_id);
24963        task.hold_machine(Some(format!(
24964            "{}{}",
24965            crate::cache::RESOURCE_HOLD,
24966            block.description()
24967        )));
24968        queue.put(&mut task).unwrap();
24969        let questions = crate::ask::Questions::at(tmp.path().join("questions"));
24970        let triage =
24971            || crate::triage::run_once(&queue, &questions, Some(&config), Timestamp::now());
24972        let pending = triage();
24973        assert!(pending.resumed.is_empty() && pending.asked.is_empty());
24974        assert_eq!(
24975            queue.get(&task.id).unwrap().status,
24976            crate::queue::TaskStatus::Held
24977        );
24978        drop(target_lease);
24979        assert_eq!(triage().resumed, vec![task.id.clone()]);
24980        assert_eq!(
24981            queue.get(&task.id).unwrap().status,
24982            crate::queue::TaskStatus::Queued
24983        );
24984        assert!(crate::cache::in_use(&home, &shared));
24985    }
24986
24987    #[tokio::test]
24988    async fn verification_cache_wait_preserves_the_command_budget() {
24989        crate::run::pin_test_home();
24990        let tmp = tempfile::tempdir().unwrap();
24991        let cache = tmp.path().join("target");
24992        let guard = hold(&cache);
24993        let release = tokio::spawn(async move {
24994            tokio::time::sleep(Duration::from_millis(100)).await;
24995            guard.release();
24996        });
24997        let mut st = state(10);
24998        let budget = Duration::from_millis(50);
24999        let wait = repository_wait(&st, None);
25000        let (outcomes, _) = with_cache_lease(
25001            &mut st,
25002            Some(&cache),
25003            "gate",
25004            "gate",
25005            tmp.path(),
25006            "abc1234",
25007            budget,
25008            "test gate",
25009            &wait,
25010            |_, available| async move {
25011                assert_eq!(
25012                    available, budget,
25013                    "contention must not shorten verification"
25014                );
25015                (Vec::new(), false, Vec::new())
25016            },
25017        )
25018        .await
25019        .unwrap();
25020        release.await.unwrap();
25021        assert!(outcomes.is_empty(), "{outcomes:?}");
25022        assert!(
25023            st.events
25024                .iter()
25025                .any(|event| event.message.contains("waiting for"))
25026        );
25027        assert!(st.resource_wait.is_none());
25028        // The verification body no longer owns the lease after returning.
25029        hold(&cache).release();
25030    }
25031
25032    #[tokio::test]
25033    async fn verification_cache_wait_expires_without_starting_commands() {
25034        crate::run::pin_test_home();
25035        let tmp = tempfile::tempdir().unwrap();
25036        let cache = tmp.path().join("target");
25037        let _held = hold(&cache);
25038        let mut st = state(0);
25039        let wait = repository_wait(&st, None);
25040        let (outcomes, _) = with_cache_lease(
25041            &mut st,
25042            Some(&cache),
25043            "gate",
25044            "gate",
25045            tmp.path(),
25046            "abc1234",
25047            Duration::from_secs(60),
25048            "test gate",
25049            &wait,
25050            |_, _| async { panic!("commands must not start without the cache lease") },
25051        )
25052        .await
25053        .unwrap();
25054        assert_eq!(outcomes.len(), 1);
25055        assert!(outcomes[0].resource_blocked);
25056        assert!(st.resource_wait.is_none());
25057        assert!(matches!(
25058            st.resource_block.unwrap().cause,
25059            crate::run::ResourceBlockCause::Timeout { limit_secs: 0, .. }
25060        ));
25061    }
25062
25063    #[tokio::test]
25064    async fn verification_resource_error_does_not_claim_an_elapsed_timeout() {
25065        crate::run::pin_test_home();
25066        let tmp = tempfile::tempdir().unwrap();
25067        std::fs::write(tmp.path().join("Cargo.toml"), "[invalid").unwrap();
25068        let cache = tmp.path().join("cache");
25069        let mut state = state(21600);
25070        let wait = repository_wait(&state, None);
25071        let (outcomes, _) = with_cache_lease(
25072            &mut state,
25073            Some(&cache),
25074            "gate",
25075            "gate",
25076            tmp.path(),
25077            "head",
25078            Duration::from_secs(60),
25079            "gate",
25080            &wait,
25081            |_, _| async { panic!("freshness failure must not start verification") },
25082        )
25083        .await
25084        .unwrap();
25085        assert_eq!(outcomes.len(), 1);
25086        assert!(outcomes[0].resource_blocked);
25087        let block = state.resource_block.unwrap();
25088        assert_eq!(block.cause, crate::run::ResourceBlockCause::Other);
25089        assert!(!block.description().contains("timed out"));
25090    }
25091
25092    #[tokio::test]
25093    async fn cancelled_cache_wait_preserves_the_park_cause_without_starting_an_agent() {
25094        crate::run::pin_test_home();
25095        let tmp = tempfile::tempdir().unwrap();
25096        let cache = tmp.path().join("cache");
25097        let _held = hold(&cache);
25098        let mut state = state(21600);
25099        let pause = Pause::new();
25100        let interrupt = Pause::new();
25101        let cause = ParkCause::Operator;
25102        pause.park_for(cause.clone());
25103        let prompts = Prompts::default();
25104        let ctx = WaveCtx {
25105            run: "test",
25106            node: "fix",
25107            prompts: &prompts,
25108            cache: Some(&cache),
25109            round: None,
25110            carry_seats: false,
25111            pauses: Some((&pause, &interrupt)),
25112        };
25113        let result = wave(
25114            vec![job(
25115                sh("writer", "exit 99"),
25116                tmp.path(),
25117                Duration::from_secs(1),
25118            )],
25119            Arc::new(Semaphore::new(1)),
25120            &ctx,
25121            &mut state,
25122            0,
25123        )
25124        .await;
25125        assert!(matches!(result[0].2, AgentOutcome::ResourceBlocked(_)));
25126        assert_eq!(result[0].1.turns, 0);
25127        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
25128        assert_eq!(
25129            state.resource_block.unwrap().cause,
25130            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
25131        );
25132        assert!(state.active.is_empty());
25133    }
25134
25135    #[tokio::test]
25136    async fn a_cache_wait_longer_than_the_agent_budget_leaves_the_budget_whole() {
25137        crate::run::pin_test_home();
25138        let tmp = tempfile::tempdir().unwrap();
25139        let cache = tmp.path().join("target-a");
25140        let guard = hold(&cache);
25141        // Held for longer than the agent's whole 1s budget.
25142        tokio::spawn(async move {
25143            tokio::time::sleep(Duration::from_millis(1500)).await;
25144            guard.release();
25145        });
25146        let mut st = state(60);
25147        let results = run(
25148            vec![job(
25149                sh("alpha", "echo ok"),
25150                tmp.path(),
25151                Duration::from_secs(1),
25152            )],
25153            Arc::new(Semaphore::new(1)),
25154            Some(&cache),
25155            &mut st,
25156        )
25157        .await;
25158        assert!(
25159            matches!(results[0].2, AgentOutcome::Ok(_)),
25160            "the wait must not be charged to the agent"
25161        );
25162        assert!(st.resource_block.is_none());
25163        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
25164        assert!(st.resource_wait.is_none() && st.active.is_empty());
25165    }
25166
25167    #[tokio::test]
25168    #[cfg(unix)]
25169    async fn repository_wait_in_a_wave_is_a_bounded_cancellable_resource_block() {
25170        use std::os::fd::AsRawFd as _;
25171        crate::run::pin_test_home();
25172        let tmp = tempfile::tempdir().unwrap();
25173        crate::git::git(tmp.path(), &["init"]).await.unwrap();
25174        let common = tmp.path().join(".git");
25175        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
25176        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
25177        assert_eq!(
25178            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
25179            0
25180        );
25181        let mut st = state(1);
25182        st.config.coordination = crate::config::test_coordination();
25183        let mut reader = job(
25184            sh("reader", "echo must-not-run"),
25185            tmp.path(),
25186            Duration::from_secs(30),
25187        );
25188        reader.allow_write = false;
25189        let results = run(
25190            vec![reader.clone()],
25191            Arc::new(Semaphore::new(1)),
25192            None,
25193            &mut st,
25194        )
25195        .await;
25196        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
25197        assert_eq!(results[0].1.turns, 0);
25198        assert!(FailClass::of(&results[0].2).is_none());
25199        assert_eq!(
25200            st.resource_block.as_ref().unwrap().kind,
25201            "repository coordination"
25202        );
25203        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
25204        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
25205        drop(external);
25206        let editor = crate::repo_lock::SeatLease::for_checkout(
25207            tmp.path(),
25208            true,
25209            crate::config::test_coordination().as_ref(),
25210        )
25211        .await
25212        .unwrap();
25213        let pause = Pause::new();
25214        let interrupt = Pause::new();
25215        let prompts = Prompts::default();
25216        let ctx = WaveCtx {
25217            run: "r",
25218            node: "review",
25219            prompts: &prompts,
25220            cache: None,
25221            round: None,
25222            carry_seats: false,
25223            pauses: Some((&pause, &interrupt)),
25224        };
25225        let (results, ()) = tokio::join!(
25226            wave(vec![reader], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0),
25227            async {
25228                tokio::time::sleep(Duration::from_millis(50)).await;
25229                pause.park();
25230            }
25231        );
25232        assert!(
25233            matches!(&results[0].2, AgentOutcome::ResourceBlocked(why) if why.contains("parking"))
25234        );
25235        assert_eq!(results[0].1.turns, 0);
25236        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
25237        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
25238        drop(editor);
25239    }
25240
25241    #[tokio::test]
25242    async fn an_expired_cache_wait_blocks_without_asking_or_rotating_the_agent() {
25243        crate::run::pin_test_home();
25244        let tmp = tempfile::tempdir().unwrap();
25245        let cache = tmp.path().join("target-b");
25246        let _held = hold(&cache);
25247        let mut st = state(1);
25248        let results = run(
25249            vec![job(
25250                sh("alpha", "echo ok"),
25251                tmp.path(),
25252                Duration::from_secs(1),
25253            )],
25254            Arc::new(Semaphore::new(1)),
25255            Some(&cache),
25256            &mut st,
25257        )
25258        .await;
25259        let (_, seat, out) = &results[0];
25260        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
25261        assert!(wave_blocked(&results));
25262        assert_eq!(seat.agent, "alpha", "the chosen agent is kept");
25263        assert_eq!(seat.turns, 0, "nothing was asked");
25264        assert!(
25265            !tmp.path().join("art").join("impl-A.prompt.md").exists(),
25266            "no agent was spawned"
25267        );
25268        assert!(FailClass::of(out).is_none(), "not a failure class");
25269        let block = st.resource_block.as_ref().expect("recorded for the resume");
25270        assert_eq!(block.kind, "shared build cache");
25271        assert!(matches!(
25272            block.cause,
25273            crate::run::ResourceBlockCause::Timeout { limit_secs: 1, .. }
25274        ));
25275        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
25276        assert!(st.active.is_empty());
25277    }
25278
25279    #[tokio::test]
25280    async fn a_semaphore_with_no_permits_ends_as_a_bounded_resource_block() {
25281        crate::run::pin_test_home();
25282        let tmp = tempfile::tempdir().unwrap();
25283        let mut st = state(1);
25284        let results = run(
25285            vec![job(
25286                sh("alpha", "echo ok"),
25287                tmp.path(),
25288                Duration::from_secs(1),
25289            )],
25290            Arc::new(Semaphore::new(0)),
25291            None,
25292            &mut st,
25293        )
25294        .await;
25295        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
25296        assert_eq!(st.resource_block.as_ref().unwrap().kind, "parallel slot");
25297        assert!(!tmp.path().join("art").join("impl-A.prompt.md").exists());
25298    }
25299
25300    #[tokio::test]
25301    async fn an_agent_that_really_hangs_still_times_out_and_hands_over() {
25302        crate::run::pin_test_home();
25303        let tmp = tempfile::tempdir().unwrap();
25304        let mut st = state(60);
25305        let results = run(
25306            vec![job(
25307                sh("alpha", "sleep 30"),
25308                tmp.path(),
25309                Duration::from_secs(1),
25310            )],
25311            Arc::new(Semaphore::new(1)),
25312            None,
25313            &mut st,
25314        )
25315        .await;
25316        let out = &results[0].2;
25317        assert!(matches!(out, AgentOutcome::Failed(e) if e == TIMED_OUT));
25318        let class = FailClass::of(out).expect("a failure");
25319        assert_eq!(class, FailClass::Timeout);
25320        assert!(should_hand_over(None, &class), "existing handover policy");
25321        assert!(st.resource_block.is_none());
25322    }
25323}