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, None).await
1368    }
1369
1370    /// Authorize a known preparation failure against the inspected evidence.
1371    pub async fn authorize_base_preparation_recovery(
1372        home: &Path,
1373        id: &str,
1374        task: &str,
1375        digest: &str,
1376    ) -> Result<()> {
1377        Self::authorize_base_recovery_request(home, id, task, false, None, Some(digest)).await
1378    }
1379
1380    /// Queue release uses its durable approval generation exactly once.
1381    pub(crate) async fn authorize_base_recovery_from_resumption(
1382        home: &Path,
1383        id: &str,
1384        task: &str,
1385    ) -> Result<()> {
1386        Self::authorize_base_recovery_request(home, id, task, true, None, None).await
1387    }
1388
1389    pub(crate) async fn authorize_base_recovery_control(
1390        home: &Path,
1391        task: &str,
1392        control: &mut crate::base_recovery_control::Transaction,
1393    ) -> Result<()> {
1394        let id = control.request.run.clone();
1395        Self::authorize_base_recovery_request(home, &id, task, false, Some(control), None).await
1396    }
1397
1398    async fn authorize_base_recovery_request(
1399        home: &Path,
1400        id: &str,
1401        task: &str,
1402        resumption: bool,
1403        mut control: Option<&mut crate::base_recovery_control::Transaction>,
1404        terminal_digest: Option<&str>,
1405    ) -> Result<()> {
1406        let _owner = crate::pr_head::owner_lock(home, id)?;
1407        let mut state = RunState::load_under(id, home)?;
1408        crate::pr_head::ensure_owner(&state)?;
1409        let queued = crate::queue::Queue::at(home.join("queue")).get(task)?;
1410        anyhow::ensure!(
1411            queued.execution_runs().last().is_some_and(|run| run == id)
1412                && queued.assignment_accepts(&state)
1413                && queued.status != crate::queue::TaskStatus::Done
1414                && !queued.fresh_start
1415                && queued.review_branch.is_none(),
1416            "run task ownership changed"
1417        );
1418        anyhow::ensure!(
1419            state
1420                .origin
1421                .as_ref()
1422                .and_then(|o| o.task.as_deref())
1423                .is_none_or(|owner| owner == task),
1424            "run belongs to another task"
1425        );
1426        let claimed = crate::daemon::is_working_on_other(home, id, Timestamp::now())?;
1427        anyhow::ensure!(
1428            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
1429            "run is live or its ownership is unknown"
1430        );
1431        // Judge the previous driver's lease before acquiring our maintenance
1432        // lease. The owner lock excludes new driver claims across both steps.
1433        let _execution = crate::driver::maintenance(home, id)?;
1434        anyhow::ensure!(
1435            state.status.resumable()
1436                && state.released_to.is_none()
1437                && state.retired_to.is_none()
1438                && state.pr_taken_over_by.is_none(),
1439            "run ownership is final"
1440        );
1441        anyhow::ensure!(state.base_sync_blocked(), "run has no base-sync stop");
1442        anyhow::ensure!(
1443            !state.pr_publication_pending
1444                && !crate::handover::landing_checkpoint(&state)
1445                && state.merge_decision.is_none(),
1446            "publication or landing has its own retained checkpoint; base recovery cannot replace it"
1447        );
1448        let winner = state.winner().context("run has no retained winner")?;
1449        anyhow::ensure!(
1450            git::is_clean(&winner.worktree).await?,
1451            "retained worktree has uncommitted changes"
1452        );
1453        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
1454        anyhow::ensure!(
1455            git::rev_parse(&state.repo, &format!("refs/heads/{}", winner.branch)).await? == head,
1456            "retained worktree does not match the winner branch"
1457        );
1458        if let Some(control) = control.as_ref() {
1459            anyhow::ensure!(
1460                head.starts_with(&control.request.head),
1461                "retained HEAD changed since the owner request"
1462            );
1463            anyhow::ensure!(
1464                state
1465                    .base_sync_recovery
1466                    .stop
1467                    .as_ref()
1468                    .is_none_or(|stop| stop.head == head),
1469                "retained HEAD differs from the recorded stop head; inspect it first"
1470            );
1471        }
1472        anyhow::ensure!(
1473            crate::repair_budget::legacy::legacy_sequencer_head(&state).is_none(),
1474            "{}",
1475            crate::repair_budget::legacy::LEGACY_EXEC_ACTION
1476        );
1477        state.ensure_base_episode();
1478        state.record_base_sync_stop(&head);
1479        let preparation = state.unknown_preparation_stop(&head);
1480        anyhow::ensure!(
1481            state
1482                .base_sync_recovery
1483                .stop
1484                .as_ref()
1485                .is_some_and(|s| s.kind == crate::base_sync_recovery::StopKind::Exhausted)
1486                || (preparation && !resumption),
1487            "base recovery refused: missing eligible movement-exhaustion or preparation-stop evidence; inspect with `magi task inspect-base-stop {task} --run {id}`. Textual stops require an evidence-bound base-conflict grant"
1488        );
1489        let fetched =
1490            git::fetch(&state.repo, &state.config.merge.remote, &state.base_branch).await?;
1491        anyhow::ensure!(
1492            fetched.ok(),
1493            "cannot authorize base recovery without a fetched base"
1494        );
1495        let approved_tip = git::rev_parse(
1496            &state.repo,
1497            &format!("{}/{}", state.config.merge.remote, state.base_branch),
1498        )
1499        .await?;
1500        let preparation_digest = state.preparation_digest(&head);
1501        anyhow::ensure!(
1502            preparation
1503                || (terminal_digest.is_none()
1504                    && control
1505                        .as_ref()
1506                        .is_none_or(|c| c.request.evidence_digest.is_none())),
1507            "preparation evidence digest does not name an eligible preparation stop"
1508        );
1509        if preparation {
1510            anyhow::ensure!(
1511                crate::daemon::compatible_run_instruction(&state, &queued),
1512                "task instruction does not match the retained run"
1513            );
1514            if let Some(control) = control.as_ref() {
1515                anyhow::ensure!(
1516                    control.request.head == head
1517                        && control.request.evidence_digest.is_some()
1518                        && control.request.evidence_digest == preparation_digest
1519                        && control.request.decision.is_none(),
1520                    "preparation stop requires the full HEAD and current inspected evidence digest"
1521                );
1522            } else {
1523                anyhow::ensure!(
1524                    terminal_digest.is_some() && terminal_digest == preparation_digest.as_deref(),
1525                    "preparation stop requires the current inspected evidence digest"
1526                );
1527            }
1528            let stop = state.base_sync_recovery.stop.as_ref().unwrap();
1529            anyhow::ensure!(
1530                git::is_ancestor(&state.repo, &stop.tip, &approved_tip).await,
1531                "current base does not descend from the stopped base"
1532            );
1533            git::probe_rebase_preparation(
1534                &state,
1535                &head,
1536                &home.join("runs").join(id),
1537                &repository_wait(&state, None),
1538            )
1539            .await?;
1540        }
1541        if let Some(control) = control.as_deref_mut() {
1542            let queue = crate::queue::Queue::at(home.join("queue"));
1543            control.prepare(&queue, &state, &queued, &head, &approved_tip)?;
1544            if let Some(prior) = state
1545                .base_sync_recovery
1546                .authorizations
1547                .iter()
1548                .find(|a| a.request.as_deref() == Some(&control.key()))
1549            {
1550                anyhow::ensure!(
1551                    !prior.consumed && prior.invalidated.is_none() && state.base_recovery_pending(),
1552                    "recovery request was consumed or invalidated; it cannot queue again"
1553                );
1554                return control.enqueue(&queue);
1555            }
1556        }
1557        if resumption {
1558            anyhow::ensure!(
1559                crate::daemon::compatible_run_instruction(&state, &queued),
1560                "resumption instruction does not match the retained run"
1561            );
1562            let approval = queued
1563                .resumption
1564                .as_ref()
1565                .context("no operator resumption")?;
1566            anyhow::ensure!(
1567                approval.instruction == queued.instruction,
1568                "resumption approval does not match the current task instruction"
1569            );
1570            state.authorize_base_sync_resumption(task, approval)?;
1571        } else {
1572            state.authorize_base_sync(task)?;
1573        }
1574        let episode = state.base_sync_recovery.episodes.last().unwrap().id;
1575        state
1576            .base_sync_recovery
1577            .authorizations
1578            .last_mut()
1579            .unwrap()
1580            .scope = Some(crate::base_sync_recovery::Scope {
1581            tip: approved_tip,
1582            instruction: queued.instruction.clone(),
1583            episode,
1584            preparation_digest,
1585        });
1586        if let Some(control) = control.as_deref_mut() {
1587            let authorization = state.base_sync_recovery.authorizations.last_mut().unwrap();
1588            authorization.request = Some(control.key());
1589            authorization.generation = control.generation();
1590            authorization.decision = control.decision();
1591            authorization.question = control
1592                .request
1593                .decision
1594                .as_ref()
1595                .map(|_| control.request.request.clone());
1596        }
1597        state.event(
1598            "base-recovery",
1599            if preparation {
1600                "owner authorized the proven preparation-stop recovery; remaining budget retained; fresh verification required"
1601            } else {
1602                "owner authorized a bounded base synchronization interval; fresh verification required"
1603            },
1604        );
1605        state.save_under(home)?;
1606        if let Some(control) = control {
1607            control.enqueue(&crate::queue::Queue::at(home.join("queue")))?;
1608        }
1609        Ok(())
1610    }
1611
1612    /// Reopen an existing run.
1613    pub fn resume(id: &str) -> Result<Self> {
1614        let state = RunState::load(id)?;
1615        crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &state.id)?;
1616        if state.startup.as_ref().is_some_and(|s| !s.complete)
1617            || (state.status == RunStatus::Prep
1618                && state.instruction.trim().is_empty()
1619                && state.candidates.is_empty()
1620                && state.prep_complete == Some(false))
1621        {
1622            bail!(
1623                "run {id} did not finish startup; inspect its startup evidence and retained assets, then start an explicitly authorized review or recovery"
1624            );
1625        }
1626        crate::pr_head::ensure_owner(&state)?;
1627        if state.pr_recovery.is_some() && state.reviewed_commits.is_none() {
1628            bail!(
1629                "selected public-head recovery did not finish setup; use `magi task recover-pr` after correcting the cause"
1630            );
1631        }
1632        if let Some(to) = &state.released_to {
1633            bail!(
1634                "run {} cannot be resumed: its worktree was released to run {}",
1635                state.short(),
1636                crate::run::short_of(to)
1637            );
1638        }
1639        let roles = state.config.resolve_roles()?;
1640        if let Some(id) = &state.config.graph.selected_implementer
1641            && state.candidates.iter().any(|c| c.agent != *id)
1642        {
1643            bail!(
1644                "replacement implementer pin does not match the saved candidates; task must stay held"
1645            );
1646        }
1647        let max_parallel = state.config.graph.max_parallel.max(1);
1648        Ok(Self {
1649            state,
1650            roles,
1651            sem: Arc::new(Semaphore::new(max_parallel)),
1652            pause: Pause::new(),
1653            interrupt: Pause::new(),
1654        })
1655    }
1656
1657    /// Walk the graph to a terminal state, skipping nodes already recorded.
1658    ///
1659    /// Every way a run is driven - the queue loop, `magi run`, a resume from
1660    /// the phone - ends here, so this is the one place a run that ended
1661    /// Blocked / Stalled / Failed, or died with an error, is announced to the
1662    /// attention-report outbox. Best-effort: see [`crate::notices::raise`].
1663    pub fn execute(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
1664        // Allocate before polling: boxing inside an async wrapper would still
1665        // retain its construction frame while the nested graph is polled.
1666        Box::pin(self.execute_inner(None))
1667    }
1668
1669    pub(crate) async fn execute_sync_only(
1670        &mut self,
1671        request: crate::base_sync_only::Request,
1672    ) -> Result<()> {
1673        Box::pin(self.execute_inner(Some(request))).await
1674    }
1675
1676    async fn execute_inner(
1677        &mut self,
1678        sync_only: Option<crate::base_sync_only::Request>,
1679    ) -> Result<()> {
1680        anyhow::ensure!(
1681            self.state.startup.as_ref().is_none_or(|s| s.complete),
1682            "startup incomplete; inspect retained evidence before explicit recovery"
1683        );
1684        if let Some(selection) = &self.state.pr_recovery
1685            && (selection.source_proof.is_some() || selection.source_run.is_some())
1686        {
1687            Box::pin(selection.verify_source(&self.state.repo)).await?;
1688        }
1689        // Queue claims cover daemon work; this also serializes manual drivers
1690        // consuming a repair answer, including the new review and decision.
1691        let _repair_claim = if self.state.config.graph.selected_implementer.is_some()
1692            || self.state.land_approval.is_some()
1693            || self.state.merge_decision.is_some()
1694            || !self.state.merge_repairs.is_empty()
1695            || (self.state.status == RunStatus::Landing && land::repair_available(&self.state))
1696        {
1697            let claim = FixClaim::acquire(&self.state.dir())?;
1698            crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &self.state.id)?;
1699            let disk = RunState::load(&self.state.id)?;
1700            let checkpoint = |s: &RunState| {
1701                (
1702                    s.merge_repairs.len(),
1703                    s.merge_repairs
1704                        .last()
1705                        .map(|r| (r.question.clone(), r.phase)),
1706                    s.land_approval
1707                        .as_ref()
1708                        .map(|a| (a.question.clone(), a.head.clone())),
1709                )
1710            };
1711            if checkpoint(&disk) != checkpoint(&self.state) {
1712                bail!(
1713                    "repair decision changed since this run was loaded; reload and resume the existing run, never start a second repair"
1714                );
1715            }
1716            Some(claim)
1717        } else {
1718            None
1719        };
1720        let base_only = sync_only.is_some();
1721        let mut execution = self.claim_driver(sync_only).await?;
1722        let runner = &mut *execution.runner;
1723        let wait = runner.repository_wait();
1724        // Keep the graph's large future off the callers' stack, including
1725        // standalone task attempts running on a default-sized test thread.
1726        let result = if base_only {
1727            wait.scope(Box::pin(async {
1728                let repo = runner.state.repo.clone();
1729                let result = async {
1730                    let _coordination = runner.coordinate(&repo).await?;
1731                    anyhow::ensure!(
1732                        !runner.pause.parked() && !runner.interrupt.parked(),
1733                        "paused before base synchronization"
1734                    );
1735                    crate::base_sync_only::sync(&mut runner.state).await
1736                }
1737                .await;
1738                let pass = runner.state.sync_only_passes.last_mut().unwrap();
1739                pass.result = match result {
1740                    Ok(outcome) => outcome,
1741                    Err(error) => crate::base_sync_only::Outcome::Stopped(format!("{error:#}")),
1742                };
1743                let summary = pass.summary();
1744                runner.state.event("base-sync-only", summary);
1745                runner.state.save()
1746            }))
1747            .await
1748        } else {
1749            wait.scope(Box::pin(runner.execute_graph())).await
1750        };
1751        let result = match result {
1752            Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
1753                record_repository_block(&mut runner.state, &e);
1754                runner.park_here()?;
1755                Ok(())
1756            }
1757            other => other,
1758        };
1759        execution.driver.finish(&mut runner.state).await?;
1760        let ended = if result.is_err() {
1761            Some({
1762                let mut notice = crate::notices::run_stopped(&runner.state.id, &runner.state);
1763                if let Err(error) = &result {
1764                    notice.message = format!(
1765                        "Run {} stopped with an error: {}",
1766                        runner.state.id,
1767                        error.to_string().lines().next().unwrap_or("unknown error")
1768                    );
1769                }
1770                notice
1771            })
1772        } else {
1773            crate::notices::run_ended(&runner.state)
1774        };
1775        if let Some(notice) = ended {
1776            crate::notices::raise(notice);
1777        }
1778        result
1779    }
1780
1781    fn repository_wait(&self) -> crate::repo_lock::WaitPolicy {
1782        repository_wait(&self.state, Some((&self.pause, &self.interrupt)))
1783    }
1784
1785    async fn coordinate(&mut self, cwd: &Path) -> Result<Option<crate::repo_lock::SeatLease>> {
1786        let wait = self.repository_wait();
1787        coordinate_operation(&mut self.state, cwd, &wait).await
1788    }
1789
1790    /// Validate ownership and persist the driver claim in one critical section.
1791    async fn claim_driver(
1792        &mut self,
1793        sync_only: Option<crate::base_sync_only::Request>,
1794    ) -> Result<DriverExecution<'_>> {
1795        let owner = match crate::pr_head::owner_lock_wait(
1796            &crate::run::home(),
1797            &self.state.id,
1798            Duration::from_secs(self.state.config.graph.timeout_resource_wait),
1799        )
1800        .await
1801        {
1802            Ok(owner) => owner,
1803            Err(error) => {
1804                let detail = format!("worktree maintenance or ownership update: {error:#}");
1805                // Admission did not own run.json: retain this resource outcome
1806                // in memory for queue settlement without overwriting a concurrent
1807                // retirement or publication transaction.
1808                self.state.resource_block = Some(crate::run::ResourceBlock {
1809                    cause: crate::run::ResourceBlockCause::Other,
1810                    node: "start".into(),
1811                    kind: "worktree maintenance".into(),
1812                    detail: detail.clone(),
1813                    at: Timestamp::now(),
1814                });
1815                return Err(crate::repo_lock::ResourceBlocked(detail).into());
1816            }
1817        };
1818        let disk = RunState::load(&self.state.id)?;
1819        crate::pr_head::ensure_owner(&disk)?;
1820        let now = Timestamp::now();
1821        let home = crate::run::home();
1822        let claim = crate::daemon::other_claim_for_run(&home, &disk.id, now)?;
1823        let assessment = disk.assess_liveness_under(&home, claim, now);
1824        // Only proven-live ownership refuses here. Unknown records (legacy runs
1825        // with no claim marker or process identity) fall through to the
1826        // exclusive execution lease taken just below, which is what actually
1827        // keeps a second driver out.
1828        anyhow::ensure!(
1829            assessment.verdict != crate::run::Liveness::Live,
1830            "{}",
1831            assessment.live_driver_refusal()
1832        );
1833        if let Some(to) = &disk.released_to {
1834            bail!(
1835                "run {} cannot continue: its worktree was released to run {}",
1836                self.state.short(),
1837                crate::run::short_of(to)
1838            );
1839        }
1840        anyhow::ensure!(
1841            serde_json::to_value(&disk.base_sync_recovery)?
1842                == serde_json::to_value(&self.state.base_sync_recovery)?,
1843            "base recovery changed since this run was loaded; reload the saved run"
1844        );
1845        anyhow::ensure!(
1846            disk.sync_only_passes == self.state.sync_only_passes,
1847            "base-only synchronization changed since this run was loaded; reload the saved run"
1848        );
1849        let driver = crate::driver::DriverGuard::acquire(&crate::run::home(), &disk)?;
1850        let mut execution = DriverExecution {
1851            runner: self,
1852            driver,
1853        };
1854        // Declare after the execution guard: on any claim error this short
1855        // lock must drop before that guard reloads and releases ownership.
1856        let _owner = owner;
1857        if let Some(request) = sync_only {
1858            crate::base_sync_only::validate_run(&disk, &crate::run::home())?;
1859            anyhow::ensure!(
1860                request.run == disk.id,
1861                "sync-base-only request targets a different run"
1862            );
1863            let state = &mut execution.runner.state;
1864            let task_entry = state.next_pass_task_entry;
1865            *state = disk;
1866            state.next_pass_task_entry = task_entry;
1867            if state.pending_sync_only().is_some() {
1868                let pass_index = state.passes.len();
1869                let pass = state.sync_only_passes.last_mut().unwrap();
1870                anyhow::ensure!(
1871                    pass.request == request,
1872                    "interrupted base-only synchronization belongs to a different request"
1873                );
1874                pass.pass_index = pass_index;
1875            } else {
1876                let pass = crate::base_sync_only::Pass::new(request, state);
1877                state.sync_only_passes.push(pass);
1878            }
1879            if state.status == RunStatus::Failed {
1880                state.status = RunStatus::Blocked;
1881            }
1882        } else {
1883            anyhow::ensure!(
1884                disk.pending_sync_only().is_none(),
1885                "base-only synchronization has not succeeded; resume with --sync-base-only before verifying"
1886            );
1887            crate::repair_budget::apply(&crate::run::home(), &mut execution.runner.state, &disk)
1888                .await?;
1889        }
1890        let state = &mut execution.runner.state;
1891        // Moving again, so it is no longer parked. Set before the walk rather
1892        // than in `resume`, so every way of re-entering the graph clears it
1893        // and a card cannot claim a run is waiting to be resumed while the
1894        // agents are already working.
1895        state.parked = false;
1896        state.resource_wait = None;
1897        state.resource_block = None;
1898        // Any seat this state still lists as answering belongs to whatever
1899        // process last drove this run — this one included, if it crashed
1900        // mid-wave. Cleared and flushed immediately, before anything else
1901        // runs, so a resume can never show a seat as live when nothing is
1902        // asking it anything yet; the node that actually dispatches the next
1903        // wave repopulates it.
1904        state.clear_active();
1905        // Recorded in the same spot, and flushed together with the clear
1906        // above: this is the pid a reader checks (`RunState::liveness`) when
1907        // no daemon claim exists to answer "is a process still driving this
1908        // run" — a plain `magi run` / `magi review` typed into a terminal
1909        // claims nothing there. Always overwritten, never only-if-absent, so
1910        // a resumed run's stale pid from a previous, possibly-dead process
1911        // can never survive into this one's own report. Unlike
1912        // `clear_active`, this changes on every single `execute()` call, so
1913        // the save below is now unconditional rather than only-if-cleared.
1914        //
1915        // `driver_started_at` is recorded in the same breath, from this same
1916        // pid, so `liveness` can tell a live pid that is genuinely still us
1917        // apart from one the OS has since handed to an unrelated process —
1918        // see that field's own doc for why the pid alone is not enough.
1919        let pid = std::process::id();
1920        state.driver_pid = Some(pid);
1921        state.driver_started_at = crate::proc::process_started_at(pid);
1922        state.driver_exited = false;
1923        state.driver_claimed = Some(true);
1924        state.begin_pass();
1925        execution.driver.bind(state);
1926        state.save()?;
1927        execution.driver.record(state)?;
1928        Ok(execution)
1929    }
1930
1931    /// No conflict checkpoint proves dispatch was never reached. End that
1932    /// consumed generation so an owner can explicitly authorize a fresh one.
1933    async fn repair_base_conflict(&mut self, dispatch: bool) -> Result<()> {
1934        let result = crate::base_conflict::repair(&mut self.state, dispatch).await;
1935        if let Err(error) = &result
1936            && !error.is::<crate::repo_lock::ResourceBlocked>()
1937            && self
1938                .state
1939                .repair_grants
1940                .last()
1941                .is_some_and(|g| g.conflict.is_none())
1942        {
1943            self.state.repair_grants.last_mut().unwrap().phase =
1944                crate::repair_budget::Phase::Complete;
1945            self.state.status = RunStatus::Blocked;
1946            self.state.save()?;
1947            bail!(
1948                "{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",
1949                self.state.passes.last().map_or(0, |p| p.index)
1950            );
1951        }
1952        result
1953    }
1954
1955    /// A grant owns only these repair attempts. Confirmation reviews cannot
1956    /// create another fixer allowance, and every operation is restart-checkpointed.
1957    async fn execute_granted_repair(&mut self) -> Result<()> {
1958        use crate::repair_budget::{Kind, Phase};
1959        let index = self.state.repair_grants.len() - 1;
1960        let winner = self
1961            .state
1962            .winner()
1963            .cloned()
1964            .context("repair winner missing")?;
1965        loop {
1966            let grant = self.state.repair_grants[index].clone();
1967            match grant.phase {
1968                Phase::Pending => {
1969                    if grant.spent >= grant.receipt.request.rounds {
1970                        self.state.repair_grants[index].phase = Phase::Complete;
1971                        self.state.status = RunStatus::Blocked;
1972                        self.state.save()?;
1973                        return Ok(());
1974                    }
1975                    // Reserve before dispatch. A crash can consume an attempt,
1976                    // but can never duplicate it or reset saved fixer history.
1977                    self.state.repair_grants[index].spent += 1;
1978                    self.state.repair_grants[index].phase = Phase::Fixing;
1979                    self.state.save()?;
1980                    match grant.receipt.request.kind {
1981                        Kind::BaseConflict => self.repair_base_conflict(true).await?,
1982                        Kind::Gate => {
1983                            let failed = self.state.gate.clone();
1984                            let _ = self.gate_fix_round(&winner, &failed).await?;
1985                        }
1986                        Kind::Review => {
1987                            let mut record = self
1988                                .state
1989                                .reviews
1990                                .last()
1991                                .cloned()
1992                                .context("review failure missing")?;
1993                            let round = record.round;
1994                            let step = self.run_fix_round(&winner, &mut record).await?;
1995                            self.state.reviews[round - 1] = record;
1996                            if matches!(step, FixStep::Recorded { report_lost: true }) {
1997                                self.state.repair_grants[index].phase = Phase::Complete;
1998                                self.state.status = RunStatus::Blocked;
1999                                self.state.event("repair-grant", "fixer continuation remains unresolved; repair grant cannot bypass its stop");
2000                                self.state.save()?;
2001                                return Ok(());
2002                            }
2003                            if matches!(step, FixStep::Resource) {
2004                                self.stop_for_resource()?;
2005                                return Ok(());
2006                            }
2007                            self.state.save()?;
2008                        }
2009                    }
2010                    if self.resource_halt()? {
2011                        return Ok(());
2012                    }
2013                }
2014                Phase::Fixing => {
2015                    if grant.receipt.request.kind == Kind::BaseConflict {
2016                        self.repair_base_conflict(false).await?;
2017                    }
2018                    // Interrupted fixers may have left source changes or an
2019                    // unpushed commit. Preserve them before fresh assessment.
2020                    let _coordination = self.coordinate(&winner.worktree).await?;
2021                    let rescued = git::rescue_commit(
2022                        &winner.worktree,
2023                        "magi: preserve interrupted granted repair",
2024                    )
2025                    .await?;
2026                    self.state.note_withheld("repair-grant", &rescued.withheld);
2027                    // Fresh checks must supersede even a same-head failure.
2028                    // Archive rather than erase failure evidence or counters.
2029                    self.state
2030                        .verification_history
2031                        .push(crate::run::VerificationEvidence {
2032                            superseded_by: None,
2033                            archived_at: Some(Timestamp::now()),
2034                            fixes_spent: Some(self.state.gate_fixes.len()),
2035                            gate_head: self.state.gate_head.take(),
2036                            gate_ran: std::mem::take(&mut self.state.gate_ran),
2037                            gate: std::mem::take(&mut self.state.gate),
2038                            e2e: self.state.head_e2e.take(),
2039                        });
2040                    if let Some(e2e) = self.state.gate_repair_e2e.take() {
2041                        self.state
2042                            .verification_history
2043                            .push(crate::run::VerificationEvidence {
2044                                superseded_by: None,
2045                                archived_at: Some(Timestamp::now()),
2046                                fixes_spent: Some(self.state.gate_fixes.len()),
2047                                gate_head: None,
2048                                gate_ran: false,
2049                                gate: Vec::new(),
2050                                e2e: Some(e2e),
2051                            });
2052                    }
2053                    self.state.repair_grants[index].review_start = self.state.reviews.len();
2054                    self.state.repair_grants[index].head =
2055                        git::rev_parse(&winner.worktree, "HEAD").await?;
2056                    self.state.repair_grants[index].phase = Phase::Reviewing;
2057                    if grant.receipt.request.kind == Kind::BaseConflict {
2058                        self.state.base_sync_recovery.stop = None;
2059                        if let Some(sync) = &mut self.state.base_sync {
2060                            sync.tip = grant
2061                                .receipt
2062                                .request
2063                                .tip
2064                                .clone()
2065                                .context("repair base tip missing")?;
2066                            sync.conflict = None;
2067                            sync.behind = 0;
2068                        }
2069                        refresh_reviewed_commits(&mut self.state, &winner.branch).await;
2070                    }
2071                    self.state.save()?;
2072                }
2073                Phase::Reviewing => {
2074                    self.review_loop_pass().await?;
2075                    if self.resource_halt()? {
2076                        return Ok(());
2077                    }
2078                    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
2079                    let clean = self.state.reviews.len() > grant.review_start
2080                        && self.state.reviews.last().is_some_and(|r| {
2081                            r.head == head
2082                                && r.clean
2083                                && r.expected > 0
2084                                && r.answered == r.expected
2085                                && matches!(
2086                                    r.e2e_status(),
2087                                    E2eStatus::Passed | E2eStatus::NotConfigured
2088                                )
2089                        });
2090                    if !clean {
2091                        // A confirmation review carries no additional fix budget.
2092                        self.state.repair_grants[index].phase = if grant.receipt.request.kind
2093                            == Kind::Review
2094                            && grant.spent < grant.receipt.request.rounds
2095                            && self.state.reviews.last().is_some_and(|r| {
2096                                r.fix.is_none()
2097                                    && (r.blocking > 0 || r.e2e_status() == E2eStatus::Failed)
2098                            }) {
2099                            Phase::Pending
2100                        } else {
2101                            Phase::Complete
2102                        };
2103                        self.state.status = RunStatus::Blocked;
2104                        self.state.event(
2105                            "repair-grant",
2106                            "fresh review did not clear the repaired head; no publication",
2107                        );
2108                        self.state.save()?;
2109                        if self.state.repair_grants[index].phase == Phase::Pending {
2110                            continue;
2111                        }
2112                        return Ok(());
2113                    }
2114                    self.state.repair_grants[index].phase = Phase::Gating;
2115                    self.state.save()?;
2116                }
2117                Phase::Gating => {
2118                    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
2119                    self.state.reconcile_verification_head(&head);
2120                    let wait = self.repository_wait();
2121                    if self
2122                        .state
2123                        .reviews
2124                        .last()
2125                        .is_none_or(|r| r.head != head || !r.clean)
2126                    {
2127                        self.state.status = RunStatus::Blocked;
2128                        self.state.repair_grants[index].phase = Phase::Complete;
2129                        self.state.event(
2130                            "repair-grant",
2131                            "head changed since fresh review; repair held",
2132                        );
2133                        self.state.save()?;
2134                        return Ok(());
2135                    }
2136                    if !verify_current_head(&mut self.state, &winner, &wait).await? {
2137                        return Ok(());
2138                    }
2139                    let outcomes = self.run_gate(&winner).await?;
2140                    if verify_inconclusive(&outcomes) {
2141                        return Ok(());
2142                    }
2143                    let after = git::rev_parse(&winner.worktree, "HEAD").await?;
2144                    if after != head {
2145                        self.state.repair_grants[index].review_start = self.state.reviews.len();
2146                        self.state.repair_grants[index].head = after;
2147                        self.state.repair_grants[index].phase = Phase::Reviewing;
2148                        self.state.status = RunStatus::Blocked;
2149                        self.state.event("repair-grant", "pre-gate changed the reviewed head; resume for fresh review before publication");
2150                        self.state.save()?;
2151                        return Ok(());
2152                    }
2153                    let passed = outcomes.iter().all(CommandOutcome::ok);
2154                    // Follow-up grants owe the same guarded checkout delivery
2155                    // as the conflict repair that introduced the new head.
2156                    if passed
2157                        && !crate::foreign_checkout::write_back(&mut self.state, &head).await?
2158                    {
2159                        return Ok(());
2160                    }
2161                    self.state.repair_grants[index].succeeded = passed;
2162                    self.state.gate = outcomes;
2163                    self.state.gate_ran = true;
2164                    self.state.status = if passed {
2165                        RunStatus::Gating
2166                    } else {
2167                        RunStatus::Blocked
2168                    };
2169                    self.state.repair_grants[index].phase = if !passed
2170                        && grant.receipt.request.kind == Kind::Gate
2171                        && grant.spent < grant.receipt.request.rounds
2172                    {
2173                        Phase::Pending
2174                    } else {
2175                        Phase::Complete
2176                    };
2177                    if passed && self.state.config.merge.mode == MergeMode::Pr {
2178                        // Persist publication debt with the successful checkpoint.
2179                        self.state.pr_publication_pending = true;
2180                    } else if passed {
2181                        self.state.status = RunStatus::Ready;
2182                    }
2183                    self.state.save()?;
2184                    if !passed {
2185                        continue;
2186                    }
2187                    // Existing PR ownership and push lease stay in place. The
2188                    // normal publisher owes the new reviewed/gated SHA, and
2189                    // land's fresh owner approval remains mandatory.
2190                    if self.state.config.merge.mode != MergeMode::Pr {
2191                        self.state.status = RunStatus::Ready;
2192                        self.state.event(
2193                            "repair-grant",
2194                            "repair verified locally; grant carries no merge authorization",
2195                        );
2196                        self.state.save()?;
2197                        return Ok(());
2198                    }
2199                    return self.merge().await;
2200                }
2201                Phase::Complete => return Ok(()),
2202            }
2203        }
2204    }
2205
2206    async fn execute_graph(&mut self) -> Result<()> {
2207        // Even a terminal run may reenter through an explicit recovery action.
2208        // Restore before prep shortcuts, saved conversations or graph nodes use
2209        // a disposable path; GC may already have removed its original objects.
2210        let archive_home = crate::run::home().canonicalize()?;
2211        if crate::retention::has_archived_seats(&archive_home, &self.state)? {
2212            let repo = self.state.repo.clone();
2213            let _coordination = self.coordinate(&repo).await?;
2214            ensure_setup_config(&mut self.state, &repo).await?;
2215            crate::retention::restore_execution_seats(
2216                &archive_home,
2217                &self.state,
2218                _coordination.as_ref(),
2219            )
2220            .await?;
2221        }
2222        self.state.configure_recovery_resume()?;
2223        if self
2224            .state
2225            .repair_grants
2226            .last()
2227            .is_some_and(|g| g.phase != crate::repair_budget::Phase::Complete)
2228        {
2229            return self.execute_granted_repair().await;
2230        }
2231        if self
2232            .state
2233            .repair_grants
2234            .last()
2235            .is_some_and(|g| !g.succeeded)
2236        {
2237            self.state.status = RunStatus::Blocked;
2238            self.state.save()?;
2239            return Ok(());
2240        }
2241        // Preservation may invalidate an old empty classification. Resolve it
2242        // before any resume shortcut can reuse a verdict or publish a branch.
2243        self.persist_candidates().await?;
2244        // A saved base stop outranks stage markers, including legacy Voting.
2245        // Recovery never reenters implementation, deliberation or voting.
2246        if self.state.base_sync_blocked() {
2247            self.sync_to_base().await?;
2248            if !self.state.base_sync_blocked()
2249                && self.state.status != RunStatus::AlreadyInBase
2250                && !self.resource_halt()?
2251            {
2252                self.finish_after_tally().await?;
2253            }
2254            return Ok(());
2255        }
2256        if self
2257            .state
2258            .merge_decision
2259            .as_ref()
2260            .is_some_and(|decision| !decision.closed)
2261            && self.state.status != RunStatus::Landing
2262        {
2263            if crate::merge_decision::resumable_hold(&self.state) {
2264                self.state.merge = Some(MergeOutcome {
2265                    mode: MergeMode::Pr,
2266                    ok: false,
2267                    detail: self
2268                        .state
2269                        .merge_decision
2270                        .as_ref()
2271                        .unwrap()
2272                        .target
2273                        .pr
2274                        .clone(),
2275                    empty: false,
2276                });
2277                self.run_land().await?;
2278                self.settle_questions();
2279                return Ok(());
2280            }
2281            bail!(
2282                "owner stop decision is held; inspect the existing PR and request an explicit fresh review/decision before further work"
2283            );
2284        }
2285        if self.state.config.graph.selected_implementer.is_some()
2286            && self.state.status == RunStatus::Blocked
2287            && self.state.tally.is_none()
2288            && self.state.candidate_preservation.is_empty()
2289            && self.state.interrupted_implementations.is_empty()
2290        {
2291            bail!(
2292                "selected implementation is held; explicitly release the owning task to retry it"
2293            );
2294        }
2295
2296        if self.state.merge_repairs.last().is_some_and(|r| {
2297            matches!(
2298                r.phase,
2299                crate::run::MergeRepairPhase::Requested
2300                    | crate::run::MergeRepairPhase::Fixing
2301                    | crate::run::MergeRepairPhase::Reviewing
2302            )
2303        }) {
2304            if self.repair_merge_review().await? {
2305                self.run_land().await?;
2306            }
2307            self.settle_questions();
2308            return Ok(());
2309        }
2310        // Publication already passed review and gate. Resume only that node:
2311        // syncing to a newer base here could change the verified commit.
2312        if self.state.pr_publication_pending {
2313            self.merge().await?;
2314            if self.resource_halt()? {
2315                return Ok(());
2316            }
2317            self.state.save()?;
2318            self.settle_questions();
2319            return Ok(());
2320        }
2321        // A run that already lost its quorum never resumes into the verdict
2322        // machinery: `deliberate` and `vote` would otherwise clobber the
2323        // stalled marker back to Voting and the run would keep going past a
2324        // verdict that is no longer trustworthy. Everything already recorded is
2325        // kept, so the run stays resumable (or foldable) for a human to pick up.
2326        //
2327        // On --resume the run gets one chance to repair itself: the seats a
2328        // rate limit took out are re-asked. If their quota has since reset and
2329        // the quorum is restored, the run picks up and finishes; otherwise it
2330        // stays stale and still-resumable for a later retry. If it does not
2331        // recover, the returned status stays `Stalled` and nothing was
2332        // clobbered (the recovery only mutates entries for the lost seats).
2333        if self.state.status == RunStatus::Stalled {
2334            if self.recover_stall().await? {
2335                self.finish_after_tally().await?;
2336            } else {
2337                // Still below quorum: persist the marker and stay resumable.
2338                self.state.save()?;
2339            }
2340            return Ok(());
2341        }
2342        // A run parked inside `land` - watching CI, mid fix-round, or
2343        // waiting on the owner's merge approval - resumes directly into it,
2344        // never back through `prep`. Everything before `merge` already
2345        // concluded; that is the only way `status` reaches `Landing` in the
2346        // first place. Re-walking `review_loop` first would also be actively
2347        // wrong: its own status recomputation (see its doc) treats any
2348        // clean round as reason to set `status` to `Gating`, which would
2349        // clobber this marker before `merge` ever ran, and this run would
2350        // never find its way back into `land` at all.
2351        if self.state.status == RunStatus::Landing
2352            || crate::handover::landing_checkpoint(&self.state)
2353        {
2354            self.state.land_sync_pending = true;
2355            self.state.save()?;
2356            self.run_land().await?;
2357            // `run_land` may have settled the run right here - CI came back
2358            // green and the PR merged, say - without ever passing back
2359            // through `merge`'s own trailing call. Whatever it left `status`
2360            // as is what this has to read.
2361            self.settle_questions();
2362            return Ok(());
2363        }
2364        // A run parked at `merge` on the owner's word about a withheld PR text
2365        // resumes straight into `merge`. Re-walking the tail would sync to the
2366        // base again (possibly rebasing, possibly spending the fixer) after the
2367        // gate had passed, and then push a tree nobody reviewed or gated.
2368        if self.state.github_text.is_some()
2369            && self.state.merge.is_none()
2370            && self.state.status == RunStatus::Gating
2371        {
2372            self.merge().await?;
2373            if self.resource_halt()? {
2374                return Ok(());
2375            }
2376            self.state.save()?;
2377            return Ok(());
2378        }
2379        // A resource stop left the reserved synchronization unfinished. Reconcile
2380        // its exact HEAD and base before starting any earlier graph stage.
2381        if self.state.pending_base_operation().is_some() {
2382            return self.finish_after_tally().await;
2383        }
2384        if let Err(e) = self.prep().await {
2385            if e.is::<crate::repo_lock::ResourceBlocked>() {
2386                return Err(e);
2387            }
2388            self.state.status = RunStatus::Blocked;
2389            self.state
2390                .prep_failure
2391                .get_or_insert_with(|| format!("{e:#}"));
2392            self.state
2393                .event("prep", format!("preparation stopped: {e:#}"));
2394            self.state.save()?;
2395            return Err(e);
2396        }
2397        if self.park_here()? {
2398            return Ok(());
2399        }
2400        self.advise().await?;
2401        if self.park_here()? {
2402            return Ok(());
2403        }
2404        self.implement().await?;
2405        if self.park_here()? {
2406            return Ok(());
2407        }
2408        // `after_implement` already saved the state and settled any open
2409        // questions when it set this; nothing later in the graph has
2410        // anything to judge.
2411        if self.state.status == RunStatus::VerifiedNoop {
2412            return Ok(());
2413        }
2414        self.judge().await?;
2415        if self.park_here()? {
2416            return Ok(());
2417        }
2418        self.deliberate().await?;
2419        if self.park_here()? {
2420            return Ok(());
2421        }
2422        self.vote().await?;
2423        if self.park_here()? {
2424            return Ok(());
2425        }
2426        self.tally()?;
2427        // A verdict that lost its quorum is not trustworthy: do not review,
2428        // gate, or merge on it. Everything already done is kept, so the run
2429        // stays resumable (or foldable); the human can replace the agent that
2430        // ran out of quota and pick it up.
2431        if self.state.status == RunStatus::Stalled {
2432            // Persist the stalled marker now — the normal end-of-execute save
2433            // below is below this early return, and without it a resumed run
2434            // would reload a pre-tally status and keep going.
2435            self.state.save()?;
2436            return Ok(());
2437        }
2438        self.finish_after_tally().await?;
2439        Ok(())
2440    }
2441
2442    /// A wave could not start its agents because a shared resource stayed busy
2443    /// (see [`RunState::resource_block`]): leave the run `Blocked` and
2444    /// resumable. Unstarted seats have no result; completed peers retain
2445    /// their saved candidate state.
2446    fn stop_for_resource(&mut self) -> Result<()> {
2447        // Resource acquisition observes cancellation inside a node. Complete
2448        // the same durable park as every other node boundary before returning.
2449        if self.pause.parked() || self.interrupt.parked() {
2450            self.park_here()?;
2451            return Ok(());
2452        }
2453        if self.state.resource_block.is_some() {
2454            self.state.status = RunStatus::Blocked;
2455        }
2456        self.state.save()
2457    }
2458
2459    /// Stop walking the graph if a node ended on a resource block.
2460    fn resource_halt(&mut self) -> Result<bool> {
2461        if self.state.resource_block.is_none() {
2462            return Ok(false);
2463        }
2464        self.stop_for_resource()?;
2465        Ok(true)
2466    }
2467
2468    /// Park here if asked to, recording it in the run's own timeline.
2469    ///
2470    /// Returns whether the caller should stop walking the graph. The state is
2471    /// saved either way by the node that just finished; this adds the event so
2472    /// the operator's card says why a run that is neither finished nor moving
2473    /// is sitting where it is.
2474    fn park_here(&mut self) -> Result<bool> {
2475        let parking = self.pause.parked() || self.interrupt.parked();
2476        if !parking && self.state.resource_block.is_some() {
2477            self.stop_for_resource()?;
2478            return Ok(true);
2479        }
2480        // Either handle asking is enough - see `Pause`'s own doc for why
2481        // they are never the same one. `interrupt` is checked second so a
2482        // reason it carries is preferred in the message below over a plain
2483        // shutdown park racing it at the same boundary.
2484        if !self.pause.parked() && !self.interrupt.parked() {
2485            return Ok(false);
2486        }
2487        if self.state.parked {
2488            return Ok(true);
2489        }
2490        let cause = self.interrupt.cause().or_else(|| self.pause.cause());
2491        if let Some(block) = &mut self.state.resource_block
2492            && matches!(
2493                block.cause,
2494                crate::run::ResourceBlockCause::Cancelled { .. }
2495            )
2496        {
2497            block.cause = crate::run::ResourceBlockCause::Cancelled {
2498                park: cause.clone(),
2499            };
2500        }
2501        let why = match cause.as_ref().map(ParkCause::label) {
2502            Some(reason) => format!(
2503                "parked after `{}` ({reason}) — resume to carry on from here",
2504                self.state.status.as_str()
2505            ),
2506            None => format!(
2507                "parked after `{}` — resume to carry on from here",
2508                self.state.status.as_str()
2509            ),
2510        };
2511        self.state.event("park", why);
2512        self.state
2513            .end_pass_parked(cause.unwrap_or(ParkCause::Unspecified));
2514        self.state.parked = true;
2515        self.state.save()?;
2516        Ok(true)
2517    }
2518
2519    /// Only a new explicit operator approval may retry failed preparation.
2520    pub fn retry_preparation(&mut self, approval_at: jiff::Timestamp) -> Result<()> {
2521        if self.state.prep_failure.is_none() {
2522            return Ok(());
2523        }
2524        let failed_at = self
2525            .state
2526            .events
2527            .iter()
2528            .rev()
2529            .find(|event| event.node == "prep")
2530            .map_or(self.state.updated_at, |event| event.at);
2531        anyhow::ensure!(
2532            approval_at > failed_at,
2533            "preparation retry requires a new explicit release after the failure"
2534        );
2535        self.state.prep_failure = None;
2536        self.state.prep_complete = Some(false);
2537        self.state
2538            .event("prep-retry", "operator approved retry of preparation");
2539        Ok(())
2540    }
2541
2542    /// Hand the runner the pause `magi serve`'s own shutdown watches.
2543    pub fn on_pause(&mut self, pause: Pause) {
2544        self.pause = pause;
2545    }
2546
2547    /// Hand the runner a second, independent pause: `magi serve`'s interrupt
2548    /// scheduler asking this one run - and no other - to park so a task
2549    /// marked [`crate::queue::Task::interrupt`] can run alone. See
2550    /// [`Pause`]'s own doc for why this is never [`Runner::on_pause`]'s
2551    /// handle.
2552    pub fn watch_interrupt(&mut self, pause: Pause) {
2553        self.interrupt = pause;
2554    }
2555
2556    /// Abandon this run's own open questions, once `status` has actually
2557    /// settled rather than merely paused.
2558    ///
2559    /// `Blocked` and `Stalled` are `RunStatus::resumable` — a human can pick
2560    /// either back up with the candidates, the review round and the seat
2561    /// sessions already on disk, so a question an implementer asked mid-round
2562    /// may still get a real answer read by a real resume. Only the statuses
2563    /// `resumable` excludes are actually final: the run merged, it reached
2564    /// `Ready` with nothing left to do, it failed outright with no
2565    /// established point to continue from, or every candidate agreed, with
2566    /// evidence, that nothing belonged in the worktree (`VerifiedNoop`). In
2567    /// every one of those the seat that asked is gone for good, exactly like
2568    /// the run being deleted under `magi run rm` - so the same cleanup
2569    /// applies, worded for what actually happened instead of "the run was
2570    /// deleted".
2571    ///
2572    /// Best-effort and silent on success: called from every place `status`
2573    /// can land on one of those three, including ones a resumed run revisits,
2574    /// so it must cost nothing when there was nothing open to begin with.
2575    fn settle_questions(&mut self) {
2576        if let Err(e) = ask::Questions::open().settle_run(&self.state.id, self.state.status) {
2577            tracing::warn!("abandon questions for {}: {e:#}", self.state.id);
2578        }
2579    }
2580
2581    /// The tail of the graph after a trustworthy tally: fold losers, review,
2582    /// gate, merge, and persist.
2583    fn finish_after_tally(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
2584        Box::pin(self.finish_after_tally_inner())
2585    }
2586
2587    async fn finish_after_tally_inner(&mut self) -> Result<()> {
2588        // Before the losers are folded: their branches are what the graft
2589        // reads from.
2590        self.graft().await?;
2591        if self.resource_halt()? {
2592            return Ok(());
2593        }
2594        self.fold_losers().await?;
2595        // Before review starts, and again right before the gate: a run's
2596        // review rounds can themselves take long enough for the base to move
2597        // a second time, and the gate is the one node whose "green" gets
2598        // acted on.
2599        self.sync_to_base().await?;
2600        if self.hold_base_sync().await? || self.resource_halt()? {
2601            return Ok(());
2602        }
2603        if self.state.status == RunStatus::AlreadyInBase {
2604            return Ok(());
2605        }
2606        self.review_loop().await?;
2607        if self.resource_halt()? {
2608            return Ok(());
2609        }
2610        self.sync_to_base().await?;
2611        if self.hold_base_sync().await? || self.resource_halt()? {
2612            return Ok(());
2613        }
2614        if self.state.status == RunStatus::AlreadyInBase {
2615            return Ok(());
2616        }
2617        self.gate().await?;
2618        self.merge().await?;
2619        if self.resource_halt()? {
2620            return Ok(());
2621        }
2622        self.state.save()?;
2623        Ok(())
2624    }
2625
2626    // ---------------------------------------------------------------- prep
2627
2628    /// Run `[worktree] setup` in a seat's fresh worktree. A failure blocks the
2629    /// run with the step and its output in the event; it is never swallowed.
2630    /// During `prep` (`in_prep`) the whole preparation is rolled back, so a
2631    /// resume starts over instead of finding candidates and missing seats.
2632    async fn setup_seat_worktree(
2633        &mut self,
2634        repo: &Path,
2635        wt: &Path,
2636        in_prep: bool,
2637        coordination: Option<&crate::repo_lock::SeatLease>,
2638    ) -> Result<()> {
2639        let result = match ensure_setup_config(&mut self.state, repo).await {
2640            Ok(()) => {
2641                worktree_setup::prepare_with(
2642                    &self.state.config,
2643                    repo,
2644                    wt,
2645                    crate::build_target::Coordination::Held(coordination),
2646                )
2647                .await
2648            }
2649            Err(e) => Err(e),
2650        };
2651        if let Err(e) = result {
2652            git::worktree_remove_clean(repo, wt).await.ok();
2653            if in_prep {
2654                self.rollback_prep(repo).await;
2655            }
2656            self.state.status = RunStatus::Blocked;
2657            self.state.event(
2658                "setup",
2659                format!("worktree setup failed in {}: {e:#}", wt.display()),
2660            );
2661            self.state.save()?;
2662            return Err(e);
2663        }
2664        Ok(())
2665    }
2666
2667    /// Undo everything `prep` created, so a resume re-runs it whole.
2668    async fn rollback_prep(&mut self, repo: &Path) {
2669        let root = self.state.worktree_root();
2670        for c in std::mem::take(&mut self.state.candidates) {
2671            if matches!(
2672                git::worktree_remove_clean(repo, &c.worktree).await,
2673                Ok(true)
2674            ) {
2675                git::branch_delete(repo, &c.branch).await.ok();
2676            } else {
2677                self.state.candidates.push(c);
2678            }
2679        }
2680        let seats = self.roles.judges.len().max(self.state.config.graph.judges);
2681        for j in 1..=seats {
2682            remove_read_seat_worktree(&mut self.state, &root.join(format!("judge-{j}")))
2683                .await
2684                .ok();
2685        }
2686        for k in 1..=self.state.config.graph.advisors {
2687            remove_read_seat_worktree(&mut self.state, &root.join(format!("advisor-{k}")))
2688                .await
2689                .ok();
2690        }
2691    }
2692
2693    async fn prep(&mut self) -> Result<()> {
2694        if let Some(reason) = &self.state.prep_failure {
2695            bail!(
2696                "candidate preparation previously failed: {reason}; correct the source before retrying"
2697            );
2698        }
2699        if self
2700            .state
2701            .prep_complete
2702            .unwrap_or(!self.state.candidates.is_empty())
2703        {
2704            return Ok(());
2705        }
2706        let repo = self.state.repo.clone();
2707        // Includes rollback, config, refs, checkout creation and setup. No
2708        // repository mutation may precede the real shared lock acquisition.
2709        let _coordination = self.coordinate(&repo).await?;
2710        let base = self.state.base_commit.clone();
2711        let plan = self.state.sources.plan(&repo, &base).await?;
2712        self.rollback_prep(&repo).await;
2713        if !self.state.candidates.is_empty() {
2714            bail!(
2715                "preparation rollback retained worktrees; recover their uncommitted work before retrying"
2716            );
2717        }
2718        self.state.prep_complete = Some(false);
2719        self.state.status = RunStatus::Prep;
2720        self.state.save()?;
2721        let repo = self.state.repo.clone();
2722        let start = plan.start.clone().unwrap_or_else(|| base.clone());
2723        let root = self.state.worktree_root();
2724        let labels = blind::assign_labels(self.roles.implementers.len(), self.state.seed);
2725
2726        // The hook is the write-time half of the blindness contract; the
2727        // presentation filter in `blind` is the half that cannot be bypassed.
2728        let hooks_dir = self.state.dir().join("hooks");
2729        if self.state.config.blind.commit_msg_hook {
2730            std::fs::create_dir_all(&hooks_dir)
2731                .with_context(|| format!("create {}", hooks_dir.display()))?;
2732            let script = blind::commit_msg_hook(&self.state.config.blind.strip_lines);
2733            let path = hooks_dir.join("commit-msg");
2734            std::fs::write(&path, script).with_context(|| format!("write {}", path.display()))?;
2735            make_executable(&path)?;
2736            // Ref-counted rather than a plain idempotent set: with more than
2737            // one run able to be in flight in the same repository at once
2738            // (see `Config::daemon.max_concurrent_runs`), a bare "already
2739            // true?" check cannot tell "another run of mine still needs
2740            // this" from "nobody does", and the run that happens to finish
2741            // first would disable the hook out from under a sibling still
2742            // relying on it.
2743            git::acquire_worktree_config(&repo).await?;
2744            self.state.enabled_worktree_config = true;
2745        }
2746
2747        // `[worktree] setup` hides its products per worktree, which needs the
2748        // same per-worktree config the hook does. Held until fold, like it.
2749        ensure_setup_config(&mut self.state, &repo).await?;
2750
2751        for (index, (spec, label)) in self
2752            .roles
2753            .implementers
2754            .clone()
2755            .into_iter()
2756            .zip(labels)
2757            .enumerate()
2758        {
2759            let branch = self.state.branch_for(label);
2760            let worktree = root.join(format!("cand-{label}"));
2761            // Persist intent before Git can leave a partially created tree.
2762            // Candidate registration follows setup, so it cannot inventory
2763            // crashes or refusals during creation itself.
2764            self.state.event(
2765                "prep-intent",
2766                serde_json::json!({
2767                    "branch": branch,
2768                    "worktree": worktree,
2769                    "start": start,
2770                    "picks": plan.picks,
2771                })
2772                .to_string(),
2773            );
2774            self.state.save()?;
2775            git::worktree_add_branch(&repo, &worktree, &branch, &start).await?;
2776            if self.state.config.blind.commit_msg_hook {
2777                git::set_worktree_hooks_path(&worktree, &hooks_dir).await?;
2778            }
2779            git::local_exclude(&worktree, "/.magi/").await?;
2780            if let Err(e) = worktree_setup::prepare_with(
2781                &self.state.config,
2782                &repo,
2783                &worktree,
2784                crate::build_target::Coordination::Held(_coordination.as_ref()),
2785            )
2786            .await
2787            {
2788                // Nothing of this prep may survive: a resume must start over,
2789                // not find half the candidates and skip the rest.
2790                git::worktree_remove_clean(&repo, &worktree).await.ok();
2791                git::branch_delete(&repo, &branch).await.ok();
2792                self.rollback_prep(&repo).await;
2793                self.state.status = RunStatus::Blocked;
2794                self.state
2795                    .event("prep", format!("worktree setup failed: {e:#}"));
2796                if !e.is::<crate::repo_lock::ResourceBlocked>() {
2797                    self.state.prep_failure = Some(format!("worktree setup failed: {e:#}"));
2798                }
2799                self.state.save()?;
2800                return Err(e);
2801            }
2802            self.state.candidates.push(Candidate {
2803                index,
2804                label,
2805                agent: spec.id.clone(),
2806                branch,
2807                worktree,
2808                summary: String::new(),
2809                stat: String::new(),
2810                files: 0,
2811                commits: 0,
2812                empty: false,
2813                failed: None,
2814                verified_noop: None,
2815                duration_ms: 0,
2816                folded: false,
2817            });
2818            self.state.save()?;
2819            for pick in &plan.picks {
2820                if let Err(e) = git::cherry_pick(&self.state.candidates[index].worktree, pick).await
2821                {
2822                    self.state.status = RunStatus::Blocked;
2823                    self.state.prep_failure = Some(format!("cannot apply referenced commit: {e}"));
2824                    self.state
2825                        .event("prep", format!("cannot apply referenced commit: {e}"));
2826                    self.state.save()?;
2827                    return Err(e);
2828                }
2829            }
2830        }
2831
2832        for j in 1..=self.roles.judges.len() {
2833            let wt = root.join(format!("judge-{j}"));
2834            if !wt.exists() {
2835                git::worktree_add_detached(&repo, &wt, &base).await?;
2836                self.setup_seat_worktree(&repo, &wt, true, _coordination.as_ref())
2837                    .await?;
2838            }
2839        }
2840
2841        // Disposable, detached checkouts for the design-deliberation stage's
2842        // advisor seats — the same shape as the judges' above, at the same
2843        // base commit, since advisors also only ever read. Sized off the
2844        // configured count directly rather than a resolved roster: unlike
2845        // `implementers`/`judges`/`reviewers`, advisor seats are resolved
2846        // lazily inside `advise` itself (see `Config::advisors`'s doc), so
2847        // `prep` has no `ResolvedRoles` field to read a count from here.
2848        if self.state.config.graph.advise {
2849            for k in 1..=self.state.config.graph.advisors {
2850                let wt = root.join(format!("advisor-{k}"));
2851                if !wt.exists() {
2852                    git::worktree_add_detached(&repo, &wt, &base).await?;
2853                    self.setup_seat_worktree(&repo, &wt, true, _coordination.as_ref())
2854                        .await?;
2855                }
2856            }
2857        }
2858
2859        // A judge cannot tell it is looking at its own patch — the seats keep
2860        // separate conversations — but a panel that shares agents with the
2861        // field is less independent than it looks, and that is worth saying out
2862        // loud once per run rather than leaving it in the config.
2863        let authors: Vec<&str> = self
2864            .roles
2865            .implementers
2866            .iter()
2867            .map(|a| a.id.as_str())
2868            .collect();
2869        let overlap: Vec<String> = self
2870            .roles
2871            .judges
2872            .iter()
2873            .enumerate()
2874            .filter(|(_, j)| authors.contains(&j.id.as_str()))
2875            .map(|(i, j)| format!("judge {} = {}", i + 1, j.id))
2876            .collect();
2877        if !overlap.is_empty() {
2878            let note = format!(
2879                "{} also authored a candidate; blind, but the panel is less \
2880                 independent than {} distinct agents would be",
2881                overlap.join(", "),
2882                self.roles.judges.len()
2883            );
2884            self.state.event("prep", note);
2885        }
2886
2887        self.state.event(
2888            "prep",
2889            format!(
2890                "{} candidates, {} judges, base {} ({})",
2891                self.state.candidates.len(),
2892                self.roles.judges.len(),
2893                &self.state.base_commit[..7.min(self.state.base_commit.len())],
2894                self.state.base_branch
2895            ),
2896        );
2897        self.state.prep_complete = Some(true);
2898        self.state.status = RunStatus::Implementing;
2899        self.state.save()?;
2900        Ok(())
2901    }
2902
2903    // -------------------------------------------------------------- advise
2904
2905    /// The design-deliberation stage: independent, read-only advisor seats
2906    /// each sketch a design before any implementer touches the repository,
2907    /// and (when at least one produced a usable proposal) a synthesis seat
2908    /// blends them into a brief `implement` carries in every candidate's
2909    /// prompt.
2910    ///
2911    /// `[graph] advise` is the on/off switch, on by default; `[graph]
2912    /// advisors` is the proposal count. Everything here is best-effort and
2913    /// non-fatal to the run: a misconfigured `[roles] advisors`, a roster
2914    /// that cannot reach quota, or a synthesis seat that produced nothing
2915    /// usable all leave `implement` exactly as it was before this stage
2916    /// existed — the task instruction alone — rather than failing the whole
2917    /// competition over an enrichment stage. Every outcome is still recorded
2918    /// as an event, so a run that got nothing from this stage says why.
2919    ///
2920    /// [`RunState::advise_attempted`] is this node's idempotency marker, the
2921    /// same role [`RunState::judge_skipped`] plays for `judge`: without it a
2922    /// resumed run whose stage failed would re-run it, and re-spend the
2923    /// agent calls, on every reentry before `implement`.
2924    ///
2925    /// Also skipped once any candidate shows implementation progress — the
2926    /// exact predicate `implement` itself uses to decide a candidate is no
2927    /// longer "todo" (see its own `todo` filter). `advise_attempted` alone
2928    /// is not enough: a run created by an older binary that predates this
2929    /// field deserializes it as `false` (`#[serde(default)]`), so resuming
2930    /// an already-`Implementing`-or-later run under this build would
2931    /// otherwise walk straight back through `prep` (a no-op once candidates
2932    /// exist) into this node and spawn every advisor seat against worktrees
2933    /// `prep` never recreated — after implementation has already started,
2934    /// which is exactly the invariant this stage exists to guarantee.
2935    async fn advise(&mut self) -> Result<()> {
2936        let implement_untouched = self
2937            .state
2938            .candidates
2939            .iter()
2940            .all(|c| c.commits == 0 && c.failed.is_none() && !c.empty);
2941        if !self.state.config.graph.advise || self.state.advise_attempted {
2942            return Ok(());
2943        }
2944        if !implement_untouched {
2945            self.state.event(
2946                "advise",
2947                "skipping the design-deliberation stage: at least one \
2948                 candidate already shows implementation progress, so this \
2949                 run is past the point the stage exists to run before"
2950                    .to_owned(),
2951            );
2952            self.state.advise_attempted = true;
2953            self.state.save()?;
2954            return Ok(());
2955        }
2956        let run_id = self.state.id.clone();
2957        let prompts = self.state.config.prompts.clone();
2958        let instruction = self.state.instruction.clone();
2959        let language = self.state.config.graph.language.clone();
2960        let root = self.state.worktree_root();
2961        let n = self.state.config.graph.advisors;
2962        let where_recorded = self.state.dir().join("run.json");
2963
2964        let seats = match self.state.config.advisors() {
2965            Ok(seats) if !seats.is_empty() => seats,
2966            Ok(_) => {
2967                self.state.event(
2968                    "advise",
2969                    format!(
2970                        "[graph] advisors is 0; skipping the design-deliberation \
2971                         stage and continuing without a synthesis brief (see {})",
2972                        where_recorded.display()
2973                    ),
2974                );
2975                self.state.advise_attempted = true;
2976                self.state.save()?;
2977                return Ok(());
2978            }
2979            Err(e) => {
2980                self.state.event(
2981                    "advise",
2982                    format!(
2983                        "could not resolve advisor seats ({e:#}); continuing \
2984                         without a design-deliberation brief (see {})",
2985                        where_recorded.display()
2986                    ),
2987                );
2988                self.state.advise_attempted = true;
2989                self.state.save()?;
2990                return Ok(());
2991            }
2992        };
2993
2994        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
2995        let artifacts = agent::artifacts_dir(&self.state.dir());
2996        let worktrees: Vec<PathBuf> = (1..=n).map(|k| root.join(format!("advisor-{k}"))).collect();
2997
2998        let mut jobs = Vec::new();
2999        for (i, spec) in seats.iter().cloned().enumerate() {
3000            let seat_key = format!("advisor-{}", i + 1);
3001            let seat = self.seat(&seat_key, &spec.id);
3002            jobs.push(SeatJob {
3003                prompt: prompt::advisor(&instruction, i + 1, seats.len(), &language),
3004                spec,
3005                seat,
3006                cwd: worktrees[i % worktrees.len()].clone(),
3007                timeout,
3008                allow_write: false,
3009                sessions: false,
3010                artifacts: artifacts.clone(),
3011                stem: seat_key,
3012                handover: None,
3013            });
3014        }
3015
3016        self.state.event(
3017            "advise",
3018            format!(
3019                "{} advisor seat(s) sketching a design in parallel",
3020                jobs.len()
3021            ),
3022        );
3023        let mut quota_losses = Vec::new();
3024        let cache = self.state.config.cache_dir();
3025        let ctx = WaveCtx {
3026            carry_seats: false,
3027            pauses: Some((&self.pause, &self.interrupt)),
3028            run: &run_id,
3029            node: "advise",
3030            prompts: &prompts,
3031            cache: cache.as_deref(),
3032            round: None,
3033        };
3034        let advisor_roster = self.state.config.advisor_roster().unwrap_or_default();
3035        let results = ask_json_wave::<Proposal>(
3036            jobs,
3037            Arc::clone(&self.sem),
3038            self.state.config.graph.retries,
3039            &advisor_roster,
3040            &ctx,
3041            &mut quota_losses,
3042            &mut self.state,
3043            &|p: &Proposal| p.validate(),
3044        )
3045        .await;
3046        if self.state.resource_block.is_some() {
3047            return self.stop_for_resource();
3048        }
3049        self.state.quota.extend(quota_losses);
3050
3051        let mut records = Vec::with_capacity(results.len());
3052        for (i, (seat, res, _attempts)) in results.into_iter().enumerate() {
3053            let agent_id = seat.agent.clone();
3054            self.state.seats.insert(seat.key.clone(), seat);
3055            match res {
3056                Ok((proposal, out)) => {
3057                    self.state
3058                        .event("advise", format!("advisor-{} proposed a design", i + 1));
3059                    records.push(advise::AdvisorRecord::proposed(
3060                        i + 1,
3061                        agent_id,
3062                        proposal,
3063                        out.duration_ms,
3064                    ));
3065                }
3066                Err(e) => {
3067                    self.state.event(
3068                        "advise",
3069                        format!("advisor-{} produced no usable proposal: {e:#}", i + 1),
3070                    );
3071                    records.push(advise::AdvisorRecord::failed(
3072                        i + 1,
3073                        agent_id,
3074                        e.to_string(),
3075                    ));
3076                }
3077            }
3078        }
3079
3080        let mut advice = advise::Advice {
3081            records,
3082            synthesis: None,
3083        };
3084        if advice.proposals().is_empty() {
3085            self.state.event(
3086                "advise",
3087                "no advisor produced a usable proposal; continuing without a \
3088                 synthesis brief"
3089                    .to_owned(),
3090            );
3091        } else {
3092            match self
3093                .synthesize_brief(
3094                    &advice,
3095                    &instruction,
3096                    &language,
3097                    &worktrees[0],
3098                    &artifacts,
3099                    &run_id,
3100                    &prompts,
3101                    cache.as_deref(),
3102                )
3103                .await
3104            {
3105                Ok(Some(text)) => {
3106                    self.state.event(
3107                        "advise",
3108                        "synthesized a design brief for the implementer".to_owned(),
3109                    );
3110                    advice.synthesis = Some(text);
3111                }
3112                Ok(None) => {
3113                    self.state.event(
3114                        "advise",
3115                        "the synthesis seat produced nothing usable; continuing \
3116                         without a design brief"
3117                            .to_owned(),
3118                    );
3119                }
3120                Err(e) => {
3121                    if e.is::<crate::repo_lock::ResourceBlocked>() {
3122                        return Err(e);
3123                    }
3124                    self.state.event(
3125                        "advise",
3126                        format!("could not synthesize a design brief: {e:#}"),
3127                    );
3128                }
3129            }
3130        }
3131        advise::apply_reflection(&mut advice);
3132
3133        self.state.advice = Some(advice);
3134        self.state.advise_attempted = true;
3135        self.state.save()?;
3136        Ok(())
3137    }
3138
3139    /// The synthesis seat: reads every advisor's proposal and blends them
3140    /// into the design brief `advise` stores on [`RunState::advice`]. Split
3141    /// out of [`Runner::advise`] only for readability — it is not called
3142    /// anywhere else.
3143    ///
3144    /// Picked the same way [`crate::talk`]'s standing conversation and
3145    /// [`crate::bump`]'s release-bump decision are: [`agent::pick`], with
3146    /// `[roles] synthesizer` checked first and [`agent::pick`]'s own default
3147    /// order (a claude seat, else the first runnable agent in roster order)
3148    /// used when that field is unset — see `[roles] synthesizer`'s own doc
3149    /// in [`crate::config`] for why a dedicated field exists here at all.
3150    #[allow(clippy::too_many_arguments)]
3151    async fn synthesize_brief(
3152        &mut self,
3153        advice: &advise::Advice,
3154        instruction: &str,
3155        language: &str,
3156        cwd: &Path,
3157        artifacts: &Path,
3158        run_id: &str,
3159        prompts: &Prompts,
3160        cache: Option<&Path>,
3161    ) -> Result<Option<String>> {
3162        let chain = agent::pick_chain(
3163            &self.state.config.agents,
3164            self.state.config.roles.synthesizer.as_ref(),
3165            &agent::installed,
3166            "synthesizer",
3167        )?;
3168        let proposals = advice.proposals();
3169        let mut prompt = prompt::with_overlay(
3170            prompt::synthesize_brief(instruction, &proposals, language),
3171            prompts.overlay("advise"),
3172        );
3173        if cache.is_some() {
3174            // This seat never writes, so it is never handed `CARGO_TARGET_DIR`
3175            // below — see `prompt::build_cache_note`'s doc for why telling a
3176            // read-only seat to build through the shared cache is exactly how
3177            // a sandbox's write refusal gets misread as a defect.
3178            prompt.push('\n');
3179            prompt.push_str(&prompt::build_cache_note("advise", false));
3180        }
3181        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge.max(1));
3182        // Each id is tried once, in order; a quota hit, error or unusable
3183        // answer moves to the next. The seat is single-turn (`sessions:
3184        // false`) and the prompt is the whole context, so a fallback agent
3185        // needs nothing carried over.
3186        let mut last = None;
3187        for (n, spec) in chain.iter().enumerate() {
3188            if n > 0 {
3189                self.state
3190                    .event("advise", format!("synthesis falling back to {}", spec.id));
3191            }
3192            let mut seat = self.seat("advise-synthesis", &spec.id);
3193            let wait = self.repository_wait();
3194            let outcome = wait
3195                .scope(agent::invoke(
3196                    spec,
3197                    &mut seat,
3198                    &Invocation {
3199                        coordination: self.state.config.coordination.as_ref(),
3200                        fetched_base: None,
3201                        cwd,
3202                        prompt: &prompt,
3203                        timeout,
3204                        allow_write: false,
3205                        sessions: false,
3206                        artifacts,
3207                        stem: &if n == 0 {
3208                            "advise-synthesis".to_owned()
3209                        } else {
3210                            format!("advise-synthesis-{}", spec.id)
3211                        },
3212                        run: run_id,
3213                        node: "advise",
3214                        cache_dir: None,
3215                        attachments: &[],
3216                        writable: &[],
3217                    },
3218                ))
3219                .await;
3220            if outcome.is_ok() {
3221                self.state.seats.insert(seat.key.clone(), seat);
3222            }
3223            let advance = agent::chain_advances(&outcome);
3224            last = Some(outcome);
3225            if !advance {
3226                break;
3227            }
3228        }
3229        // Exhausted: the last attempt's result is what a single failed seat
3230        // would have produced.
3231        let out = last.expect("a chain holds at least one agent")?;
3232        if !out.usable() {
3233            return Ok(None);
3234        }
3235        let text =
3236            verdict::section(&out.text, "synthesis").unwrap_or_else(|| out.text.trim().to_owned());
3237        Ok((!text.trim().is_empty()).then_some(text))
3238    }
3239
3240    // ----------------------------------------------------------- implement
3241
3242    async fn implement(&mut self) -> Result<()> {
3243        self.persist_candidates().await?;
3244        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
3245        // agent files with `magi task add` name the run that paid for it. The
3246        // prompt overlay is cloned alongside it because the waves borrow it
3247        // while `self` is mutably borrowed by the node's own bookkeeping.
3248        let run_id = self.state.id.clone();
3249        let prompts = self.state.config.prompts.clone();
3250        let todo: Vec<usize> = self
3251            .state
3252            .candidates
3253            .iter()
3254            .enumerate()
3255            .filter(|(_, c)| {
3256                (c.commits == 0 || self.state.interrupted_implementations.contains(&c.label))
3257                    && c.failed.is_none()
3258                    && !c.empty
3259            })
3260            .map(|(i, _)| i)
3261            .collect();
3262        if todo.is_empty() {
3263            return self.after_implement();
3264        }
3265        self.state.status = RunStatus::Implementing;
3266
3267        let language = self.state.config.graph.language.clone();
3268        let github_language = self.state.config.graph.github_language.clone();
3269        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
3270        let sessions = self.state.config.graph.sessions;
3271        let artifacts = agent::artifacts_dir(&self.state.dir());
3272        // The design-deliberation stage's blended brief, when `advise` found
3273        // one — carried into every implementer's prompt the same way
3274        // regardless of which candidate it is.
3275        let brief = self
3276            .state
3277            .advice
3278            .as_ref()
3279            .and_then(|a| a.synthesis.as_deref())
3280            .map(str::to_owned);
3281        let attachments = self.state.attachments.clone();
3282
3283        let mut jobs = Vec::new();
3284        for &i in &todo {
3285            let (index, label, worktree) = {
3286                let c = &self.state.candidates[i];
3287                (c.index, c.label, c.worktree.clone())
3288            };
3289            let spec = self.roles.implementers[index].clone();
3290            let seat_key = format!("impl-{label}");
3291            let seat = self.seat(&seat_key, &spec.id);
3292            let instruction = seeded_instruction(&self.state);
3293            jobs.push(SeatJob {
3294                spec,
3295                seat,
3296                prompt: prompt::implement_in(
3297                    &instruction,
3298                    &worktree.to_string_lossy(),
3299                    &language,
3300                    &github_language,
3301                    brief.as_deref(),
3302                    &attachments,
3303                ),
3304                cwd: worktree,
3305                timeout,
3306                allow_write: true,
3307                sessions,
3308                artifacts: artifacts.clone(),
3309                stem: format!("impl-{label}"),
3310                handover: None,
3311            });
3312        }
3313
3314        self.state.event(
3315            "implement",
3316            format!("{} candidates in parallel", jobs.len()),
3317        );
3318        // Kept so a seat whose CLI hung up can be asked again from the same
3319        // job: `wave` consumes what it is given. Mutable so `resume_seat_handovers`
3320        // can update a seat's own entry once a fallback agent takes it over —
3321        // `resume_unconfirmed_commands`, which reads `sent` afterward, must see
3322        // whichever agent actually answered, not the one that quota'd out.
3323        let mut sent = jobs.clone();
3324        let cache = self.state.config.cache_dir();
3325        let ctx = WaveCtx {
3326            carry_seats: false,
3327            pauses: Some((&self.pause, &self.interrupt)),
3328            run: &run_id,
3329            node: "implement",
3330            prompts: &prompts,
3331            cache: cache.as_deref(),
3332            round: None,
3333        };
3334        let mut results = wave(jobs, Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
3335        if !wave_blocked(&results) {
3336            self.resume_undelivered(&mut results, &sent, &prompts, &run_id)
3337                .await;
3338            self.resume_seat_handovers(&mut results, &mut sent, &prompts, &run_id)
3339                .await?;
3340            self.resume_unconfirmed_commands(&mut results, &sent, &prompts, &run_id)
3341                .await;
3342        }
3343        // Do not finalize failed candidates when the entire wave needs machine
3344        // recovery: leaving them pending resumes this node with its work intact.
3345        if !results.is_empty()
3346            && results
3347                .iter()
3348                .all(|(_, _, out)| matches!(out, AgentOutcome::Quota(_)))
3349        {
3350            let losses: Vec<_> = results
3351                .iter()
3352                .map(|(_, seat, out)| {
3353                    let AgentOutcome::Quota(o) = out else {
3354                        unreachable!()
3355                    };
3356                    QuotaLoss::from_report(seat.key.clone(), "implement", o.quota.as_ref())
3357                })
3358                .collect();
3359            self.state.quota.extend(losses.clone());
3360            for (_, seat, _) in results {
3361                self.state.seats.insert(seat.key.clone(), seat);
3362            }
3363            for &i in &todo {
3364                let label = self.state.candidates[i].label;
3365                self.state.interrupted_implementations.insert(label);
3366                self.state
3367                    .candidate_preservation
3368                    .insert(label, "machine outage awaiting persistence".into());
3369            }
3370            // Preserve partial edits too, while keeping every interrupted seat
3371            // pending even when its tree already contains an inherited patch.
3372            block_machine_outage(&mut self.state, "implement", &losses);
3373            self.state.save()?;
3374            self.persist_candidates().await?;
3375            for &i in &todo {
3376                self.state
3377                    .interrupted_implementations
3378                    .insert(self.state.candidates[i].label);
3379            }
3380            return self.stop_for_resource();
3381        }
3382        let resource_blocked = self.state.resource_block.is_some() || wave_blocked(&results);
3383
3384        let selected_failed = self.state.config.graph.selected_implementer.is_some()
3385            && results
3386                .iter()
3387                .any(|(_, _, out)| FailClass::of(out).is_some());
3388        let base_commit = self.state.base_commit.clone();
3389        let blind_cfg = self.state.config.blind.clone();
3390        let mut rejected_noops: Vec<(char, String)> = Vec::new();
3391        for (&i, (_wi, seat, out)) in todo.iter().zip(results) {
3392            if matches!(out, AgentOutcome::ResourceBlocked(_)) {
3393                // Executed turns interrupted by disk pressure already carry
3394                // a preservation barrier from wave. Admission-only waits do
3395                // not. Keep the interrupted seat's session for recovery too.
3396                if self
3397                    .state
3398                    .candidate_preservation
3399                    .contains_key(&self.state.candidates[i].label)
3400                {
3401                    self.state.seats.insert(seat.key.clone(), seat);
3402                }
3403                continue;
3404            }
3405            let seat_key = seat.key.clone();
3406            // A quota fallback (`resume_seat_handovers`) may have handed this
3407            // seat to a different agent than the one `prep` recorded on the
3408            // candidate; the stats tables and any later fixer-defaults-to-
3409            // winner's-author lookup must credit whoever actually answered —
3410            // unless every fallback also quota'd out, in which case nobody
3411            // actually answered and crediting the last agent tried would
3412            // erase every earlier agent's own quota loss from the stats
3413            // tables instead of just this one seat's.
3414            let agent = seat.agent.clone();
3415            let exhausted_the_fallback_chain = FailClass::of(&out).is_some();
3416            self.state.seats.insert(seat.key.clone(), seat);
3417            let label = self.state.candidates[i].label;
3418            let worktree = self.state.candidates[i].worktree.clone();
3419            self.state.interrupted_implementations.remove(&label);
3420
3421            let (sanitized_summary, duration, failed, verified_claim) = match out {
3422                AgentOutcome::Ok(o) => {
3423                    let text = verdict::section(&o.text, "summary").unwrap_or(o.text.clone());
3424                    let failed = (!o.usable()).then(|| {
3425                        if o.timed_out {
3426                            "agent timed out".to_owned()
3427                        } else {
3428                            format!(
3429                                "agent exited with {}",
3430                                crate::notices::exit_status(o.exit_code)
3431                            )
3432                        }
3433                    });
3434                    let sanitized_summary = blind::sanitize_prose(&text, &blind_cfg);
3435                    let verified_claim = match verified_noop_claim_in_worktree(
3436                        failed.is_none(),
3437                        &o.commands,
3438                        &text,
3439                        &worktree,
3440                        &base_commit,
3441                    )
3442                    .await
3443                    {
3444                        NoopClaimVerdict::Accepted => {
3445                            if matches!(
3446                                verdict::parse_verified_noop(&sanitized_summary),
3447                                Some(Ok(_))
3448                            ) {
3449                                Some(sanitized_summary.clone())
3450                            } else {
3451                                rejected_noops.push((
3452                                    label,
3453                                    "structured NO CHANGE NEEDED summary became invalid after blind sanitization".to_owned(),
3454                                ));
3455                                None
3456                            }
3457                        }
3458                        NoopClaimVerdict::Rejected(reason) => {
3459                            rejected_noops.push((label, reason));
3460                            None
3461                        }
3462                        NoopClaimVerdict::Absent => None,
3463                    };
3464                    (sanitized_summary, o.duration_ms, failed, verified_claim)
3465                }
3466                // Left un-resumed by `resume_undelivered` (a dirty tree
3467                // already rescues the work, or there was no session left to
3468                // resume into) — reported like the ordinary failure it is,
3469                // never as if `o.text` (the CLI's raw error JSON) were an
3470                // answer.
3471                AgentOutcome::Dropped(o) => {
3472                    let why = o
3473                        .dropped
3474                        .as_ref()
3475                        .map(|d| d.why.as_str())
3476                        .unwrap_or("the CLI ended the stream without delivering its answer");
3477                    (
3478                        String::new(),
3479                        o.duration_ms,
3480                        Some(format!("the CLI dropped the stream ({why})")),
3481                        None,
3482                    )
3483                }
3484                AgentOutcome::Quota(o) => {
3485                    self.state.quota.push(QuotaLoss::from_report(
3486                        seat_key,
3487                        "implement",
3488                        o.quota.as_ref(),
3489                    ));
3490                    (
3491                        String::new(),
3492                        o.duration_ms,
3493                        Some("rate limited (quota); produced no change".to_owned()),
3494                        None,
3495                    )
3496                }
3497                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
3498                    (String::new(), 0, Some(e), None)
3499                }
3500            };
3501
3502            // Save every completed turn before any fallible Git operation. A failed
3503            // rescue must not erase the reply or prevent collection of other seats.
3504            let c = &mut self.state.candidates[i];
3505            if !exhausted_the_fallback_chain {
3506                c.agent = agent;
3507            }
3508            c.summary = sanitized_summary;
3509            c.duration_ms = duration;
3510            c.failed = failed;
3511            c.verified_noop = verified_claim;
3512            self.state
3513                .candidate_preservation
3514                .insert(label, "awaiting persistence".to_owned());
3515        }
3516        self.state.save()?;
3517        self.persist_candidates().await?;
3518
3519        let mut recorded_rejection = false;
3520        for (label, reason) in rejected_noops {
3521            if self.state.interrupted_implementations.contains(&label) {
3522                continue;
3523            }
3524            if let Some(c) = self.state.candidates.iter_mut().find(|c| c.label == label)
3525                && c.empty
3526            {
3527                c.verified_noop = None;
3528                c.failed
3529                    .get_or_insert_with(|| format!("no-op claim rejected: {reason}"));
3530                self.state.event(
3531                    "implement",
3532                    format!("candidate {label}: rejected NO CHANGE NEEDED claim: {reason}"),
3533                );
3534                recorded_rejection = true;
3535            }
3536        }
3537        if recorded_rejection {
3538            self.state.save()?;
3539        }
3540
3541        if resource_blocked {
3542            return self.stop_for_resource();
3543        }
3544        if selected_failed {
3545            self.state.status = RunStatus::Blocked;
3546            self.state.event("implement", "selected implementer failed or hit quota; holding without fallback, review or publication");
3547            self.state.save()?;
3548            bail!(
3549                "selected implementer unavailable or quota-limited; restore availability and explicitly release the task"
3550            );
3551        }
3552        self.after_implement()
3553    }
3554
3555    /// Retry only persistence after a completed implementation turn.
3556    async fn persist_candidates(&mut self) -> Result<()> {
3557        let labels: Vec<_> = self.state.candidate_preservation.keys().copied().collect();
3558        for label in labels {
3559            let i = self
3560                .state
3561                .candidates
3562                .iter()
3563                .position(|c| c.label == label)
3564                .context("pending candidate is missing")?;
3565            let c = self.state.candidates[i].clone();
3566            let interrupted = self.state.interrupted_implementations.contains(&label);
3567            let result = async {
3568                let wait = crate::repo_lock::WaitPolicy::new(
3569                    Duration::from_secs(self.state.config.graph.timeout_resource_wait),
3570                    || false,
3571                );
3572                let _coordination =
3573                    coordinate_operation(&mut self.state, &c.worktree, &wait).await?;
3574                // Best effort evidence requires no index writes. A successful snapshot
3575                // never authorizes removal of a tree whose rescue failed.
3576                if let Err(e) = git::snapshot_uncommitted(
3577                    &c.worktree,
3578                    &self
3579                        .state
3580                        .dir()
3581                        .join("artifacts")
3582                        .join(format!("candidate-{label}-recovery")),
3583                )
3584                .await
3585                {
3586                    self.state.event(
3587                        "preserve",
3588                        format!("candidate {label} snapshot incomplete: {e:#}"),
3589                    );
3590                }
3591                let rescued = git::rescue_commit(
3592                    &c.worktree,
3593                    &format!("magi: candidate {label} (uncommitted work)"),
3594                )
3595                .await?;
3596                self.state.note_withheld("implement", &rescued.withheld);
3597                let base = &self.state.base_commit;
3598                let commits = git::commits_ahead(&c.worktree, base, "HEAD").await?;
3599                let patch = git::diff(&c.worktree, base, "HEAD").await?;
3600                let stat = git::diff_stat(&c.worktree, base, "HEAD").await?;
3601                let files = git::changed_files(&c.worktree, base, "HEAD").await?.len();
3602                write_artifact(&self.state, &format!("cand-{label}.patch"), &patch)?;
3603                if c.empty && commits > 0 && !patch.trim().is_empty()
3604                    && (self.state.judge_skipped || !self.state.judgements.is_empty()
3605                        || !self.state.deliberation.is_empty() || !self.state.votes.is_empty()
3606                        || self.state.tally.is_some())
3607                {
3608                    // Keep the old classification and pending marker so every
3609                    // retry stops too. Retain decisions as recovery evidence;
3610                    // only a supported recovery operation may replace them.
3611                    bail!("candidate {label} changes the judged candidate set; supported recovery and fresh judging are required before continuing");
3612                }
3613                let c = &mut self.state.candidates[i];
3614                c.commits = commits;
3615                c.stat = stat;
3616                c.files = files;
3617                let no_changes = commits == 0 || patch.trim().is_empty();
3618                c.empty = no_changes && !interrupted;
3619                if interrupted && no_changes {
3620                    c.failed = None;
3621                    c.verified_noop = None;
3622                }
3623                if !c.empty {
3624                    c.failed = None;
3625                    c.verified_noop = None;
3626                }
3627                self.state.event(
3628                    "preserve",
3629                    format!("candidate {label}: {files} files, {commits} commits"),
3630                );
3631                Ok::<_, anyhow::Error>(())
3632            }
3633            .await;
3634            match result {
3635                Ok(()) => {
3636                    self.state.candidate_preservation.remove(&label);
3637                    if !interrupted || self.state.candidates[i].files > 0 {
3638                        self.state.interrupted_implementations.remove(&label);
3639                    }
3640                }
3641                Err(e) => {
3642                    let reason = format!("candidate {label} preservation failed: {e:#}");
3643                    self.state.event("preserve", &reason);
3644                    self.state.candidate_preservation.insert(label, reason);
3645                }
3646            }
3647            if self.state.candidate_preservation.is_empty()
3648                && self.state.status == RunStatus::Blocked
3649                && self.state.candidates.iter().all(|c| c.failed.is_none())
3650            {
3651                // Persist the recovered phase with the cleared pending marker;
3652                // a crash between saves must not turn this into a selected-seat
3653                // failure hold on the next resume.
3654                self.state.status = RunStatus::Implementing;
3655                self.state.event(
3656                    "preserve",
3657                    "candidate persistence recovered; implementation can continue",
3658                );
3659            }
3660            self.state.save()?;
3661        }
3662        if !self.state.candidate_preservation.is_empty() {
3663            self.state.status = RunStatus::Blocked;
3664            self.state.save()?;
3665            bail!(
3666                "candidate preservation incomplete; retain worktrees and artifacts, repair persistence and resume this run"
3667            );
3668        }
3669        Ok(())
3670    }
3671
3672    /// Ask again, once, for work a CLI did and then failed to hand over.
3673    ///
3674    /// [`agent::dropped_stream`] recognises the one shape observed: an error
3675    /// status with an empty response and a usage report showing output tokens,
3676    /// i.e. **billed work with nothing delivered**. Run 26c7's candidate B was
3677    /// seven minutes and 14,267 output tokens that arrived as an empty
3678    /// candidate, because `agy`'s own subscriber fell behind and hung up.
3679    ///
3680    /// Two conditions, and both matter:
3681    ///
3682    /// - **Only when the tree is untouched.** Often the agent has already
3683    ///   written its files and only the closing message was lost; the rescue
3684    ///   commit below picks that up and there is nothing to ask for. Re-asking
3685    ///   then would pay for a second implementation of work already on disk.
3686    /// - **Once.** A CLI that drops one stream can drop the next, and this
3687    ///   node is the most expensive in the graph.
3688    ///
3689    /// The re-ask is a resume, not a re-run: `has_context` is true because the
3690    /// dropped reply still carried its `conversation_id`, so the seat is asked
3691    /// to finish what it was doing rather than sent the whole task again. It
3692    /// therefore gets a nudge's budget ([`retry_budget`]) - a quarter of the
3693    /// node's - for the same reason a re-ranked judge does: restating finished
3694    /// work is not the work.
3695    ///
3696    /// Unlike a quota this is worth retrying at all: a rate limit fails the
3697    /// same way until it resets, while an abandoned conversation is still
3698    /// there to be picked up.
3699    async fn resume_undelivered(
3700        &mut self,
3701        results: &mut [(usize, SeatState, AgentOutcome)],
3702        sent: &[SeatJob],
3703        prompts: &Prompts,
3704        run_id: &str,
3705    ) {
3706        for (wi, seat, out) in results.iter_mut() {
3707            let Some(dropped) = (match &*out {
3708                AgentOutcome::Dropped(o) => o.dropped.clone(),
3709                _ => None,
3710            }) else {
3711                continue;
3712            };
3713            let Some(job) = sent.get(*wi) else { continue };
3714            // Already on disk? Then only the closing message was lost.
3715            if !git::is_clean(&job.cwd).await.unwrap_or(true) {
3716                self.state.event(
3717                    "implement",
3718                    format!(
3719                        "{}: the CLI dropped the stream after {} output tokens ({}), but the \
3720                         work is in the tree",
3721                        seat.key, dropped.output_tokens, dropped.why
3722                    ),
3723                );
3724                continue;
3725            }
3726            // The re-ask only makes sense as a resume: `resume_after_drop`
3727            // says nothing about the task, trusting the seat to still hold it.
3728            // Without a session to resume — sessions disabled, or this CLI's
3729            // drop shape happened not to carry a session id — that prompt
3730            // would open a brand-new conversation with no context at all,
3731            // which is worse than leaving this as the ordinary failure it
3732            // already is.
3733            if !has_context(&job.spec, seat, job.sessions) {
3734                self.state.event(
3735                    "implement",
3736                    format!(
3737                        "{}: the CLI dropped the stream after {} output tokens ({}), but there \
3738                         is no session left to resume",
3739                        seat.key, dropped.output_tokens, dropped.why
3740                    ),
3741                );
3742                continue;
3743            }
3744            self.state.event(
3745                "implement",
3746                format!(
3747                    "{}: the CLI dropped the stream after {} output tokens ({}); resuming the \
3748                     conversation",
3749                    seat.key, dropped.output_tokens, dropped.why
3750                ),
3751            );
3752            let mut retry = job.clone();
3753            retry.seat = seat.clone();
3754            retry.prompt = prompt::resume_after_drop(&dropped.why);
3755            retry.timeout = retry_budget(job.timeout, true);
3756            retry.stem = format!("{}-resume", job.stem);
3757            let cache = self.state.config.cache_dir();
3758            let ctx = WaveCtx {
3759                carry_seats: false,
3760                pauses: Some((&self.pause, &self.interrupt)),
3761                run: run_id,
3762                node: "implement",
3763                prompts,
3764                cache: cache.as_deref(),
3765                round: None,
3766            };
3767            let (resumed_seat, resumed) =
3768                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
3769            *seat = resumed_seat;
3770            *out = resumed;
3771        }
3772    }
3773
3774    /// Fall an implement seat through to the next untried agent in the
3775    /// implementer roster when it lost to quota — or, since the handover was
3776    /// generalised, to a timeout or an ordinary failure (see [`FailClass`] and
3777    /// [`should_hand_over`] for when a non-quota failure stops the chain), the
3778    /// quota path itself being unchanged — instead of leaving the
3779    /// seat's loss final the moment one agent's account runs dry.
3780    ///
3781    /// Solo runs (`graph.implementers = 1`, `daemon::apply_solo`'s forced shape)
3782    /// are the motivating case: `Config::resolve_roles`'s `implementers`
3783    /// truncates to the single slot rotation picked, so a solo task whose one
3784    /// implementer hits quota mid-run used to have nothing else to try. This
3785    /// walks [`ResolvedRoles::implementer_roster`] instead — the untruncated,
3786    /// unrotated roster — which is the only place the *other* candidates in
3787    /// the machine's roster still exist once `implementers` has been cut down
3788    /// to size.
3789    ///
3790    /// Walks forward from just past the seat's own original position in the
3791    /// roster, never wrapping back to the front: a later candidate slot (say
3792    /// `beta`, the roster's second entry) must fall through to the *next*
3793    /// entry (`gamma`) on its own quota loss, not back to `alpha`, which is
3794    /// almost certainly a different candidate's own agent already — and once
3795    /// the roster's tail is exhausted there is nothing left to fall through
3796    /// to for *this* seat, wrapping or not. Tried by `spec.id`, never the
3797    /// whole [`AgentSpec`]: a roster with the same id named twice must not
3798    /// let this retry that id forever. The loop keeps falling through until
3799    /// an attempt lands something other than `Quota` or the roster's tail
3800    /// runs out of untried ids, at which point the seat is left exactly as
3801    /// `implement`'s own `AgentOutcome::Quota` arm already handles it: one
3802    /// `QuotaLoss` recorded, the candidate failed/empty.
3803    ///
3804    /// `sent` is taken mutably and updated with the fallback agent's spec:
3805    /// `resume_unconfirmed_commands`, which runs after this and also reads
3806    /// `sent`, must see whichever agent actually ended up answering the seat
3807    /// — reading the stale, original spec there would check session
3808    /// eligibility against the wrong CLI and could hand a fallback agent's
3809    /// session id to the agent that just lost the seat to quota.
3810    ///
3811    /// Every fallback gets a fresh [`SeatState`], never the quota'd seat's own
3812    /// — `self.seat` only reuses state when the agent id is unchanged, so
3813    /// handing it a different id already gets this for free. Reusing the old
3814    /// seat would resume a different CLI's session as if it were a
3815    /// continuation of this one.
3816    ///
3817    /// Unlike [`Runner::resume_undelivered`], not gated on a clean worktree:
3818    /// a quota loss cuts an agent off mid-turn, so anything already in the
3819    /// tree is unfinished work, not a completed candidate a re-ask would pay
3820    /// for twice. A dirty tree is rescued into a commit first (the same
3821    /// neutral-identity rescue `implement`'s own outcome loop gives every
3822    /// candidate) so the next agent starts clean.
3823    ///
3824    /// The new agent gets the implementer's full prompt and full
3825    /// `timeout_implement` budget, not `resume_after_drop`'s nudge-sized one:
3826    /// it has no session and no context, and is implementing the task from
3827    /// nothing, unlike a resumed drop which is only restating work already
3828    /// done.
3829    ///
3830    /// Every intermediate `Quota` this loop absorbs is folded into a plain
3831    /// `implement` event, never into `self.state.quota` — that is what
3832    /// `daemon.rs`'s own backoff reads to decide a run's task attempt should
3833    /// go unspent, and a seat that ultimately recovered on its second or
3834    /// third agent is not the stalled panel that check exists to catch. Only
3835    /// the final, unrecovered `Quota` (once the roster runs out) ever reaches
3836    /// `self.state.quota`, via the ordinary `AgentOutcome::Quota` arm the
3837    /// outcome loop already has — this helper never pushes to it itself.
3838    async fn resume_seat_handovers(
3839        &mut self,
3840        results: &mut [(usize, SeatState, AgentOutcome)],
3841        sent: &mut [SeatJob],
3842        prompts: &Prompts,
3843        run_id: &str,
3844    ) -> Result<()> {
3845        let instruction = seeded_instruction(&self.state);
3846        let language = self.state.config.graph.language.clone();
3847        let github_language = self.state.config.graph.github_language.clone();
3848        let brief = self
3849            .state
3850            .advice
3851            .as_ref()
3852            .and_then(|a| a.synthesis.as_deref())
3853            .map(str::to_owned);
3854        let attachments = self.state.attachments.clone();
3855        for (wi, seat, out) in results.iter_mut() {
3856            // Who holds the other candidate seats of this wave right now
3857            // (earlier handovers already written back to `sent`).
3858            let others: BTreeSet<String> = sent
3859                .iter()
3860                .enumerate()
3861                .filter(|(j, _)| j != wi)
3862                .map(|(_, j)| j.spec.id.clone())
3863                .collect();
3864            let Some(job) = sent.get_mut(*wi) else {
3865                continue;
3866            };
3867            // Where the seat's own original agent sits in the roster — the
3868            // fallback walk starts just past here, never at the front, so a
3869            // later candidate slot's quota loss does not fall back onto an
3870            // earlier slot's own agent.
3871            let start = self
3872                .roles
3873                .implementer_roster
3874                .iter()
3875                .position(|s| s.id == job.spec.id)
3876                .unwrap_or(0);
3877            let mut tried: BTreeSet<String> = BTreeSet::from([job.spec.id.clone()]);
3878            let mut fallback_attempt = 0usize;
3879            let mut prev: Option<FailClass> = None;
3880            while let Some(cur) = FailClass::of(&*out) {
3881                if !should_hand_over(prev.as_ref(), &cur) {
3882                    break;
3883                }
3884                let Some(next) =
3885                    pick_successor(&self.roles.implementer_roster, start, &tried, None, &others)
3886                        .cloned()
3887                else {
3888                    break;
3889                };
3890                tried.insert(next.id.clone());
3891                fallback_attempt += 1;
3892
3893                let coordination = self.coordinate(&job.cwd).await?;
3894                if let Ok(r) = git::rescue_commit(
3895                    &job.cwd,
3896                    &format!(
3897                        "magi: candidate {} (uncommitted work before {} fallback)",
3898                        seat.key,
3899                        if cur == FailClass::Quota {
3900                            "quota"
3901                        } else {
3902                            "handover"
3903                        }
3904                    ),
3905                )
3906                .await
3907                {
3908                    self.state.note_withheld("implement", &r.withheld);
3909                }
3910                drop(coordination);
3911
3912                record_handover(
3913                    &mut self.state,
3914                    "implement",
3915                    &seat.key,
3916                    &seat.agent,
3917                    &next.id,
3918                    &cur,
3919                    &fail_reason(&*out),
3920                );
3921                prev = Some(cur.clone());
3922
3923                let new_seat = handover_seat(&seat.key, &next.id, self.state.next_seat_seed());
3924                self.state.seats.insert(seat.key.clone(), new_seat.clone());
3925                // Kept in sync on `sent` itself, not just the local retry: a
3926                // later helper (`resume_unconfirmed_commands`) reads `sent`
3927                // after this one returns and must see whichever agent is now
3928                // occupying the seat, not the one that just quota'd out —
3929                // otherwise it would judge session/continuation eligibility
3930                // by the wrong CLI and could resend a fallback's session id
3931                // to the agent that lost it the seat in the first place.
3932                job.spec = next.clone();
3933                let mut retry = job.clone();
3934                retry.seat = new_seat;
3935                retry.prompt = prompt::implement_in(
3936                    &instruction,
3937                    &job.cwd.to_string_lossy(),
3938                    &language,
3939                    &github_language,
3940                    brief.as_deref(),
3941                    &attachments,
3942                );
3943                retry.stem = format!("{}-{}-{}", job.stem, cur.stem_word(), next.id);
3944                let cache = self.state.config.cache_dir();
3945                let ctx = WaveCtx {
3946                    carry_seats: false,
3947                    pauses: Some((&self.pause, &self.interrupt)),
3948                    run: run_id,
3949                    node: "implement",
3950                    prompts,
3951                    cache: cache.as_deref(),
3952                    round: None,
3953                };
3954                let (fallback_seat, fallback_out) = run_one(
3955                    retry,
3956                    Arc::clone(&self.sem),
3957                    &ctx,
3958                    &mut self.state,
3959                    fallback_attempt,
3960                )
3961                .await;
3962                *seat = fallback_seat;
3963                *out = fallback_out;
3964            }
3965        }
3966        Ok(())
3967    }
3968
3969    /// Ask an implement seat's own CLI to confirm what it started, once, when
3970    /// its reply reported a command whose completion status it never
3971    /// confirmed — see [`has_unconfirmed_command`]'s own doc for exactly what
3972    /// that does and does not mean.
3973    ///
3974    /// The completion contract this task asks for, extended to `implement`
3975    /// with the same signal `continue_fix_report` reads for the fixer,
3976    /// rather than a keyword search over the reply or a hard requirement on
3977    /// `## SUMMARY`'s presence — the shape behind fb35, 9566 and e185, where
3978    /// a candidate's CLI turn ended cleanly while a test run it had started
3979    /// had not. A short, ordinary reply with no `## SUMMARY` and no commands
3980    /// named in it at all is untouched by this: `commands` is empty, so
3981    /// there is nothing to be unconfirmed.
3982    ///
3983    /// Unlike `resume_undelivered`, not gated on the tree being untouched:
3984    /// this is not about recovering edits that might already be on disk, it
3985    /// is about a result the seat itself never vouched for, which resuming
3986    /// asks for regardless of what the tree already holds. Bounded to one
3987    /// attempt for the same reason `resume_undelivered` is — this is the
3988    /// most expensive node in the graph — and a seat that still cannot
3989    /// confirm on that attempt is left as whatever its (possibly still
3990    /// unconfirmed) reply says; this does not invent a new "failed" reason
3991    /// for a candidate that otherwise produced a real, committed change.
3992    async fn resume_unconfirmed_commands(
3993        &mut self,
3994        results: &mut [(usize, SeatState, AgentOutcome)],
3995        sent: &[SeatJob],
3996        prompts: &Prompts,
3997        run_id: &str,
3998    ) {
3999        for (wi, seat, out) in results.iter_mut() {
4000            let AgentOutcome::Ok(o) = &*out else {
4001                continue;
4002            };
4003            if !has_unconfirmed_command(&o.commands) {
4004                continue;
4005            }
4006            let Some(job) = sent.get(*wi) else { continue };
4007            if !has_context(&job.spec, seat, job.sessions) {
4008                self.state.event(
4009                    "implement",
4010                    format!(
4011                        "{}: the reply named a command whose own CLI never confirmed the exit \
4012                         status of, but there is no session left to resume",
4013                        seat.key
4014                    ),
4015                );
4016                continue;
4017            }
4018            self.state.event(
4019                "implement",
4020                format!(
4021                    "{}: the reply named a command whose own CLI never confirmed the exit \
4022                     status of; resuming the conversation",
4023                    seat.key
4024                ),
4025            );
4026            let mut retry = job.clone();
4027            retry.seat = seat.clone();
4028            retry.prompt = prompt::resume_incomplete(
4029                "a command in your last reply had no confirmed exit status",
4030            );
4031            retry.timeout = retry_budget(job.timeout, true);
4032            retry.stem = format!("{}-confirm", job.stem);
4033            let cache = self.state.config.cache_dir();
4034            let ctx = WaveCtx {
4035                carry_seats: false,
4036                pauses: Some((&self.pause, &self.interrupt)),
4037                run: run_id,
4038                node: "implement",
4039                prompts,
4040                cache: cache.as_deref(),
4041                round: None,
4042            };
4043            let (resumed_seat, resumed) =
4044                run_one(retry, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
4045            *seat = resumed_seat;
4046            *out = resumed;
4047        }
4048    }
4049
4050    /// Ask the fixer's own seat again, up to [`MAX_FIX_CONTINUATIONS`] times,
4051    /// when its CLI turn ended cleanly (`AgentOutcome::Ok`) but the reply held
4052    /// no [`FixReport`] — see [`MAX_FIX_CONTINUATIONS`]'s own doc for the run
4053    /// that motivated this.
4054    ///
4055    /// Not the same gap as an unparsable *shape*, which [`ask_json_wave`]'s
4056    /// own nudge loop already covers for judge/review/vote seats, and not a
4057    /// dropped stream, which [`Runner::resume_undelivered`] covers for
4058    /// implement seats: here the CLI turn genuinely finished while the node's
4059    /// own work — the fixer's account of what it did — had not. Gated purely
4060    /// on `extract_json::<FixReport>` having failed on an otherwise-usable
4061    /// reply, never on any wording in it, so a fixer whose valid, first-try
4062    /// `FixReport` happens to mention having waited on a background test is
4063    /// never resumed — the `Ok(report)` branch at the call site returns
4064    /// before this is ever invoked.
4065    ///
4066    /// Same discipline as `resume_undelivered`: a nudge-sized timeout per
4067    /// attempt ([`retry_budget`]), nothing attempted once the session is
4068    /// gone, and a quota hit ends the loop immediately rather than retrying a
4069    /// rate limit that fails the same way again.
4070    async fn continue_fix_report(
4071        &mut self,
4072        mut seat: SeatState,
4073        parse_err: String,
4074        job: &SeatJob,
4075        prompts: &Prompts,
4076        run_id: &str,
4077        round: usize,
4078    ) -> (
4079        SeatState,
4080        Option<FixReport>,
4081        Option<String>,
4082        ContinuationRecord,
4083    ) {
4084        let mut last_err = parse_err;
4085        let mut cumulative_wait_ms = 0u64;
4086        let mut attempts = 0usize;
4087        loop {
4088            if !has_context(&job.spec, &seat, job.sessions) {
4089                self.state.event(
4090                    "fix",
4091                    format!(
4092                        "round {round}: fixer's reply had no adoption report ({last_err}); no \
4093                         session left to resume into"
4094                    ),
4095                );
4096                let outcome = if attempts == 0 {
4097                    ContinuationOutcome::NoSession
4098                } else {
4099                    ContinuationOutcome::Exhausted
4100                };
4101                return (
4102                    seat,
4103                    None,
4104                    Some(format!("unparsable fix report: {last_err}")),
4105                    ContinuationRecord {
4106                        attempts,
4107                        cumulative_wait_ms,
4108                        outcome,
4109                    },
4110                );
4111            }
4112            if attempts >= MAX_FIX_CONTINUATIONS {
4113                self.state.event(
4114                    "fix",
4115                    format!(
4116                        "round {round}: fixer's reply still had no adoption report after \
4117                         {attempts} continuation(s) ({last_err}); giving up"
4118                    ),
4119                );
4120                return (
4121                    seat,
4122                    None,
4123                    Some(format!(
4124                        "unparsable fix report after {attempts} continuation(s): {last_err}"
4125                    )),
4126                    ContinuationRecord {
4127                        attempts,
4128                        cumulative_wait_ms,
4129                        outcome: ContinuationOutcome::Exhausted,
4130                    },
4131                );
4132            }
4133            attempts += 1;
4134            self.state.event(
4135                "fix",
4136                format!(
4137                    "round {round}: fixer's reply had no adoption report ({last_err}); resuming \
4138                     the conversation (attempt {attempts}/{MAX_FIX_CONTINUATIONS})"
4139                ),
4140            );
4141            let mut retry = job.clone();
4142            retry.seat = seat.clone();
4143            retry.prompt = prompt::resume_incomplete(&last_err);
4144            retry.timeout = retry_budget(job.timeout, true);
4145            retry.stem = format!("{}-continue{attempts}", job.stem);
4146            let cache = self.state.config.cache_dir();
4147            let ctx = WaveCtx {
4148                carry_seats: false,
4149                pauses: Some((&self.pause, &self.interrupt)),
4150                run: run_id,
4151                node: "fix",
4152                prompts,
4153                cache: cache.as_deref(),
4154                round: Some(round),
4155            };
4156            let (resumed_seat, resumed_out) = run_one(
4157                retry,
4158                Arc::clone(&self.sem),
4159                &ctx,
4160                &mut self.state,
4161                attempts,
4162            )
4163            .await;
4164            seat = resumed_seat;
4165            match resumed_out {
4166                AgentOutcome::Ok(o) => {
4167                    cumulative_wait_ms += o.duration_ms;
4168                    match verdict::extract_json::<FixReport>(&o.text) {
4169                        Ok(report) if !has_unconfirmed_command(&o.commands) => {
4170                            self.state.event(
4171                                "fix",
4172                                format!(
4173                                    "round {round}: fixer's adoption report recovered after \
4174                                     {attempts} continuation(s)"
4175                                ),
4176                            );
4177                            return (
4178                                seat,
4179                                Some(report),
4180                                None,
4181                                ContinuationRecord {
4182                                    attempts,
4183                                    cumulative_wait_ms,
4184                                    outcome: ContinuationOutcome::Resumed,
4185                                },
4186                            );
4187                        }
4188                        // The report parsed, but this same reply's own
4189                        // CommandEvidence — the identical record `state.jobs`
4190                        // renders — names a command whose CLI never
4191                        // confirmed an exit status. Read together, that is
4192                        // not a resolved answer: keep nudging rather than
4193                        // accept a report standing next to a command the
4194                        // seat's own CLI cannot vouch for.
4195                        Ok(_) => {
4196                            last_err = "the reply parsed, but it reported a command whose own CLI \
4197                                 never confirmed an exit status"
4198                                .to_owned();
4199                        }
4200                        Err(e) => last_err = e.to_string(),
4201                    }
4202                }
4203                AgentOutcome::Quota(o) => {
4204                    cumulative_wait_ms += o.duration_ms;
4205                    let loss = QuotaLoss::from_report(seat.key.clone(), "fix", o.quota.as_ref());
4206                    block_machine_outage(&mut self.state, "fix", std::slice::from_ref(&loss));
4207                    self.state.quota.push(loss);
4208                    self.state.event(
4209                        "fix",
4210                        format!(
4211                            "round {round}: continuation rate limited (quota); not retrying now"
4212                        ),
4213                    );
4214                    return (
4215                        seat,
4216                        None,
4217                        Some("rate limited (quota) while recovering the fix report".to_owned()),
4218                        ContinuationRecord {
4219                            attempts,
4220                            cumulative_wait_ms,
4221                            outcome: ContinuationOutcome::QuotaLost,
4222                        },
4223                    );
4224                }
4225                AgentOutcome::Dropped(o) => {
4226                    cumulative_wait_ms += o.duration_ms;
4227                    let why = o
4228                        .dropped
4229                        .as_ref()
4230                        .map(|d| d.why.as_str())
4231                        .unwrap_or("the CLI ended the stream without delivering its answer");
4232                    last_err = format!("the CLI dropped the stream ({why})");
4233                }
4234                AgentOutcome::Failed(e) => last_err = e,
4235                // The continuation was never started; the report stays lost
4236                // and the caller records that, without any handover.
4237                AgentOutcome::ResourceBlocked(e) => {
4238                    return (
4239                        seat,
4240                        None,
4241                        Some(format!("the continuation was not started: {e}")),
4242                        ContinuationRecord {
4243                            attempts: attempts.saturating_sub(1),
4244                            cumulative_wait_ms,
4245                            outcome: ContinuationOutcome::NoSession,
4246                        },
4247                    );
4248                }
4249            }
4250        }
4251    }
4252
4253    fn after_implement(&mut self) -> Result<()> {
4254        if !self.state.candidate_preservation.is_empty() {
4255            bail!("candidate preservation incomplete; judging is unsafe");
4256        }
4257        // Scan every candidate patch once the set is complete.
4258        if self.state.leaks.is_empty() {
4259            let cfg = self.state.config.blind.clone();
4260            let mut leaks = Vec::new();
4261            for c in &self.state.candidates {
4262                let Some(patch) =
4263                    crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
4264                else {
4265                    continue;
4266                };
4267                leaks.extend(blind::scan(
4268                    &format!("candidate {} patch", c.label),
4269                    &patch,
4270                    &cfg.vendor_tokens,
4271                ));
4272            }
4273            if !leaks.is_empty() {
4274                let summary = leaks
4275                    .iter()
4276                    .map(|l| format!("{}×{} in {}", l.token, l.count, l.site))
4277                    .collect::<Vec<_>>()
4278                    .join(", ");
4279                match cfg.on_leak {
4280                    LeakPolicy::Fail => {
4281                        self.state.status = RunStatus::Failed;
4282                        self.state
4283                            .event("blind", format!("vendor text in a patch: {summary}"));
4284                        self.state.leaks = leaks;
4285                        self.state.save()?;
4286                        self.settle_questions();
4287                        bail!(
4288                            "blind.on_leak = \"fail\" and vendor text reached a \
4289                             judged patch: {summary}"
4290                        );
4291                    }
4292                    LeakPolicy::Redact => self.state.event(
4293                        "blind",
4294                        format!("redacting vendor text for judging: {summary}"),
4295                    ),
4296                    LeakPolicy::Warn => self.state.event(
4297                        "blind",
4298                        format!("vendor text present in a judged patch (shown as-is): {summary}"),
4299                    ),
4300                }
4301                self.state.leaks = leaks;
4302            }
4303        }
4304
4305        // Re-verify any saved `verified_noop` claim on active/resumed runs so an
4306        // incomplete or inconsistent saved state cannot bypass the strict contract.
4307        let mut invalidated = Vec::new();
4308        for c in &mut self.state.candidates {
4309            if c.verified_noop.is_some() && !c.has_valid_verified_noop() {
4310                c.verified_noop = None;
4311                if c.empty && c.failed.is_none() {
4312                    c.failed = Some(
4313                        "no-op claim rejected: saved candidate does not satisfy structured verification requirements"
4314                            .to_owned(),
4315                    );
4316                }
4317                invalidated.push(c.label);
4318            }
4319        }
4320        for label in invalidated {
4321            self.state.event(
4322                "implement",
4323                format!("candidate {label}: invalidated inconsistent saved NO CHANGE NEEDED claim"),
4324            );
4325        }
4326
4327        if self.state.viable().is_empty() {
4328            if self.state.all_candidates_verified_noop() {
4329                // Every candidate agreed, with evidence the adoption guard
4330                // accepted, that nothing belongs in this worktree. That is
4331                // not the same fact as a candidate that simply failed to
4332                // write anything, and settling it as an ordinary `Failed`
4333                // (see `SCHEMA`'s doc for schema 10) is what let two of
4334                // task 391f's attempts burn a retry each re-discovering the
4335                // same already-landed fix. Terminal either way, so `judge`
4336                // must never run over an empty candidate set — unlike the
4337                // `Failed` branch below this returns `Ok`, not an error:
4338                // nothing here failed.
4339                self.state.status = RunStatus::VerifiedNoop;
4340                self.state.save()?;
4341                self.settle_questions();
4342                return Ok(());
4343            }
4344            self.state.status = RunStatus::Failed;
4345            self.state.save()?;
4346            self.settle_questions();
4347            bail!("no candidate produced a change; nothing to judge");
4348        }
4349        self.state.status = RunStatus::Judging;
4350        self.state.save()?;
4351        Ok(())
4352    }
4353
4354    // --------------------------------------------------------------- judge
4355
4356    async fn judge(&mut self) -> Result<()> {
4357        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4358        // agent files with `magi task add` name the run that paid for it. The
4359        // prompt overlay is cloned alongside it because the waves borrow it
4360        // while `self` is mutably borrowed by the node's own bookkeeping.
4361        let run_id = self.state.id.clone();
4362        let prompts = self.state.config.prompts.clone();
4363        if !self.state.judgements.is_empty() || self.state.judge_skipped {
4364            return Ok(());
4365        }
4366        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4367        if viable.len() == 1 {
4368            // Recorded so this is a one-time event: `judgements` stays empty
4369            // either way, which without this flag is indistinguishable from
4370            // "not yet judged" on the next reentry — and status is left
4371            // untouched, so a later node's conclusion (e.g. `Blocked` after
4372            // the review budget ran out) survives a resume instead of being
4373            // clobbered back to `Judging` by this node running again.
4374            self.state.judge_skipped = true;
4375            self.state.event(
4376                "judge",
4377                format!(
4378                    "only candidate {} produced a change; judging skipped",
4379                    viable[0].label
4380                ),
4381            );
4382            self.state.save()?;
4383            return Ok(());
4384        }
4385        self.state.status = RunStatus::Judging;
4386
4387        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
4388        let language = self.state.config.graph.language.clone();
4389        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4390        let sessions = self.state.config.graph.sessions;
4391        let artifacts = agent::artifacts_dir(&self.state.dir());
4392        let root = self.state.worktree_root();
4393        let base_short = short(&self.state.base_commit);
4394
4395        let mut jobs = Vec::new();
4396        let mut orders = Vec::new();
4397        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4398            let order = blind::presentation_order(viable.len(), j, self.state.seed);
4399            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
4400            orders.push(order.iter().map(|&k| viable[k].index).collect::<Vec<_>>());
4401            let seat_key = format!("judge-{}", j + 1);
4402            let seat = self.seat(&seat_key, &spec.id);
4403            jobs.push(SeatJob {
4404                prompt: prompt::judge(
4405                    &self.state.instruction,
4406                    &views,
4407                    self.roles.judges.len(),
4408                    &base_short,
4409                    &language,
4410                ),
4411                spec,
4412                seat,
4413                cwd: root.join(format!("judge-{}", j + 1)),
4414                timeout,
4415                allow_write: false,
4416                sessions,
4417                artifacts: artifacts.clone(),
4418                stem: format!("judge-{}", j + 1),
4419                handover: None,
4420            });
4421        }
4422
4423        self.state.event(
4424            "judge",
4425            format!(
4426                "{} judges ranking {} candidates blind",
4427                jobs.len(),
4428                viable.len()
4429            ),
4430        );
4431        let labels_for_check = labels.clone();
4432        let mut quota_losses = Vec::new();
4433        let cache = self.state.config.cache_dir();
4434        let ctx = WaveCtx {
4435            carry_seats: false,
4436            pauses: Some((&self.pause, &self.interrupt)),
4437            run: &run_id,
4438            node: "judge",
4439            prompts: &prompts,
4440            cache: cache.as_deref(),
4441            round: None,
4442        };
4443        let results = ask_json_wave::<Ranking>(
4444            jobs,
4445            Arc::clone(&self.sem),
4446            self.state.config.graph.retries,
4447            &self.roles.judge_roster,
4448            &ctx,
4449            &mut quota_losses,
4450            &mut self.state,
4451            &move |r: &Ranking| r.validate(&labels_for_check),
4452        )
4453        .await;
4454        if self.state.resource_block.is_some() {
4455            return self.stop_for_resource();
4456        }
4457        self.state.quota.extend(quota_losses);
4458
4459        for (j, (seat, res, _attempts)) in results.into_iter().enumerate() {
4460            let agent_id = seat.agent.clone();
4461            self.state.seats.insert(seat.key.clone(), seat);
4462            let mut record = Judgement {
4463                judge: j + 1,
4464                seat: format!("judge-{}", j + 1),
4465                agent: agent_id,
4466                ranking: Vec::new(),
4467                reasons: BTreeMap::new(),
4468                confidence: None,
4469                strengths: BTreeMap::new(),
4470                order: orders[j].clone(),
4471                failed: None,
4472                duration_ms: 0,
4473            };
4474            match res {
4475                Ok((ranking, out)) => {
4476                    record.ranking = ranking.normalized();
4477                    record.reasons = ranking.reasons;
4478                    record.strengths = ranking.strengths;
4479                    record.confidence = ranking.confidence;
4480                    record.duration_ms = out.duration_ms;
4481                    self.state.event(
4482                        "judge",
4483                        format!(
4484                            "judge {} ranked {}",
4485                            j + 1,
4486                            record.ranking.iter().collect::<String>()
4487                        ),
4488                    );
4489                }
4490                Err(e) => {
4491                    record.failed = Some(e.to_string());
4492                    self.state
4493                        .event("judge", format!("judge {} produced no ranking: {e}", j + 1));
4494                }
4495            }
4496            self.state.judgements.push(record);
4497            self.state.save()?;
4498        }
4499        Ok(())
4500    }
4501
4502    // ---------------------------------------------------------- deliberate
4503
4504    async fn deliberate(&mut self) -> Result<()> {
4505        if self.hold_base_sync().await? {
4506            return Ok(());
4507        }
4508        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4509        // agent files with `magi task add` name the run that paid for it. The
4510        // prompt overlay is cloned alongside it because the waves borrow it
4511        // while `self` is mutably borrowed by the node's own bookkeeping.
4512        let run_id = self.state.id.clone();
4513        let prompts = self.state.config.prompts.clone();
4514        let rounds = self.state.config.graph.deliberate_rounds;
4515        // Resume unfinished rounds after an outage, but never reopen a tally.
4516        if self.state.deliberation.len() >= rounds || self.state.tally.is_some() {
4517            return Ok(());
4518        }
4519        let tops: Vec<char> = self
4520            .state
4521            .judgements
4522            .iter()
4523            .filter_map(|j| j.ranking.first().copied())
4524            .collect();
4525        if tops.len() < 2 || tops.iter().all(|t| *t == tops[0]) || rounds == 0 {
4526            if tops.len() >= 2 && tops.iter().all(|t| *t == tops[0]) {
4527                self.state.event(
4528                    "deliberate",
4529                    format!("judges agreed on {} outright; no deliberation", tops[0]),
4530                );
4531            }
4532            self.state.status = RunStatus::Voting;
4533            self.state.save()?;
4534            return Ok(());
4535        }
4536
4537        self.state.status = RunStatus::Deliberating;
4538        self.state.event(
4539            "deliberate",
4540            format!(
4541                "split: first choices were {} — opening {rounds} round(s)",
4542                tops.iter().collect::<String>()
4543            ),
4544        );
4545
4546        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4547        let language = self.state.config.graph.language.clone();
4548        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4549        let sessions = self.state.config.graph.sessions;
4550        let artifacts = agent::artifacts_dir(&self.state.dir());
4551        let root = self.state.worktree_root();
4552        let base_short = short(&self.state.base_commit);
4553
4554        // Judges argue in sequence so that a turn can answer the one before it;
4555        // that is the difference between deliberation and three parallel
4556        // monologues.
4557        for round in self.state.deliberation.len() + 1..=rounds {
4558            let mut turns: Vec<DeliberationTurn> = Vec::new();
4559            let mut round_losses = Vec::new();
4560            let mut asked = 0;
4561            for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4562                if self.state.judgements[j].failed.is_some() {
4563                    continue;
4564                }
4565                let seat_key = format!("judge-{}", j + 1);
4566                let spec = self.occupant(&seat_key, spec);
4567                let mut seat = self.seat(&seat_key, &spec.id);
4568                let transcript = self.transcript(&turns, j);
4569                let build = |context: Option<&str>| {
4570                    prompt::deliberate(
4571                        &self.state.instruction,
4572                        context,
4573                        &transcript,
4574                        round,
4575                        rounds,
4576                        &language,
4577                    )
4578                };
4579                let block = self.candidate_block(&viable, &base_short);
4580                let full = build(Some(&block));
4581                let text = if has_context(&spec, &seat, sessions) {
4582                    build(None)
4583                } else {
4584                    full.clone()
4585                };
4586                let job = SeatJob {
4587                    spec,
4588                    seat: seat.clone(),
4589                    prompt: text,
4590                    cwd: root.join(format!("judge-{}", j + 1)),
4591                    timeout,
4592                    allow_write: false,
4593                    sessions,
4594                    artifacts: artifacts.clone(),
4595                    stem: format!("delib-{round}-judge-{}", j + 1),
4596                    handover: Some(full),
4597                };
4598                let cache = self.state.config.cache_dir();
4599                let ctx = WaveCtx {
4600                    carry_seats: false,
4601                    pauses: Some((&self.pause, &self.interrupt)),
4602                    run: &run_id,
4603                    node: "deliberate",
4604                    prompts: &prompts,
4605                    cache: cache.as_deref(),
4606                    round: None,
4607                };
4608                // A turn is never nudged (`retries` 0): a failed seat is
4609                // handed to the next roster agent, which gets the full
4610                // context. An empty answer is a turn, not a failure.
4611                let mut losses = Vec::new();
4612                asked += 1;
4613                let mut results = ask_wave_with::<String>(
4614                    vec![job],
4615                    Arc::clone(&self.sem),
4616                    0,
4617                    &self.roles.judge_roster,
4618                    &ctx,
4619                    &mut losses,
4620                    &mut self.state,
4621                    &|text: &str| {
4622                        Ok(verdict::section(text, "position").unwrap_or_else(|| text.to_owned()))
4623                    },
4624                )
4625                .await;
4626                if self.state.resource_block.is_some() {
4627                    return self.stop_for_resource();
4628                }
4629                round_losses.extend(losses.iter().cloned());
4630                self.state.quota.extend(losses);
4631                let (updated, res, _) = results.pop().expect("one job in, one result out");
4632                seat = updated;
4633                let agent_id = seat.agent.clone();
4634                self.state.seats.insert(seat.key.clone(), seat);
4635                let body = match res {
4636                    Ok((body, _)) => body,
4637                    // Skip the seat; a CLI's raw error JSON is never read as
4638                    // this judge's position.
4639                    Err(e) => {
4640                        self.state
4641                            .event("deliberate", format!("judge {} skipped: {e}", j + 1));
4642                        continue;
4643                    }
4644                };
4645                let tentative = verdict::extract_json::<Position>(&body)
4646                    .ok()
4647                    .and_then(|p| p.tentative)
4648                    .and_then(|s| s.trim().chars().next())
4649                    .map(|c| c.to_ascii_uppercase());
4650                self.state.event(
4651                    "deliberate",
4652                    format!(
4653                        "round {round}: judge {} now favours {}",
4654                        j + 1,
4655                        tentative.map_or("—".to_owned(), |c| c.to_string())
4656                    ),
4657                );
4658                turns.push(DeliberationTurn {
4659                    judge: j + 1,
4660                    agent: agent_id,
4661                    body: blind::sanitize_prose(&body, &self.state.config.blind),
4662                    tentative,
4663                });
4664            }
4665            if asked > 0 && turns.is_empty() && round_losses.len() == asked {
4666                block_machine_outage(&mut self.state, "deliberate", &round_losses);
4667                return self.stop_for_resource();
4668            }
4669            self.state
4670                .deliberation
4671                .push(DeliberationRound { round, turns });
4672            self.state.save()?;
4673        }
4674
4675        self.state.status = RunStatus::Voting;
4676        self.state.save()?;
4677        Ok(())
4678    }
4679
4680    // ---------------------------------------------------------------- vote
4681
4682    async fn vote(&mut self) -> Result<()> {
4683        if self.hold_base_sync().await? {
4684            return Ok(());
4685        }
4686        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
4687        // agent files with `magi task add` name the run that paid for it. The
4688        // prompt overlay is cloned alongside it because the waves borrow it
4689        // while `self` is mutably borrowed by the node's own bookkeeping.
4690        let run_id = self.state.id.clone();
4691        let prompts = self.state.config.prompts.clone();
4692        if !self.state.votes.is_empty() || self.state.tally.is_some() {
4693            return Ok(());
4694        }
4695        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
4696        if viable.len() == 1 {
4697            return Ok(());
4698        }
4699        self.state.status = RunStatus::Voting;
4700
4701        let language = self.state.config.graph.language.clone();
4702        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
4703        let sessions = self.state.config.graph.sessions;
4704        let artifacts = agent::artifacts_dir(&self.state.dir());
4705        let root = self.state.worktree_root();
4706        let base_short = short(&self.state.base_commit);
4707        let candidates: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
4708
4709        let mut jobs = Vec::new();
4710        let mut seats_at = Vec::new();
4711        for (j, spec) in self.roles.judges.clone().into_iter().enumerate() {
4712            if self
4713                .state
4714                .judgements
4715                .get(j)
4716                .is_some_and(|r| r.failed.is_some())
4717            {
4718                continue;
4719            }
4720            let seat_key = format!("judge-{}", j + 1);
4721            let spec = self.occupant(&seat_key, spec);
4722            let seat = self.seat(&seat_key, &spec.id);
4723            let full = self.vote_prompt_full(j, &viable, &language, &candidates, &base_short);
4724            let text = if has_context(&spec, &seat, sessions) {
4725                prompt::final_vote(&viable, &language)
4726            } else {
4727                full.clone()
4728            };
4729            jobs.push(SeatJob {
4730                spec,
4731                seat,
4732                prompt: text,
4733                cwd: root.join(format!("judge-{}", j + 1)),
4734                timeout,
4735                allow_write: false,
4736                sessions,
4737                artifacts: artifacts.clone(),
4738                stem: format!("vote-judge-{}", j + 1),
4739                handover: Some(full),
4740            });
4741            seats_at.push(j);
4742        }
4743
4744        self.state.event(
4745            "vote",
4746            format!(
4747                "collecting {} final votes one by one, privately",
4748                jobs.len()
4749            ),
4750        );
4751        let allowed = viable.clone();
4752        let mut quota_losses = Vec::new();
4753        let cache = self.state.config.cache_dir();
4754        let ctx = WaveCtx {
4755            carry_seats: false,
4756            pauses: Some((&self.pause, &self.interrupt)),
4757            run: &run_id,
4758            node: "vote",
4759            prompts: &prompts,
4760            cache: cache.as_deref(),
4761            round: None,
4762        };
4763        let results = ask_json_wave::<FinalVote>(
4764            jobs,
4765            Arc::clone(&self.sem),
4766            self.state.config.graph.retries,
4767            &self.roles.judge_roster,
4768            &ctx,
4769            &mut quota_losses,
4770            &mut self.state,
4771            &move |v: &FinalVote| match v.label() {
4772                Some(c) if allowed.contains(&c) => Ok(()),
4773                other => bail!("vote {other:?} is not one of {allowed:?}"),
4774            },
4775        )
4776        .await;
4777        if self.state.resource_block.is_some() {
4778            return self.stop_for_resource();
4779        }
4780        self.state.quota.extend(quota_losses);
4781
4782        for (&j, (seat, res, _attempts)) in seats_at.iter().zip(results) {
4783            let agent_id = seat.agent.clone();
4784            self.state.seats.insert(seat.key.clone(), seat);
4785            let initial = self
4786                .state
4787                .judgements
4788                .get(j)
4789                .and_then(|r| r.ranking.first().copied());
4790            let mut record = VoteRecord {
4791                judge: j + 1,
4792                agent: agent_id,
4793                vote: None,
4794                reason: String::new(),
4795                changed: false,
4796            };
4797            match res {
4798                Ok((v, _)) => {
4799                    record.vote = v.label();
4800                    record.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
4801                    record.changed = matches!((record.vote, initial), (Some(a), Some(b)) if a != b);
4802                    self.state.event(
4803                        "vote",
4804                        format!(
4805                            "judge {} voted {}{}",
4806                            j + 1,
4807                            record.vote.unwrap_or('?'),
4808                            if record.changed { " (changed)" } else { "" }
4809                        ),
4810                    );
4811                }
4812                Err(e) => {
4813                    self.state
4814                        .event("vote", format!("judge {} cast no vote: {e}", j + 1));
4815                }
4816            }
4817            self.state.votes.push(record);
4818            self.state.save()?;
4819        }
4820        Ok(())
4821    }
4822
4823    // --------------------------------------------------------------- tally
4824
4825    fn tally(&mut self) -> Result<()> {
4826        if self.state.tally.is_some() {
4827            return Ok(());
4828        }
4829        let viable: Vec<char> = self.state.viable().into_iter().map(|c| c.label).collect();
4830        let tops: Vec<char> = self
4831            .state
4832            .judgements
4833            .iter()
4834            .filter_map(|j| j.ranking.first().copied())
4835            .collect();
4836        let unanimous_initial = tops.len() > 1 && tops.iter().all(|t| *t == tops[0]);
4837
4838        // A judge whose private vote failed still counted once, in the initial
4839        // ranking; using it beats discarding a whole seat.
4840        let mut first_choice: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
4841        let mut cast: Vec<char> = Vec::new();
4842        for (i, j) in self.state.judgements.iter().enumerate() {
4843            let vote = self
4844                .state
4845                .votes
4846                .iter()
4847                .find(|v| v.judge == i + 1)
4848                .and_then(|v| v.vote)
4849                .or_else(|| j.ranking.first().copied());
4850            if let Some(v) = vote {
4851                *first_choice.entry(v).or_insert(0) += 1;
4852                cast.push(v);
4853            }
4854        }
4855
4856        let mut borda: BTreeMap<char, usize> = viable.iter().map(|l| (*l, 0)).collect();
4857        for j in &self.state.judgements {
4858            let n = j.ranking.len();
4859            for (pos, label) in j.ranking.iter().enumerate() {
4860                *borda.entry(*label).or_insert(0) += n.saturating_sub(pos + 1);
4861            }
4862        }
4863
4864        let best = first_choice.values().copied().max().unwrap_or(0);
4865        let mut leaders: Vec<char> = first_choice
4866            .iter()
4867            .filter(|(_, v)| **v == best)
4868            .map(|(k, _)| *k)
4869            .collect();
4870        let mut tie_break = None;
4871        if leaders.len() > 1 {
4872            let top_borda = leaders.iter().map(|l| borda[l]).max().unwrap_or(0);
4873            let borda_leaders: Vec<char> = leaders
4874                .iter()
4875                .copied()
4876                .filter(|l| borda[l] == top_borda)
4877                .collect();
4878            tie_break = Some(if borda_leaders.len() == 1 {
4879                format!(
4880                    "{} way tie on first-choice votes, broken by Borda points from the initial rankings",
4881                    leaders.len()
4882                )
4883            } else {
4884                format!(
4885                    "{} way tie on both first-choice votes and Borda points, broken by label order",
4886                    leaders.len()
4887                )
4888            });
4889            leaders = borda_leaders;
4890            leaders.sort_unstable();
4891        }
4892        let winner = *leaders
4893            .first()
4894            .or(viable.first())
4895            .context("no candidate to declare a winner from")?;
4896
4897        let changed_votes = self.state.votes.iter().filter(|v| v.changed).count();
4898        let unanimous_final = !cast.is_empty() && cast.iter().all(|c| *c == cast[0]);
4899        let deliberated = !self.state.deliberation.is_empty();
4900
4901        // Whose verdict is this? A rate-limited seat is absent even if it
4902        // ranked before the limit hit, so presence is measured against the
4903        // recorded losses, not just "did a ranking ever appear".
4904        let quota_seats: std::collections::BTreeSet<&str> =
4905            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
4906        let mut present = 0usize;
4907        for (i, j) in self.state.judgements.iter().enumerate() {
4908            if quota_seats.contains(j.seat.as_str()) {
4909                continue;
4910            }
4911            let ranked = !j.ranking.is_empty() && j.failed.is_none();
4912            let voted = self
4913                .state
4914                .votes
4915                .iter()
4916                .any(|v| v.judge == i + 1 && v.vote.is_some());
4917            if ranked || voted {
4918                present += 1;
4919            }
4920        }
4921        // Strict majority of the configured panel. A bare majority is real
4922        // signal we can act on, while a minority verdict must never stand in
4923        // for a healthy one. A one-candidate run needs no panel at all, and
4924        // `judges` stays `0` rather than the roster size a panel that never
4925        // sat would otherwise be credited with.
4926        let needs_quorum = viable.len() > 1;
4927        let judges_total = if needs_quorum {
4928            self.roles.judges.len()
4929        } else {
4930            0
4931        };
4932        let quorum = if needs_quorum {
4933            judges_total / 2 + 1
4934        } else {
4935            0
4936        };
4937        let met_quorum = !needs_quorum || present >= quorum;
4938        let uncontested = (!needs_quorum).then(|| {
4939            format!("only one candidate ({winner}) produced a usable change; no panel was asked")
4940        });
4941
4942        self.state.event(
4943            "tally",
4944            match &uncontested {
4945                Some(reason) => format!("winner {winner} — {reason}"),
4946                None => format!(
4947                    "winner {winner} — votes {} | initial {} | {} changed | \
4948                     {present}/{judges_total} judges{}",
4949                    first_choice
4950                        .iter()
4951                        .map(|(k, v)| format!("{k}:{v}"))
4952                        .collect::<Vec<_>>()
4953                        .join(" "),
4954                    if unanimous_initial {
4955                        "unanimous"
4956                    } else {
4957                        "split"
4958                    },
4959                    changed_votes,
4960                    if met_quorum {
4961                        String::new()
4962                    } else {
4963                        format!(" — below quorum ({quorum} required)")
4964                    },
4965                ),
4966            },
4967        );
4968        if !met_quorum {
4969            self.state.event(
4970                "stall",
4971                format!(
4972                    "verdict rests on {present} of {judges_total} judges (quorum {quorum}); \
4973                     the run stops here, resumable"
4974                ),
4975            );
4976        }
4977        self.state.tally = Some(Tally {
4978            first_choice,
4979            borda,
4980            winner,
4981            rankings: tops.len(),
4982            unanimous_initial,
4983            deliberated,
4984            changed_votes,
4985            unanimous_final,
4986            tie_break,
4987            judges: judges_total,
4988            present,
4989            quorum,
4990            met_quorum,
4991            uncontested,
4992        });
4993        self.state.status = if met_quorum {
4994            RunStatus::Reviewing
4995        } else {
4996            RunStatus::Stalled
4997        };
4998        self.state.save()?;
4999        Ok(())
5000    }
5001
5002    // ------------------------------------------------------------- recover
5003
5004    /// Re-ask the judge seats `tally` counts as absent, so a `Stalled` run can be
5005    /// resumed toward completion once the transient cause clears.
5006    ///
5007    /// A seat is absent — and therefore re-asked — when `tally` refuses to count
5008    /// it toward the quorum, which is exactly the set of seats whose absence
5009    /// collapsed the panel: struck by a rate limit at *any* node (the quorum must
5010    /// not depend on which node happened to hit the limit), or an ordinary
5011    /// failure (`failed = Some`) that never produced a usable ranking. A healthy
5012    /// seat is never disturbed.
5013    ///
5014    /// A seat that now answers with a usable ranking is "recovered": its
5015    /// `Judgement` is refreshed, its `QuotaLoss`/`failed` state cleared (so
5016    /// `tally` counts it present again), and its vote re-collected. A seat that
5017    /// still fails keeps its loss and stays absent.
5018    ///
5019    /// Returns `true` when the re-tally restores the quorum (the run may proceed
5020    /// to review/gate/merge), `false` when it is still below quorum (the run
5021    /// stays `Stalled`, still resumable for a later retry).
5022    #[allow(clippy::too_many_lines)]
5023    async fn recover_stall(&mut self) -> Result<bool> {
5024        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
5025        // agent files with `magi task add` name the run that paid for it. The
5026        // prompt overlay is cloned alongside it because the waves borrow it
5027        // while `self` is mutably borrowed by the node's own bookkeeping.
5028        let run_id = self.state.id.clone();
5029        let prompts = self.state.config.prompts.clone();
5030        // Absent seats = quota-lost at any node, or failed outright. Mirroring
5031        // `tally`'s presence test (rather than the old quota-judge/vote filter)
5032        // is what keeps a non-quota collapse — or a quota loss recorded at the
5033        // deliberate node — from being a permanent dead-end on `--resume`.
5034        let quota_seats: BTreeSet<&str> =
5035            self.state.quota.iter().map(|q| q.seat.as_str()).collect();
5036        let absent: Vec<String> = self
5037            .state
5038            .judgements
5039            .iter()
5040            .filter(|j| quota_seats.contains(j.seat.as_str()) || j.failed.is_some())
5041            .map(|j| j.seat.clone())
5042            .collect();
5043        if absent.is_empty() {
5044            return Ok(false);
5045        }
5046        let viable: Vec<Candidate> = self.state.viable().into_iter().cloned().collect();
5047        if viable.len() <= 1 {
5048            return Ok(false);
5049        }
5050        let labels: Vec<char> = viable.iter().map(|c| c.label).collect();
5051        let language = self.state.config.graph.language.clone();
5052        let timeout = Duration::from_secs(self.state.config.graph.timeout_judge);
5053        let sessions = self.state.config.graph.sessions;
5054        let artifacts = agent::artifacts_dir(&self.state.dir());
5055        let root = self.state.worktree_root();
5056        let base_short = short(&self.state.base_commit);
5057        let candidates: Vec<Candidate> = viable.clone();
5058
5059        // Map each absent seat key to its 0-based position in `roles.judges`.
5060        let mut positions: Vec<usize> = absent
5061            .iter()
5062            .filter_map(|k| self.state.judgements.iter().position(|r| &r.seat == k))
5063            .collect();
5064        if positions.is_empty() {
5065            return Ok(false);
5066        }
5067        positions.sort_unstable();
5068        positions.dedup();
5069
5070        // Re-rank the lost seats, one blind prompt each.
5071        let mut judge_jobs = Vec::new();
5072        for &j in &positions {
5073            let order = blind::presentation_order(viable.len(), j, self.state.seed);
5074            let views: Vec<CandidateView> = order.iter().map(|&k| self.view(&viable[k])).collect();
5075            let seat_key = format!("judge-{}", j + 1);
5076            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
5077            let seat = self.seat(&seat_key, &spec.id);
5078            judge_jobs.push(SeatJob {
5079                spec,
5080                seat,
5081                prompt: prompt::judge(
5082                    &self.state.instruction,
5083                    &views,
5084                    self.roles.judges.len(),
5085                    &base_short,
5086                    &language,
5087                ),
5088                cwd: root.join(seat_key),
5089                timeout,
5090                allow_write: false,
5091                sessions,
5092                artifacts: artifacts.clone(),
5093                stem: format!("judge-{}-recover", j + 1),
5094                handover: None,
5095            });
5096        }
5097
5098        let labels_for_check = labels.clone();
5099        let mut judge_losses = Vec::new();
5100        let retries = self.state.config.graph.retries;
5101        let cache = self.state.config.cache_dir();
5102        let ctx = WaveCtx {
5103            carry_seats: false,
5104            pauses: Some((&self.pause, &self.interrupt)),
5105            run: &run_id,
5106            node: "judge",
5107            prompts: &prompts,
5108            cache: cache.as_deref(),
5109            round: None,
5110        };
5111        let results = ask_json_wave::<Ranking>(
5112            judge_jobs,
5113            Arc::clone(&self.sem),
5114            retries,
5115            &self.roles.judge_roster,
5116            &ctx,
5117            &mut judge_losses,
5118            &mut self.state,
5119            &move |r: &Ranking| r.validate(&labels_for_check),
5120        )
5121        .await;
5122        if self.state.resource_block.is_some() {
5123            self.stop_for_resource()?;
5124            return Ok(false);
5125        }
5126
5127        // Refresh the judgement of every seat that ranked again.
5128        let mut recovered: BTreeSet<usize> = BTreeSet::new();
5129        for (&j, (seat, res, _attempts)) in positions.iter().zip(results) {
5130            let agent_id = seat.agent.clone();
5131            self.state.seats.insert(seat.key.clone(), seat);
5132            let record = &mut self.state.judgements[j];
5133            match res {
5134                Ok((ranking, out)) => {
5135                    record.agent = agent_id;
5136                    record.ranking = ranking.normalized();
5137                    record.reasons = ranking.reasons;
5138                    record.strengths = ranking.strengths;
5139                    record.confidence = ranking.confidence;
5140                    record.failed = None;
5141                    record.duration_ms = out.duration_ms;
5142                    recovered.insert(j);
5143                    self.state.event(
5144                        "recover",
5145                        format!("judge {} ranked again after the limit", j + 1),
5146                    );
5147                }
5148                Err(e) => {
5149                    self.state
5150                        .event("recover", format!("judge {} still cannot rank: {e}", j + 1));
5151                }
5152            }
5153        }
5154
5155        // Re-ask the votes of the seats that recovered a ranking.
5156        let mut vote_jobs = Vec::new();
5157        let mut vote_pos: Vec<usize> = Vec::new();
5158        for &j in &recovered {
5159            let seat_key = format!("judge-{}", j + 1);
5160            let spec = self.occupant(&seat_key, self.roles.judges[j].clone());
5161            let seat = self.seat(&seat_key, &spec.id);
5162            let full = self.vote_prompt_full(j, &labels, &language, &candidates, &base_short);
5163            let text = if has_context(&spec, &seat, sessions) {
5164                prompt::final_vote(&labels, &language)
5165            } else {
5166                full.clone()
5167            };
5168            vote_jobs.push(SeatJob {
5169                spec,
5170                seat,
5171                prompt: text,
5172                cwd: root.join(seat_key),
5173                timeout,
5174                allow_write: false,
5175                sessions,
5176                artifacts: artifacts.clone(),
5177                stem: format!("vote-judge-{}-recover", j + 1),
5178                handover: Some(full),
5179            });
5180            vote_pos.push(j);
5181        }
5182        let allowed = labels.clone();
5183        let mut vote_losses = Vec::new();
5184        let vote_retries = self.state.config.graph.retries;
5185        let vote_cache = self.state.config.cache_dir();
5186        let ctx = WaveCtx {
5187            carry_seats: false,
5188            pauses: Some((&self.pause, &self.interrupt)),
5189            run: &run_id,
5190            node: "vote",
5191            prompts: &prompts,
5192            cache: vote_cache.as_deref(),
5193            round: None,
5194        };
5195        let votes = ask_json_wave::<FinalVote>(
5196            vote_jobs,
5197            Arc::clone(&self.sem),
5198            vote_retries,
5199            &self.roles.judge_roster,
5200            &ctx,
5201            &mut vote_losses,
5202            &mut self.state,
5203            &move |v: &FinalVote| match v.label() {
5204                Some(c) if allowed.contains(&c) => Ok(()),
5205                other => bail!("vote {other:?} is not one of {allowed:?}"),
5206            },
5207        )
5208        .await;
5209        if self.state.resource_block.is_some() {
5210            self.stop_for_resource()?;
5211            return Ok(false);
5212        }
5213        for (&j, (seat, res, _attempts)) in vote_pos.iter().zip(votes) {
5214            let agent_id = seat.agent.clone();
5215            self.state.seats.insert(seat.key.clone(), seat);
5216            match res {
5217                Ok((v, _)) => {
5218                    if let Some(rec) = self.state.votes.iter_mut().find(|r| r.judge == j + 1) {
5219                        rec.vote = v.label();
5220                        rec.reason = blind::sanitize_prose(&v.reason, &self.state.config.blind);
5221                    } else {
5222                        self.state.votes.push(VoteRecord {
5223                            judge: j + 1,
5224                            agent: agent_id,
5225                            vote: v.label(),
5226                            reason: blind::sanitize_prose(&v.reason, &self.state.config.blind),
5227                            changed: false,
5228                        });
5229                    }
5230                    self.state.event(
5231                        "recover",
5232                        format!("judge {} voted again after the limit", j + 1),
5233                    );
5234                }
5235                Err(e) => {
5236                    self.state
5237                        .event("recover", format!("judge {} still cannot vote: {e}", j + 1));
5238                }
5239            }
5240        }
5241
5242        // A seat that ranked again is present even if its re-vote failed —
5243        // `tally` falls back to the initial ranking's first choice — so clear
5244        // its quota loss. Seats that still fail keep theirs and stay absent.
5245        let recovered_keys: BTreeSet<String> = recovered
5246            .iter()
5247            .map(|&j| format!("judge-{}", j + 1))
5248            .collect();
5249        self.state
5250            .quota
5251            .retain(|q| !recovered_keys.contains(&q.seat));
5252        // A seat that hit the limit again is a fresh loss, not the old one:
5253        // replace the stale entry so the history stays one-per-seat and the
5254        // daemon can tell this attempt's loss from a previous session's.
5255        for loss in judge_losses.into_iter().chain(vote_losses) {
5256            if recovered_keys.contains(&loss.seat) {
5257                continue;
5258            }
5259            self.state.quota.retain(|q| q.seat != loss.seat);
5260            self.state.quota.push(loss);
5261        }
5262
5263        // Recompute the verdict from the refreshed panel.
5264        self.state.tally = None;
5265        self.tally()?;
5266        Ok(self
5267            .state
5268            .tally
5269            .as_ref()
5270            .map(|t| t.met_quorum)
5271            .unwrap_or(false))
5272    }
5273
5274    // ---------------------------------------------------------------- graft
5275
5276    /// Port the strengths the judges attributed to the losing candidates onto
5277    /// the winner, once, between the tally and the review loop.
5278    ///
5279    /// Best-effort by construction: it returns nothing and fails nothing. A
5280    /// skip, a fixer that failed or hit quota, or a round that changed nothing
5281    /// all leave the winner at its previous commit (`GraftRecord::pre`), and
5282    /// the run carries on as if the phase were off. See [`graft`] for the
5283    /// decisions and `AGENTS.md` for the invariants.
5284    ///
5285    /// The one exception is a rollback that could not be confirmed: the
5286    /// rejected commit may still be the winner's tip, so the run is blocked
5287    /// (resumable; the record stays `Running`, which makes a resume retry the
5288    /// restore) instead of reviewing, gating and merging it.
5289    async fn graft(&mut self) -> Result<()> {
5290        let Err(e) = self.graft_inner().await else {
5291            return Ok(());
5292        };
5293        if e.is::<crate::repo_lock::ResourceBlocked>() {
5294            return Err(e);
5295        }
5296        if e.downcast_ref::<GraftRestoreFailed>().is_some() {
5297            self.state.status = RunStatus::Blocked;
5298            self.state.event("graft", format!("blocked: {e:#}"));
5299            self.state.save()?;
5300            return Err(e);
5301        }
5302        // An error after the `Running` record was saved may have left the
5303        // fixer's work in the tree: the record must not stay unsettled
5304        // (a later resume would reset past the review fixes), so confirm the
5305        // restore now, or block.
5306        if let Some(rec) = self.state.graft.clone()
5307            && !rec.outcome.settled()
5308        {
5309            if let Some(winner) = self.state.winner().cloned() {
5310                if let Err(re) = self.graft_restore(&winner.worktree, &rec.pre).await {
5311                    if re.is::<crate::repo_lock::ResourceBlocked>() {
5312                        return Err(re);
5313                    }
5314                    self.state.status = RunStatus::Blocked;
5315                    self.state.event("graft", format!("blocked: {re:#}"));
5316                    self.state.save()?;
5317                    return Err(re);
5318                }
5319            }
5320            if let Some(g) = self.state.graft.as_mut() {
5321                g.outcome = GraftOutcome::RolledBack(format!("{e:#}"));
5322            }
5323        }
5324        self.state.event("graft", format!("skipped: {e:#}"));
5325        if let Err(e) = self.state.save() {
5326            tracing::warn!("save after graft: {e:#}");
5327        }
5328        Ok(())
5329    }
5330
5331    /// Put the winner back on `pre` and confirm it: a failed `reset` (a stale
5332    /// `index.lock`, say) or a tip that is not `pre` afterwards is an error.
5333    async fn graft_restore(&mut self, wt: &Path, pre: &str) -> Result<()> {
5334        let _coordination = self.coordinate(wt).await?;
5335        crate::recovery::restore_repair(wt, pre)
5336            .await
5337            .map_err(|e| GraftRestoreFailed(format!("{e:#}")).into())
5338    }
5339
5340    /// A skip is a run event, recorded once however often the node is re-entered.
5341    fn graft_skipped(&mut self, why: &str) {
5342        let message = format!("skipped: {why}");
5343        if !self
5344            .state
5345            .events
5346            .iter()
5347            .any(|e| e.node == "graft" && e.message == message)
5348        {
5349            self.state.event("graft", message);
5350        }
5351    }
5352
5353    async fn graft_inner(&mut self) -> Result<()> {
5354        // A round that was started and never finished (crash, kill): the
5355        // fixer may have left anything in the tree, so put the winner back.
5356        if let Some(rec) = self.state.graft.clone()
5357            && !rec.outcome.settled()
5358        {
5359            // Reviews exist only if the graft ended without its record being
5360            // settled (a swallowed error): the tree has moved on since, and
5361            // a reset to `pre` would discard the review fixes.
5362            if self.state.reviews.is_empty()
5363                && let Some(winner) = self.state.winner().cloned()
5364            {
5365                self.graft_restore(&winner.worktree, &rec.pre).await?;
5366            }
5367            if rec.outcome == GraftOutcome::WaitingForRestore {
5368                self.state.graft = None;
5369                self.state.save()?;
5370            } else {
5371                if let Some(g) = self.state.graft.as_mut() {
5372                    g.outcome = GraftOutcome::RolledBack(graft::INTERRUPTED.to_owned());
5373                }
5374                self.state.event(
5375                    "graft",
5376                    "rolled back: the previous round was interrupted; the winner is untouched",
5377                );
5378                self.state.save()?;
5379                return Ok(());
5380            }
5381        }
5382        let plan = match graft::plan(&self.state) {
5383            Ok(plan) => plan,
5384            Err(skip) => {
5385                if skip != graft::Skip::AlreadyDone {
5386                    self.graft_skipped(skip.reason());
5387                    self.state.save()?;
5388                }
5389                return Ok(());
5390            }
5391        };
5392        let Some(winner) = self.state.winner().cloned() else {
5393            return Ok(());
5394        };
5395        let wt = winner.worktree.clone();
5396        if !git::is_clean(&wt).await? {
5397            self.graft_skipped("the winner's worktree has uncommitted changes");
5398            self.state.save()?;
5399            return Ok(());
5400        }
5401        let pre = git::rev_parse(&wt, "HEAD").await?;
5402        // Saved before the fixer is called: a stop from here on is repaired
5403        // by the branch above on the next entry.
5404        self.state.graft = Some(GraftRecord {
5405            pre: pre.clone(),
5406            post: None,
5407            lines: None,
5408            limit: None,
5409            agent: None,
5410            outcome: GraftOutcome::Running,
5411            requested: graft::requested(&plan),
5412            adoption: None,
5413            adoption_error: None,
5414        });
5415        self.state.event(
5416            "graft",
5417            format!(
5418                "porting strengths of candidate(s) {} onto {}",
5419                plan.strengths
5420                    .iter()
5421                    .map(|(l, _, _)| l.to_string())
5422                    .collect::<Vec<_>>()
5423                    .join(", "),
5424                plan.winner
5425            ),
5426        );
5427        self.state.save()?;
5428
5429        let fix_prompt = prompt::graft(
5430            &self.state.instruction,
5431            plan.winner,
5432            &plan.strengths,
5433            &self.state.config.graph.language,
5434        );
5435        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
5436        let sessions = self.state.config.graph.sessions;
5437        let artifacts = agent::artifacts_dir(&self.state.dir());
5438        let attempts = fixer::graft_attempts(&self.state, &self.roles, &winner);
5439        let (_, seat, out) = self
5440            .ask_fixer_among(attempts, "graft", None, Some((&wt, &pre)), |spec, seat| {
5441                SeatJob {
5442                    prompt: fix_prompt.clone(),
5443                    spec,
5444                    seat,
5445                    cwd: wt.clone(),
5446                    timeout,
5447                    allow_write: true,
5448                    sessions,
5449                    artifacts: artifacts.clone(),
5450                    stem: "graft".to_owned(),
5451                    handover: None,
5452                }
5453            })
5454            .await;
5455        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
5456            // Preserve the need to restore earlier fallback edits without
5457            // confusing an unstarted seat with an interrupted invocation.
5458            self.state.graft.as_mut().expect("graft record").outcome =
5459                GraftOutcome::WaitingForRestore;
5460            return self.stop_for_resource();
5461        }
5462        let mut why: Option<String> = None;
5463        match &out {
5464            AgentOutcome::Ok(o) if agent::output_advances(o) => {
5465                why = Some("the fixer produced nothing usable".to_owned());
5466            }
5467            AgentOutcome::Ok(_) => {}
5468            AgentOutcome::Dropped(_) => why = Some("the CLI dropped the stream".to_owned()),
5469            AgentOutcome::Quota(o) => {
5470                self.state.quota.push(QuotaLoss::from_report(
5471                    seat.key.clone(),
5472                    "graft",
5473                    o.quota.as_ref(),
5474                ));
5475                why = Some("rate limited (quota)".to_owned());
5476            }
5477            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
5478                why = Some(format!(
5479                    "the fixer failed: {}",
5480                    e.lines()
5481                        .next()
5482                        .unwrap_or("")
5483                        .chars()
5484                        .take(160)
5485                        .collect::<String>()
5486                ));
5487            }
5488        }
5489        let agent_id = seat.agent.clone();
5490        self.state.seats.insert(seat.key.clone(), seat);
5491
5492        let mut post = None;
5493        let mut lines = None;
5494        let _coordination = self.coordinate(&wt).await?;
5495        if why.is_none() {
5496            let rescued = git::rescue_commit(&wt, "magi: graft (uncommitted work)").await;
5497            if let Ok(r) = &rescued {
5498                self.state.note_withheld("graft", &r.withheld);
5499            }
5500            let head = git::rev_parse(&wt, "HEAD").await?;
5501            // What is measured must be what gets reviewed and gated: a failed
5502            // rescue, or anything still uncommitted (withheld lockfiles
5503            // aside, which are never part of the tree), rejects the graft.
5504            let dirty = match &rescued {
5505                Ok(r) => git::status_porcelain(&wt)
5506                    .await
5507                    .map(|st| {
5508                        st.lines().any(|l| {
5509                            !r.withheld
5510                                .iter()
5511                                .any(|w| l.trim_end().ends_with(w.path.as_str()))
5512                        })
5513                    })
5514                    .unwrap_or(true),
5515                Err(_) => true,
5516            };
5517            if dirty {
5518                why = Some("the fixer left changes that could not be committed".to_owned());
5519            } else if head == pre {
5520                why = Some("the fixer changed nothing".to_owned());
5521            } else {
5522                lines = git::changed_lines(&wt, &pre, &head).await;
5523                post = Some(head);
5524            }
5525        }
5526        let (adoption, adoption_error) = match &out {
5527            AgentOutcome::Ok(o) => crate::graft_report::adoption_of(&o.text),
5528            _ => (None, None),
5529        };
5530        let requested = graft::requested(&plan);
5531        let outcome = match why {
5532            None => {
5533                self.state.event(
5534                    "graft",
5535                    format!(
5536                        "applied: {}",
5537                        lines.map_or_else(
5538                            || "changed lines unavailable".to_owned(),
5539                            |n| format!("{n} changed lines")
5540                        )
5541                    ),
5542                );
5543                GraftOutcome::Applied
5544            }
5545            Some(why) => {
5546                // Not settled until the restore is confirmed: the record
5547                // stays `Running`, so a resume retries it.
5548                crate::recovery::restore_repair(&wt, &pre)
5549                    .await
5550                    .map_err(|e| GraftRestoreFailed(format!("{e:#}")))?;
5551                self.state.event(
5552                    "graft",
5553                    format!("rolled back: {why}; the winner is untouched"),
5554                );
5555                GraftOutcome::RolledBack(why)
5556            }
5557        };
5558        self.state.graft = Some(GraftRecord {
5559            pre,
5560            post,
5561            lines,
5562            limit: None,
5563            agent: Some(agent_id),
5564            outcome,
5565            requested,
5566            adoption,
5567            adoption_error,
5568        });
5569        self.state.save()?;
5570        Ok(())
5571    }
5572
5573    // ----------------------------------------------------------------- fold
5574
5575    async fn fold_losers(&mut self) -> Result<()> {
5576        let Some(winner) = self.state.tally.as_ref().map(|t| t.winner) else {
5577            return Ok(());
5578        };
5579        if !self.state.candidate_preservation.is_empty() {
5580            bail!("candidate preservation incomplete; refusing cleanup");
5581        }
5582        let repo = self.state.repo.clone();
5583        let _coordination = self.coordinate(&repo).await?;
5584        let home = crate::run::home();
5585        let root = self.state.worktree_root();
5586        let isolated = crate::build_target::isolated(&self.state.config);
5587        let mut folded = Vec::new();
5588        for i in 0..self.state.candidates.len() {
5589            let c = &self.state.candidates[i];
5590            if c.label == winner || c.folded {
5591                continue;
5592            }
5593            let (wt, branch, label) = (c.worktree.clone(), c.branch.clone(), c.label);
5594            let target = fold_target(&home, &root, &wt, isolated);
5595            remove_preserved_worktree(&repo, &wt).await?;
5596            reclaim_fold_target(&home, target);
5597            if git::branch_exists(&repo, &branch).await?
5598                && !git::branch_delete(&repo, &branch).await?
5599            {
5600                bail!("candidate branch removal refused");
5601            }
5602            self.state.candidates[i].folded = true;
5603            self.state.save()?;
5604            folded.push(label.to_string());
5605        }
5606        // The judges are finished; their checkouts are pure cost from here.
5607        for j in 1..=self.roles.judges.len() {
5608            let wt = root.join(format!("judge-{j}"));
5609            if wt.exists() {
5610                let target = fold_target(&home, &root, &wt, isolated);
5611                remove_read_seat_worktree(&mut self.state, &wt).await?;
5612                reclaim_fold_target(&home, target);
5613                self.state.save()?;
5614            }
5615        }
5616        // The design-deliberation stage is finished by the time a tally
5617        // exists — same reasoning as the judges above.
5618        if self.state.config.graph.advise {
5619            for k in 1..=self.state.config.graph.advisors {
5620                let wt = root.join(format!("advisor-{k}"));
5621                if wt.exists() {
5622                    let target = fold_target(&home, &root, &wt, isolated);
5623                    remove_read_seat_worktree(&mut self.state, &wt).await?;
5624                    reclaim_fold_target(&home, target);
5625                    self.state.save()?;
5626                }
5627            }
5628        }
5629        if !folded.is_empty() {
5630            self.state
5631                .event("fold", format!("folded candidates {}", folded.join(", ")));
5632            self.state.save()?;
5633        }
5634        Ok(())
5635    }
5636
5637    // ------------------------------------------------------------ base sync
5638
5639    async fn hold_base_sync(&mut self) -> Result<bool> {
5640        self.hold_base_sync_as(None).await
5641    }
5642
5643    async fn hold_base_sync_kind(
5644        &mut self,
5645        kind: crate::base_sync_recovery::StopKind,
5646    ) -> Result<()> {
5647        self.hold_base_sync_as(Some(kind)).await?;
5648        Ok(())
5649    }
5650
5651    async fn hold_base_sync_as(
5652        &mut self,
5653        kind: Option<crate::base_sync_recovery::StopKind>,
5654    ) -> Result<bool> {
5655        if !self.state.base_sync_blocked() {
5656            self.state.base_sync_recovery.stop = None;
5657            return Ok(false);
5658        }
5659        let head = match self.state.winner() {
5660            Some(w) => git::rev_parse(&w.worktree, "HEAD")
5661                .await
5662                .unwrap_or_default(),
5663            None => String::new(),
5664        };
5665        if let Some(authorization) = self.state.base_sync_recovery.authorizations.last_mut()
5666            && !authorization.consumed
5667            && authorization.stop.head != head
5668        {
5669            authorization.refuse(format!(
5670                "retained HEAD changed from {} to {head}; inspect it and authorize again with --recover-base",
5671                authorization.stop.head
5672            ));
5673        }
5674        self.state.record_base_sync_stop(&head);
5675        if let Some(kind) = kind {
5676            self.state.base_sync_recovery.stop.as_mut().unwrap().kind = kind.clone();
5677            if let Some(stop) = self.state.base_sync_recovery.stops.last_mut() {
5678                stop.kind = kind;
5679            }
5680        }
5681        self.state.save()?;
5682        Ok(true)
5683    }
5684
5685    async fn resume_legacy_sequencer_stop(
5686        &mut self,
5687        winner: &Candidate,
5688        scratch: &Path,
5689        head: &str,
5690    ) -> Result<()> {
5691        use crate::repair_budget::legacy::{legacy_sequencer_head, resumable_sequencer_stop};
5692
5693        if !resumable_sequencer_stop(&self.state)
5694            || legacy_sequencer_head(&self.state) != Some(head)
5695            || self.state.base_recovery_pending()
5696            || self
5697                .state
5698                .repair_grants
5699                .iter()
5700                .any(|grant| !grant.succeeded)
5701        {
5702            return Ok(());
5703        }
5704        let Some(task) = self.state.origin.as_ref().and_then(|o| o.task.as_deref()) else {
5705            return Ok(());
5706        };
5707        let owner = crate::queue::Queue::open().get(task)?;
5708        if owner.execution_runs().last() != Some(&self.state.id)
5709            || owner.status == crate::queue::TaskStatus::Done
5710            || owner.fresh_start
5711            || owner.review_branch.is_some()
5712            || !crate::daemon::compatible_run_instruction(&self.state, &owner)
5713        {
5714            return Ok(());
5715        }
5716
5717        let repo = self.state.repo.clone();
5718        let wait = repository_wait(&self.state, None);
5719        let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
5720        let common = crate::repo_lock::common_dir(&repo).await?;
5721        let op = self.state.base_sync_recovery.operations.last().unwrap();
5722        if git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
5723            || git::rev_parse(&winner.worktree, "HEAD").await? != head
5724            || git::current_branch(&winner.worktree).await?.as_deref()
5725                != Some(winner.branch.as_str())
5726            || common.is_none()
5727            || crate::repo_lock::common_dir(&winner.worktree).await? != common
5728            || crate::repo_lock::common_dir(&owner.repo).await? != common
5729            || !git::is_clean(&winner.worktree).await?
5730        {
5731            return Ok(());
5732        }
5733        if scratch.try_exists()? {
5734            let admin = git::rebase_scratch_admin(&repo, scratch).await?;
5735            if admin.join("locked").try_exists()?
5736                || !git::git(
5737                    scratch,
5738                    &[
5739                        "status",
5740                        "--porcelain",
5741                        "--untracked-files=all",
5742                        "--ignored",
5743                    ],
5744                )
5745                .await?
5746                .is_empty()
5747            {
5748                return Ok(());
5749            }
5750            if git::checked_rebase_in_progress(scratch).await? {
5751                if crate::rebase::saved_base_identity(scratch, &winner.branch).await? != head
5752                    || crate::rebase::rebase_target(scratch).await? != op.tip
5753                    || !git::unmerged_paths(scratch).await?.is_empty()
5754                {
5755                    return Ok(());
5756                }
5757            } else if git::current_branch(scratch).await?.as_deref() != Some(winner.branch.as_str())
5758                || git::rev_parse(scratch, "HEAD").await? != head
5759            {
5760                return Ok(());
5761            }
5762        }
5763
5764        self.state
5765            .base_sync_recovery
5766            .operations
5767            .last_mut()
5768            .unwrap()
5769            .finished = false;
5770        let diagnostic = self
5771            .state
5772            .base_sync
5773            .as_mut()
5774            .unwrap()
5775            .conflict
5776            .take()
5777            .unwrap();
5778        self.state.base_sync_recovery.stop = None;
5779        self.state.event(
5780            "rebase",
5781            format!("reopened the original reservation for a legacy sequencer infrastructure stop: {diagnostic}"),
5782        );
5783        self.state.save()
5784    }
5785
5786    /// Land the winner's tree on the current tip of `<remote>/<base>` before
5787    /// anything verifies it.
5788    ///
5789    /// `verify.e2e`, `verify.gate` and every reviewer in [`Self::review_loop`]
5790    /// read whatever is checked out in the winner's worktree. Left alone that
5791    /// tree stays rooted at `base_commit` - the base as [`resolve_base`] saw
5792    /// it when the run *branched* - and a run takes long enough that the base
5793    /// has usually moved by the time it gets here. A gate that ran there
5794    /// answers "green on the commit this run started from", not "green on
5795    /// what is about to land", and the difference showed up three times in
5796    /// one day as a green run whose merge would have reverted a file another
5797    /// pull request had already landed.
5798    ///
5799    /// Reuses [`crate::rebase::rebase_with_fixer`], the same routine
5800    /// `land::Step::Rebase` calls, rather than a second implementation of the
5801    /// same idea: a throwaway worktree, nothing runs in the primary tree, and
5802    /// a second rebase path is exactly the kind of drift `resolve_base`'s own
5803    /// doc warns about ("two answers to a question nobody notices until a
5804    /// diff is wrong").
5805    ///
5806    /// Foreign-checkout reviews instead merge the base into the owned shadow
5807    /// worktree, preserving the ancestry required for fast-forward delivery.
5808    /// A conflicting merge is aborted and held for operator resolution.
5809    ///
5810    /// A conflict is not the end of the road: the standing rebase is handed
5811    /// to the fixer seat, at most `graph.review_rounds` times, counted in
5812    /// `state.rebase_fixes` (so it survives a park/resume and is shared with
5813    /// land). Once it finishes, review and the gate run as usual on the
5814    /// rebased tree, which is where a breakage the new base caused is caught
5815    /// by the ordinary gate-fix round. magi resolves nothing itself.
5816    ///
5817    /// Two different bounds, easy to confuse: [`BASE_SYNC_ROUNDS`], counted in
5818    /// the current durable recovery interval, bounds how often the base is
5819    /// synchronized during active recovery (lifetime attempts remain evidence).
5820    /// `rebase_fixes` is how many times a *conflict* was given to a fixer. When the fixer cannot finish the
5821    /// rebase the branch is restored, `state.base_sync.conflict` is set with
5822    /// what was tried (rounds spent, paths still conflicted) and the branch
5823    /// and worktree stay exactly as they were - untouched, for a person to
5824    /// look at - which is also what makes re-entering this function
5825    /// afterwards a no-op instead of a second attempt at the same wall. A
5826    /// push failure ends the same way.
5827    async fn sync_to_base(&mut self) -> Result<()> {
5828        if self.state.status == RunStatus::AlreadyInBase {
5829            return Ok(());
5830        }
5831        self.hold_base_sync().await?;
5832        let Some(winner) = self.state.winner().cloned() else {
5833            return Ok(());
5834        };
5835
5836        crate::worktree_clean::resume_pending(&mut self.state, &winner.worktree).await?;
5837
5838        let repo = self.state.repo.clone();
5839        let remote = self.state.config.merge.remote.clone();
5840        let base_branch = self.state.base_branch.clone();
5841        let tracking = format!("{remote}/{base_branch}");
5842
5843        let fetched_base =
5844            matches!(git::fetch(&repo, &remote, &base_branch).await, Ok(o) if o.ok());
5845        if !fetched_base
5846            && self
5847                .state
5848                .base_sync_recovery
5849                .stop
5850                .as_ref()
5851                .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Divergence)
5852        {
5853            self.state.event(
5854                "land",
5855                "cannot recheck recorded public branch divergence without a fresh base",
5856            );
5857            self.state.save()?;
5858            return Ok(());
5859        }
5860        // No network, or the remote never had this branch: the run already
5861        // started from a fetched `<remote>/<base>` (`resolve_base` refuses
5862        // otherwise), and one that got this far is not blocked by a fetch
5863        // that fails now. It just has no newer tip to compare against.
5864        let Ok(mut tip) = git::rev_parse(&repo, &tracking).await else {
5865            return Ok(());
5866        };
5867
5868        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
5869        self.state.ensure_base_episode();
5870        let scratch = self.state.dir().join("base-sync");
5871        self.resume_legacy_sequencer_stop(&winner, &scratch, &head)
5872            .await?;
5873        let conflicted = self
5874            .state
5875            .base_sync
5876            .as_ref()
5877            .is_some_and(|s| s.conflict.is_some());
5878        let mut pending = self.state.pending_base_operation().cloned();
5879        let in_progress = match crate::rebase::checked_progress(&mut self.state, &scratch, "").await
5880        {
5881            Ok(active) => active,
5882            Err(error) if error.is::<crate::repo_lock::ResourceBlocked>() => return Ok(()),
5883            Err(error) => return Err(error),
5884        };
5885        if in_progress {
5886            // Older resource stops predate operation reservations. Import the
5887            // standing Git operation, never retarget it to today's main.
5888            if pending.is_none()
5889                && self.state.base_sync_recovery.operations.is_empty()
5890                && !conflicted
5891                && crate::rebase::saved_base_identity(&scratch, &winner.branch)
5892                    .await
5893                    .ok()
5894                    .as_deref()
5895                    == Some(head.as_str())
5896                && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
5897                && git::is_clean(&winner.worktree).await?
5898            {
5899                let saved_tip = crate::rebase::rebase_target(&scratch).await?;
5900                if self.state.base_sync.is_none() {
5901                    self.state.base_sync = Some(BaseSync {
5902                        tip: saved_tip.clone(),
5903                        behind: 0,
5904                        attempts: 0,
5905                        conflict: None,
5906                        already_in: None,
5907                    });
5908                }
5909                self.state.reserve_base_operation(&head, &saved_tip);
5910                self.state.event(
5911                    "base-recovery",
5912                    "imported standing legacy rebase as a spent synchronization reservation",
5913                );
5914                self.state.save()?;
5915                pending = self.state.base_sync_recovery.operations.last().cloned();
5916            }
5917            let expected = pending.as_ref().map(|op| op.tip.as_str());
5918            if expected.is_none()
5919                || crate::rebase::rebase_target(&scratch).await.as_deref().ok() != expected
5920            {
5921                let why = "saved scratch rebase targets a different base; inspect the retained rebase before resuming";
5922                if self.state.base_sync.is_none() {
5923                    self.state.base_sync = Some(BaseSync {
5924                        tip: tip.clone(),
5925                        behind: 0,
5926                        attempts: 0,
5927                        conflict: None,
5928                        already_in: None,
5929                    });
5930                }
5931                self.state.base_sync.as_mut().unwrap().conflict = Some(why.into());
5932                self.state.event("land", why);
5933                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Unknown)
5934                    .await?;
5935                return Ok(());
5936            }
5937        }
5938        if let Some(op) = &pending {
5939            // A replay may add the pinned base's commits, never foreign work.
5940            let mut replay_proven =
5941                head == op.head || op.validated_head.as_deref() == Some(head.as_str());
5942            if !replay_proven && !in_progress && scratch.try_exists()? {
5943                let wait = repository_wait(&self.state, None);
5944                let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
5945                match crate::rebase::recover_completed_base(&self.state, &scratch, &winner.branch, op, &head).await {
5946                    Ok(true) => {
5947                        self.state.base_sync_recovery.operations.last_mut().unwrap().validated_head = Some(head.clone());
5948                        self.state.save()?;
5949                        git::worktree_remove(&repo, &scratch).await.ok();
5950                        replay_proven = true;
5951                    }
5952                    Ok(false) => self.state.event("base-recovery", "completed scratch failed result validation; retained for inspection"),
5953                    Err(error) => self.state.event("base-recovery", format!("completed scratch could not be validated; retained for inspection: {error:#}")),
5954                }
5955            }
5956            if !replay_proven && git::is_ancestor(&repo, &op.tip, &head).await {
5957                if self.state.foreign_checkout.is_some() {
5958                    replay_proven = git::rev_parse(&repo, &format!("{head}^1"))
5959                        .await
5960                        .ok()
5961                        .as_deref()
5962                        == Some(op.head.as_str())
5963                        && git::rev_parse(&repo, &format!("{head}^2"))
5964                            .await
5965                            .ok()
5966                            .as_deref()
5967                            == Some(op.tip.as_str());
5968                } else if crate::reconcile::origin_missing(&repo, &head, &op.head)
5969                    .await
5970                    .is_ok_and(|m| m.is_empty())
5971                    && let Ok(added) =
5972                        crate::reconcile::origin_missing(&repo, &op.head, &head).await
5973                {
5974                    replay_proven = true;
5975                    for commit in added {
5976                        if !git::is_ancestor(&repo, &commit, &op.tip).await {
5977                            replay_proven = false;
5978                            break;
5979                        }
5980                    }
5981                    replay_proven &= git::commits_ahead(&repo, &op.tip, &head).await?
5982                        <= git::commits_ahead(&repo, &op.tip, &op.head).await?;
5983                }
5984            }
5985            // Never retarget an operation across a crash, even if main moved.
5986            // sync_to_head resets and cleans with -x, so even ignored untracked
5987            // files must stop recovery independently of the old tracked tree.
5988            if git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
5989                || (head != op.head
5990                    && !git::git(&winner.worktree, &["ls-files", "--others", "-z"])
5991                        .await?
5992                        .is_empty())
5993                || (!git::is_clean(&winner.worktree).await?
5994                    && !git::git_raw(&winner.worktree, &["diff", "--quiet", &op.head])
5995                        .await
5996                        .is_ok_and(|o| o.ok()))
5997                || !replay_proven
5998            {
5999                let why = format!(
6000                    "unfinished base synchronization {} has unrecognized branch/worktree state; inspect the retained branch and scratch rebase before resuming",
6001                    op.id
6002                );
6003                let sync = self
6004                    .state
6005                    .base_sync
6006                    .as_mut()
6007                    .context("reserved synchronization has no lifetime accounting")?;
6008                sync.conflict = Some(why.clone());
6009                self.state.event("land", why);
6010                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Unknown)
6011                    .await?;
6012                return Ok(());
6013            }
6014            if head != op.head {
6015                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6016            }
6017            tip = op.tip.clone();
6018        }
6019        let behind = git::commits_ahead(&repo, &head, &tip).await.unwrap_or(0);
6020        let attempts = self.state.base_sync.as_ref().map_or(0, |s| s.attempts);
6021        if pending.is_none()
6022            && !conflicted
6023            && fetched_base
6024            && self
6025                .state
6026                .base_sync_recovery
6027                .episodes
6028                .last()
6029                .is_some_and(|e| e.boundary.is_some())
6030            && let Some(task) = self.state.origin.as_ref().and_then(|o| o.task.clone())
6031            && let Ok(owner) = crate::queue::Queue::open().get(&task)
6032            && owner.execution_runs().last() == Some(&self.state.id)
6033            && owner.status != crate::queue::TaskStatus::Done
6034            && !owner.fresh_start
6035            && owner.review_branch.is_none()
6036            && crate::daemon::compatible_run_instruction(&self.state, &owner)
6037            && let Some(approval) = owner.resumption.as_ref()
6038            && approval.instruction == owner.instruction
6039            && git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? == head
6040            && git::is_clean(&winner.worktree).await?
6041            && self.state.renew_base_episode(&task, approval, &head, &tip)
6042        {
6043            self.state.event("base-recovery", "opened bounded synchronization interval after owner-approved infrastructure recovery");
6044            self.state.save()?;
6045        }
6046
6047        // Before any rebase, and before a recorded conflict is honoured: a
6048        // branch whose change reached the base under other commit ids has
6049        // nothing to rebase and nothing to conflict with, and a run that
6050        // already stopped on that phantom conflict recovers here on resume.
6051        // `behind == 0` with head == tip is a branch the base has since taken
6052        // in whole, whether or not a conflict was ever recorded: the ancestry
6053        // proof must still run (`classify` ignores a head still on the start
6054        // commit).
6055        if (behind > 0 || conflicted || head == tip)
6056            && self
6057                .settle_already_in(&winner.branch, &tip, &head, attempts, behind)
6058                .await?
6059        {
6060            return Ok(());
6061        }
6062        if conflicted && self.state.base_recovery_pending() {
6063            let authorization = self.state.base_sync_recovery.authorizations.last().unwrap();
6064            let owner =
6065                crate::queue::Queue::at(crate::run::home().join("queue")).get(&authorization.task);
6066            let owner_valid = owner.as_ref().is_ok_and(|t| {
6067                t.execution_runs().last() == Some(&self.state.id)
6068                    && t.assignment_accepts(&self.state)
6069                    && t.status != crate::queue::TaskStatus::Done
6070                    && !t.fresh_start
6071                    && t.review_branch.is_none()
6072            });
6073            let invalidation = if !owner_valid {
6074                Some("latest task ownership changed")
6075            } else if !owner.as_ref().is_ok_and(|t| {
6076                authorization
6077                    .generation
6078                    .is_none_or(|g| t.resumption.as_ref().is_some_and(|r| r.generation == g))
6079            }) {
6080                Some("owner approval generation changed")
6081            } else if authorization.question.as_ref().is_some_and(|question| {
6082                !crate::base_recovery_control::decision_current(
6083                    &crate::queue::Queue::at(crate::run::home().join("queue")),
6084                    &self.state,
6085                    &authorization.task,
6086                    question,
6087                )
6088            }) {
6089                Some("recovery decision ownership, routing or stop evidence changed")
6090            } else if authorization.request.is_some()
6091                && !owner
6092                    .as_ref()
6093                    .is_ok_and(|t| t.operator_decided_at == authorization.decision)
6094            {
6095                Some("owner decision changed")
6096            } else if authorization.stop.kind == crate::base_sync_recovery::StopKind::Unknown
6097                && !authorization.scope.as_ref().is_some_and(|scope| {
6098                    scope.preparation_digest.is_some()
6099                        && scope.preparation_digest == self.state.preparation_digest(&head)
6100                })
6101            {
6102                Some("scratch preparation stop evidence changed")
6103            } else if let Some(scope) = &authorization.scope {
6104                if scope.tip != tip {
6105                    Some("fetched base changed")
6106                } else if !self
6107                    .state
6108                    .base_sync_recovery
6109                    .episodes
6110                    .last()
6111                    .is_some_and(|e| e.id == scope.episode)
6112                {
6113                    Some("active synchronization interval changed")
6114                } else if !owner
6115                    .as_ref()
6116                    .is_ok_and(|t| t.instruction == scope.instruction)
6117                {
6118                    Some("task instruction changed")
6119                } else {
6120                    None
6121                }
6122            } else {
6123                None
6124            };
6125            if let Some(reason) = invalidation {
6126                let authorization = self
6127                    .state
6128                    .base_sync_recovery
6129                    .authorizations
6130                    .last_mut()
6131                    .unwrap();
6132                authorization.refuse(format!("{reason}; authorize again with --recover-base"));
6133                self.state.save()?;
6134                return Ok(());
6135            }
6136            if !fetched_base
6137                || git::rev_parse(&repo, &format!("refs/heads/{}", winner.branch)).await? != head
6138                || !git::is_clean(&winner.worktree).await?
6139                || !owner.is_ok_and(|t| t.execution_runs().last() == Some(&self.state.id))
6140            {
6141                return Ok(());
6142            }
6143            if authorization.stop.kind == crate::base_sync_recovery::StopKind::Unknown {
6144                git::check_rebase_preparation(&self.state, &head, &self.state.dir()).await?;
6145            }
6146        }
6147        let recovery = conflicted && self.state.consume_base_recovery(&head);
6148        if conflicted {
6149            // Consumption (including a refused changed HEAD) is durable before Git.
6150            self.state.save()?;
6151            if !recovery {
6152                return Ok(());
6153            }
6154        }
6155
6156        if behind == 0 {
6157            // A fixer-finished rebase moves the branch ref before the
6158            // winner's worktree is told (`sync_to_head` below). A run that
6159            // died in between resumes here with `behind == 0` and a tree still
6160            // holding the pre-rebase files, which review and the gate would
6161            // then read. That state is exactly: HEAD moved off the tip the
6162            // rebase started from, yet the tree is still identical to that
6163            // tip. A tree with edits of its own differs from it, so nothing
6164            // is thrown away.
6165            if let Some(from) = self
6166                .state
6167                .rebase_fixes
6168                .iter()
6169                .rev()
6170                .find_map(|r| r.from.clone())
6171                && from != head
6172                && git::git_raw(&winner.worktree, &["diff", "--quiet", &from])
6173                    .await
6174                    .is_ok_and(|o| o.ok())
6175            {
6176                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6177            }
6178            // An earlier attempt may have rebased the branch locally and died
6179            // before pushing it (only the fresh-rebase arm below pushes).
6180            // Publish it now, so the plain push at PR time is not refused as
6181            // a non-fast-forward. A run already holding a recorded conflict
6182            // never reaches here; that case is out of scope.
6183            let conflict = self.publish_resumed_rebase(&winner.branch, &head).await;
6184            if let Some(why) = &conflict {
6185                self.state.status = RunStatus::Blocked;
6186                self.state.event("land", why.clone());
6187            }
6188            self.state.base_sync = Some(BaseSync {
6189                tip,
6190                behind: 0,
6191                attempts,
6192                conflict,
6193                already_in: None,
6194            });
6195            if pending.is_some() {
6196                self.state.finish_base_operation(Some(&head));
6197            }
6198            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Publication)
6199                .await?;
6200            self.state.save()?;
6201            return Ok(());
6202        }
6203
6204        if self.state.base_episode_used() >= BASE_SYNC_ROUNDS && pending.is_none() && !recovery {
6205            let why = format!(
6206                "{base_branch} moved {behind} commit(s) ahead of {} after {BASE_SYNC_ROUNDS} \
6207                 synchronization(s); synchronizing again would only race it",
6208                winner.branch
6209            );
6210            self.state.status = RunStatus::Blocked;
6211            self.state.base_sync = Some(BaseSync {
6212                tip,
6213                behind,
6214                attempts,
6215                conflict: Some(why.clone()),
6216                already_in: None,
6217            });
6218            self.state.event("land", why);
6219            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Exhausted)
6220                .await?;
6221            self.state.save()?;
6222            return Ok(());
6223        }
6224
6225        if self.state.foreign_checkout.is_some() {
6226            // Delivery to the operator's checkout is fast-forward only. A
6227            // rebase here would discard its saved head from our ancestry.
6228            let wait = repository_wait(&self.state, None);
6229            let _coordination = coordinate_operation(&mut self.state, &repo, &wait).await?;
6230            if self.state.base_sync.is_none() {
6231                self.state.base_sync = Some(BaseSync {
6232                    tip: tip.clone(),
6233                    behind,
6234                    attempts: 0,
6235                    conflict: None,
6236                    already_in: None,
6237                });
6238            }
6239            self.state.reserve_base_operation(&head, &tip);
6240            self.state.save()?;
6241            let merged = git::git_raw(
6242                &winner.worktree,
6243                &[
6244                    "-c",
6245                    "core.hooksPath=/dev/null",
6246                    "merge",
6247                    "--no-ff",
6248                    "--no-autostash",
6249                    "--no-edit",
6250                    "-m",
6251                    &format!("Merge {tracking} before verifying"),
6252                    &tip,
6253                ],
6254            )
6255            .await?;
6256            let conflict = if merged.ok() {
6257                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
6258                self.state.event(
6259                    "land",
6260                    format!("merged {tracking} into {} before verifying", winner.branch),
6261                );
6262                None
6263            } else {
6264                if git::rev_exists(&winner.worktree, "MERGE_HEAD").await {
6265                    git::git(&winner.worktree, &["merge", "--abort"]).await?;
6266                }
6267                let why = format!(
6268                    "could not merge {tracking} into {} without rewriting foreign checkout history: {}",
6269                    winner.branch,
6270                    merged.stderr.chars().take(600).collect::<String>()
6271                );
6272                self.state.status = RunStatus::Blocked;
6273                self.state.event("land", &why);
6274                Some(why)
6275            };
6276            let synced = conflict.is_none();
6277            let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
6278            self.state
6279                .finish_base_operation(synced.then_some(fresh.as_str()));
6280            let attempts = self.state.base_sync.as_ref().unwrap().attempts;
6281            self.state.base_sync = Some(BaseSync {
6282                tip,
6283                behind: if synced { 0 } else { behind },
6284                attempts,
6285                conflict,
6286                already_in: None,
6287            });
6288            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Conflict)
6289                .await?;
6290            self.state.save()?;
6291            return Ok(());
6292        }
6293
6294        self.state.event(
6295            "land",
6296            format!(
6297                "{base_branch} moved {behind} commit(s) ahead of {}; rebasing before verifying",
6298                winner.branch
6299            ),
6300        );
6301        self.state.save()?;
6302
6303        // The remote's copy of the branch, read now and only if the fetch
6304        // really succeeded (a stale tracking ref must never pin a lease). It is
6305        // pushed over after a rebase only when it is a commit this branch
6306        // already contains, by ancestry or by patch (an earlier rebase of ours
6307        // that never reached the remote): anything else is somebody else's work.
6308        let branch_tracking = format!("{remote}/{}", winner.branch);
6309        let fetched_branch = git::fetch(&repo, &remote, &winner.branch).await;
6310        let remote_tip = if self.state.task_pr_branch().is_none()
6311            && matches!(&fetched_branch, Ok(o) if o.ok())
6312        {
6313            git::rev_parse(&repo, &branch_tracking).await.ok()
6314        } else {
6315            None
6316        };
6317        // A remote tip this branch does not contain is somebody else's work:
6318        // rebasing would leave a local tip that can never be pushed. Stop
6319        // before touching anything and say so.
6320        if let Some(theirs) = &remote_tip
6321            && !git::is_ancestor(&repo, theirs, &head).await
6322            && !crate::reconcile::origin_missing(&repo, &head, theirs)
6323                .await
6324                .is_ok_and(|missing| missing.is_empty())
6325        {
6326            let why = format!(
6327                "{branch_tracking} ({}) has commits {} does not contain; not rebasing over \
6328                 them",
6329                short(theirs),
6330                winner.branch
6331            );
6332            self.state.status = RunStatus::Blocked;
6333            self.state.base_sync = Some(BaseSync {
6334                tip,
6335                behind,
6336                attempts,
6337                conflict: Some(why.clone()),
6338                already_in: None,
6339            });
6340            self.state.event("land", why);
6341            self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::Divergence)
6342                .await?;
6343            self.state.save()?;
6344            return Ok(());
6345        }
6346
6347        if self.state.base_sync.is_none() {
6348            self.state.base_sync = Some(BaseSync {
6349                tip: tip.clone(),
6350                behind,
6351                attempts: 0,
6352                conflict: None,
6353                already_in: None,
6354            });
6355        }
6356        let scratch = self.state.dir().join("base-sync");
6357        if let Err(error) = crate::rebase::prepare(&mut self.state, &scratch, &winner.branch).await
6358        {
6359            if error.is::<crate::repo_lock::ResourceBlocked>() {
6360                return Ok(());
6361            }
6362            return Err(error);
6363        }
6364        self.state.reserve_base_operation(&head, &tip);
6365        self.state.save()?;
6366        let rebased =
6367            match crate::rebase::rebase_prepared(&mut self.state, &scratch, &winner.branch, &tip)
6368                .await
6369            {
6370                Ok(crate::rebase::Rebased::Applied) => Ok(None),
6371                Ok(crate::rebase::Rebased::Stopped(why)) => Ok(Some(why)),
6372                Err(e) => Err(e),
6373            };
6374        let attempts = self.state.base_sync.as_ref().unwrap().attempts;
6375        let stop_kind = match &rebased {
6376            Ok(None) => crate::base_sync_recovery::StopKind::Publication,
6377            Ok(Some(_)) => crate::base_sync_recovery::StopKind::Conflict,
6378            Err(_) => crate::base_sync_recovery::StopKind::Unknown,
6379        };
6380        match rebased {
6381            Ok(None) => {
6382                // The branch ref moved, but a worktree that already had it
6383                // checked out (the winner's) was not told; sync its index and
6384                // files before anything reads them.
6385                crate::worktree_clean::reset(&mut self.state, &winner.worktree, None).await?;
6386                let fresh = git::rev_parse(&winner.worktree, "HEAD").await?;
6387                self.state.finish_base_operation(Some(&fresh));
6388                refresh_reviewed_commits(&mut self.state, &winner.branch).await;
6389                let mut conflict = None;
6390                if let Some(pinned) = &remote_tip {
6391                    let pushed = git::push_pinned(&repo, &remote, &winner.branch, pinned).await;
6392                    match pushed {
6393                        Ok(o) if o.ok() => self.state.event(
6394                            "land",
6395                            format!("pushed rebased {} to {remote}", winner.branch),
6396                        ),
6397                        Ok(o) => {
6398                            conflict = Some(format!(
6399                                "rebased {} locally but {remote} refused the push (it moved                                  since {}; someone may have pushed): {}",
6400                                winner.branch,
6401                                short(pinned),
6402                                o.stderr.chars().take(600).collect::<String>()
6403                            ));
6404                        }
6405                        Err(e) => {
6406                            conflict = Some(format!(
6407                                "rebased {} locally but could not push it: {e:#}",
6408                                winner.branch
6409                            ));
6410                        }
6411                    }
6412                }
6413                if let Some(why) = &conflict {
6414                    self.state.status = RunStatus::Blocked;
6415                    self.state.event("land", why.clone());
6416                }
6417                self.state.base_sync = Some(BaseSync {
6418                    tip: tip.clone(),
6419                    behind: 0,
6420                    attempts,
6421                    conflict,
6422                    already_in: None,
6423                });
6424                self.state
6425                    .event("land", format!("rebased {} onto {tracking}", winner.branch));
6426            }
6427            Ok(Some(conflict)) => {
6428                self.state.finish_base_operation(None);
6429                let why = format!(
6430                    "{} conflicts with {tracking} and did not rebase: {}",
6431                    winner.branch,
6432                    conflict.chars().take(600).collect::<String>()
6433                );
6434                self.state.status = RunStatus::Blocked;
6435                self.state.base_sync = Some(BaseSync {
6436                    tip,
6437                    behind,
6438                    attempts,
6439                    conflict: Some(why.clone()),
6440                    already_in: None,
6441                });
6442                self.state.event("land", why);
6443            }
6444            // A refused Git write or a busy repository: nothing is wrong with
6445            // the branch. The scratch rebase stays standing and the run
6446            // resumes into it (`base_sync` must not claim a conflict).
6447            Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
6448                self.state.save()?;
6449                return Ok(());
6450            }
6451            Err(e) => {
6452                self.state.finish_base_operation(None);
6453                let why = format!("could not rebase {} onto {tracking}: {e:#}", winner.branch);
6454                self.state.status = RunStatus::Blocked;
6455                self.state.base_sync = Some(BaseSync {
6456                    tip,
6457                    behind,
6458                    attempts,
6459                    conflict: Some(why.clone()),
6460                    already_in: None,
6461                });
6462                self.state.event("land", why);
6463            }
6464        }
6465        if !self.state.base_sync_blocked() {
6466            self.state.base_sync_recovery.stop = None;
6467        }
6468        self.hold_base_sync_kind(stop_kind).await?;
6469        self.state.save()?;
6470        Ok(())
6471    }
6472
6473    /// Push a branch an earlier attempt rebased locally but never published,
6474    /// pinned to the remote tip read right after a successful fetch. Returns
6475    /// the reason when the run must stop; `None` when there was nothing to do
6476    /// (no remote copy, the same tip, or a remote copy this branch already
6477    /// contains, which the PR-time push fast-forwards) or the push succeeded.
6478    async fn publish_resumed_rebase(&mut self, branch: &str, head: &str) -> Option<String> {
6479        // Task competitions publish only after the PR text gate, to their
6480        // public head; never resurrect a candidate branch on the remote.
6481        if self.state.task_pr_branch().is_some() {
6482            return None;
6483        }
6484        let repo = self.state.repo.clone();
6485        let remote = self.state.config.merge.remote.clone();
6486        let fetched = git::fetch(&repo, &remote, branch).await;
6487        if !matches!(&fetched, Ok(o) if o.ok()) {
6488            return None;
6489        }
6490        let branch_tracking = format!("{remote}/{branch}");
6491        let theirs = git::rev_parse(&repo, &branch_tracking).await.ok()?;
6492        if theirs == head || git::is_ancestor(&repo, &theirs, head).await {
6493            return None;
6494        }
6495        if !crate::reconcile::origin_missing(&repo, head, &theirs)
6496            .await
6497            .is_ok_and(|missing| missing.is_empty())
6498        {
6499            return Some(format!(
6500                "{branch_tracking} ({}) has commits {branch} does not contain; not pushing over \
6501                 them",
6502                short(&theirs)
6503            ));
6504        }
6505        match git::push_pinned(&repo, &remote, branch, &theirs).await {
6506            Ok(o) if o.ok() => {
6507                self.state
6508                    .event("land", format!("pushed rebased {branch} to {remote}"));
6509                None
6510            }
6511            Ok(o) => Some(format!(
6512                "{branch} is rebased locally but {remote} refused the push (it moved since {}; \
6513                 someone may have pushed): {}",
6514                short(&theirs),
6515                o.stderr.chars().take(600).collect::<String>()
6516            )),
6517            Err(e) => Some(format!(
6518                "{branch} is rebased locally but could not be pushed: {e:#}"
6519            )),
6520        }
6521    }
6522
6523    /// End the run as [`RunStatus::AlreadyInBase`] when `head`'s whole change
6524    /// is already on `tip` under other commit ids ([`crate::already`]); returns
6525    /// whether it did.
6526    ///
6527    /// Checked only when the base is ahead of the branch. A failing check is
6528    /// "not proven" - the ordinary rebase path then decides - never a reason to
6529    /// stop the run.
6530    ///
6531    /// The remote copy of the branch is held to the same standard as the local
6532    /// one: if it carries a tip this worktree does not, that tip must itself be
6533    /// proven in the base, or nothing is settled (a pull request would
6534    /// otherwise be closed over commits nobody checked). The pull request is
6535    /// closed *before* the terminal status is saved; if that fails for a
6536    /// reason other than a refusal (no network, a `gh` error) the run is left
6537    /// `Blocked` with the reason as its conflict, which a resume retries -
6538    /// the same recovery a phantom conflict gets.
6539    async fn settle_already_in(
6540        &mut self,
6541        branch: &str,
6542        tip: &str,
6543        head: &str,
6544        attempts: usize,
6545        behind: usize,
6546    ) -> Result<bool> {
6547        let repo = self.state.repo.clone();
6548        let remote = self.state.config.merge.remote.clone();
6549        let start = self.state.base_commit.clone();
6550        let evidence = match crate::already::classify(&repo, tip, head, Some(&start)).await {
6551            Ok(Some(e)) => e,
6552            Ok(None) => return Ok(false),
6553            Err(e) => {
6554                tracing::warn!("already-in-base check for {branch}: {e:#}");
6555                return Ok(false);
6556            }
6557        };
6558        let mut verified = vec![head.to_owned()];
6559        let public_branch = self.state.pr_branch().unwrap_or(branch).to_owned();
6560        let fetched = git::fetch(&repo, &remote, &public_branch).await;
6561        let divergence = self
6562            .state
6563            .base_sync_recovery
6564            .stop
6565            .as_ref()
6566            .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Divergence);
6567        if matches!(&fetched, Ok(o) if o.ok()) {
6568            match git::rev_parse(&repo, &format!("{remote}/{public_branch}")).await {
6569                Ok(theirs) if theirs != head => {
6570                    match crate::already::classify(&repo, tip, &theirs, Some(&start)).await {
6571                        Ok(Some(_)) => verified.push(theirs),
6572                        _ => return Ok(false),
6573                    }
6574                }
6575                Err(_) if divergence => return Ok(false),
6576                _ => {}
6577            }
6578        } else if divergence
6579            && !matches!(
6580                git::remote_has_branch(&repo, &remote, &public_branch).await,
6581                Ok(false)
6582            )
6583        {
6584            // A failed fetch cannot discharge a recorded divergence.
6585            return Ok(false);
6586        }
6587        let base_branch = self.state.base_branch.clone();
6588        let message = format!(
6589            "{branch} is already in {remote}/{base_branch} as {} ({} match); nothing left to \
6590             land",
6591            evidence.names(),
6592            evidence.proof.as_str()
6593        );
6594        let closed =
6595            crate::land::close_superseded_pr(&mut self.state, &public_branch, &evidence, &verified)
6596                .await;
6597        match closed {
6598            Ok(Ok(url)) => self
6599                .state
6600                .event("land", format!("closed {url}: superseded on {base_branch}")),
6601            Ok(Err(why)) => self
6602                .state
6603                .event("land", format!("did not close a pull request: {why}")),
6604            Err(e) => {
6605                let why = format!(
6606                    "{branch} is already in {remote}/{base_branch}, but its pull request could \
6607                     not be closed ({e:#}); resume to retry"
6608                );
6609                self.state.status = RunStatus::Blocked;
6610                self.state.base_sync = Some(BaseSync {
6611                    tip: tip.to_owned(),
6612                    behind,
6613                    attempts,
6614                    conflict: Some(why.clone()),
6615                    already_in: None,
6616                });
6617                self.state.event("land", why);
6618                self.hold_base_sync_kind(crate::base_sync_recovery::StopKind::ClosingIntegratedPr)
6619                    .await?;
6620                self.state.save()?;
6621                return Ok(true);
6622            }
6623        }
6624        self.state.status = RunStatus::AlreadyInBase;
6625        self.state.base_sync_recovery.stop = None;
6626        self.state.base_sync = Some(BaseSync {
6627            tip: tip.to_owned(),
6628            behind,
6629            attempts,
6630            conflict: None,
6631            already_in: Some(evidence),
6632        });
6633        self.state.event("land", message);
6634        self.state.save()?;
6635        self.settle_questions();
6636        Ok(true)
6637    }
6638
6639    /// The commit review and gate diff against: the tip [`Self::sync_to_base`]
6640    /// last landed the winner on, once it has run, else the commit the run
6641    /// branched from.
6642    ///
6643    /// Only [`Self::review_loop`] reads this. `prep`, `judge`, `deliberate`
6644    /// and `vote` all happen before there is a winner to rebase, so they
6645    /// compare every candidate against the branch point on purpose, and a
6646    /// base that moves after they are already done cannot change an answer
6647    /// they already gave.
6648    fn landing_base(&self) -> String {
6649        self.state
6650            .base_sync
6651            .as_ref()
6652            .map_or_else(|| self.state.base_commit.clone(), |s| s.tip.clone())
6653    }
6654
6655    // ------------------------------------------------------- operator fix
6656
6657    /// Route specific, already-recorded review findings to a fixer for a
6658    /// targeted, out-of-band fix on the winning branch — `magi fix`'s own
6659    /// entry point.
6660    ///
6661    /// Distinct from `review_loop`'s own fix step in three ways: it never
6662    /// runs a reviewer wave, it never spends review-round budget, and what
6663    /// happened is recorded as an [`OperatorFixRequest`] appended to
6664    /// [`RunState::operator_fixes`], never folded into a [`ReviewRound`] —
6665    /// see `run::SCHEMA`'s doc for schema 9 on why a reviewer's own severity
6666    /// and vote must never be rewritten to look like a manufactured blocking
6667    /// verdict.
6668    ///
6669    /// Only meaningful once review has actually concluded: `Ready` (handed
6670    /// off with findings still open, or simply concluded clean while minor
6671    /// findings sat unaddressed) or `Blocked` (round budget spent, or the
6672    /// gate failed). Everything else is refused: a run still in progress
6673    /// should simply be resumed, and a `Merged` run's branch has already
6674    /// landed — reopening *this* run's own record cannot change that, so the
6675    /// answer there is a fresh `magi review <branch>`.
6676    ///
6677    /// A real commit here re-verifies through a fresh, ordinary review-only
6678    /// run on the same branch ([`Self::review`]) rather than reopening this
6679    /// run's own `review_loop`: once any round in this run's history went
6680    /// clean, `review_conclusion` treats that as permanent by design (the
6681    /// same purity `gate`/`merge` rely on for safe reentry), so there is no
6682    /// way to force one more genuine reviewer wave out of *this* run without
6683    /// either rewriting history or weakening that guarantee for every other
6684    /// caller. A review-only run costs nothing extra — no implementation, no
6685    /// judging, no vote — and exercises the exact same review → verify →
6686    /// gate → (human) merge path, unmodified.
6687    pub async fn fix_selected(
6688        &mut self,
6689        ids: &[String],
6690        reason: &str,
6691        allow_stale: bool,
6692    ) -> Result<()> {
6693        let reason = reason.trim();
6694        if reason.is_empty() {
6695            bail!("a fix request needs a reason — that is the operator's own record of why");
6696        }
6697        if ids.is_empty() {
6698            bail!("no finding id given");
6699        }
6700        if !matches!(self.state.status, RunStatus::Ready | RunStatus::Blocked) {
6701            bail!(
6702                "run {} is `{}`; only a `ready` or `blocked` run — one whose review \
6703                 has already concluded — can be given a targeted fix. A run still \
6704                 in progress should simply be resumed; a `merged` run's branch has \
6705                 already landed, so its answer is a fresh `magi review <branch>`, \
6706                 not reopening this run's own record",
6707                self.state.id,
6708                self.state.status.as_str()
6709            );
6710        }
6711        // Reassignment shares this claim through its atomic task save. Check
6712        // the canonical run identity inside it, before preflight or any await.
6713        let _claim = FixClaim::acquire(&self.state.dir())?;
6714        crate::task_reassign::ensure_current(&crate::queue::Queue::open(), &self.state.id)?;
6715        let home = crate::run::home();
6716        // The ordinary driver takes these same locks at admission. Keep the
6717        // execution lease through the fix, but never the owner lock across Git
6718        // or agent awaits.
6719        let execution = {
6720            let _owner = crate::pr_head::owner_lock(&home, &self.state.id)?;
6721            let disk = RunState::load(&self.state.id)?;
6722            crate::pr_head::ensure_owner(&disk)?;
6723            anyhow::ensure!(
6724                disk.status == self.state.status && disk.released_to.is_none(),
6725                "run changed since it was loaded; reload before fixing"
6726            );
6727            let claimed = crate::daemon::is_working_on(&home, &disk.id, Timestamp::now());
6728            anyhow::ensure!(
6729                disk.liveness_under(&home, claimed) == crate::run::Liveness::Dead,
6730                "run {} is currently being worked on or its ownership is unknown",
6731                disk.id
6732            );
6733            let lease = crate::driver::maintenance(&home, &disk.id).context(
6734                "run is currently being worked on or its execution lease is unavailable",
6735            )?;
6736            self.state = disk;
6737            lease
6738        };
6739        let Some(winner) = self.state.winner().cloned() else {
6740            bail!("run {} has no winning candidate to fix", self.state.id);
6741        };
6742        if !git::branch_exists(&self.state.repo, &winner.branch).await? {
6743            bail!(
6744                "branch `{}` no longer exists; this run cannot be extended",
6745                winner.branch
6746            );
6747        }
6748        // Resolve every id before spending anything — an unknown id refuses
6749        // the whole request rather than silently dropping it — and dedup
6750        // while keeping the operator's own order.
6751        let mut seen = BTreeSet::new();
6752        let mut findings = Vec::new();
6753        let mut missing = Vec::new();
6754        for id in ids {
6755            if !seen.insert(id.clone()) {
6756                continue;
6757            }
6758            match self.state.finding(id) {
6759                Some((round, rec, f)) => findings.push(OperatorFixFinding {
6760                    id: f.id.clone(),
6761                    severity: f.severity,
6762                    reviewer_vote: rec.vote,
6763                    round: round.round,
6764                    round_head: round.head.clone(),
6765                    reviewer: rec.reviewer,
6766                    agent: rec.agent.clone(),
6767                    file: f.file.clone(),
6768                    line: f.line,
6769                    title: f.title.clone(),
6770                    detail: f.detail.clone(),
6771                    outcome: OperatorFixOutcome::Pending,
6772                }),
6773                None => missing.push(id.clone()),
6774            }
6775        }
6776        if !missing.is_empty() {
6777            bail!(
6778                "unknown finding id(s): {}; nothing was changed",
6779                missing.join(", ")
6780            );
6781        }
6782
6783        let head_at_request = git::rev_parse(&self.state.repo, &winner.branch).await?;
6784        let stale_details: Vec<(String, String)> = findings
6785            .iter()
6786            .filter(|f| f.round_head != head_at_request)
6787            .map(|f| (f.id.clone(), f.round_head.clone()))
6788            .collect();
6789        let stale = !stale_details.is_empty();
6790        if stale && !allow_stale {
6791            bail!(
6792                "the branch has moved since some finding(s) were raised — {} — now \
6793                 at {}; pass --allow-stale to fix anyway, or re-run review first",
6794                stale_details
6795                    .iter()
6796                    .map(|(id, head)| format!("{id} (raised against {})", short(head)))
6797                    .collect::<Vec<_>>()
6798                    .join(", "),
6799                short(&head_at_request)
6800            );
6801        }
6802
6803        let request = OperatorFixRequest {
6804            requested_at: Timestamp::now(),
6805            reason: reason.to_owned(),
6806            findings,
6807            head_at_request: head_at_request.clone(),
6808            allow_stale,
6809            stale,
6810            fix: None,
6811            result_head: None,
6812            follow_up_review_run: None,
6813        };
6814        self.state.event(
6815            "fix",
6816            format!(
6817                "operator requested a targeted fix on {} finding(s) ({}): {reason}",
6818                request.findings.len(),
6819                request
6820                    .findings
6821                    .iter()
6822                    .map(|f| f.id.as_str())
6823                    .collect::<Vec<_>>()
6824                    .join(", "),
6825            ),
6826        );
6827        // Recorded now, before any worktree work or the fixer call itself —
6828        // and re-saved at each checkpoint below: a crash at any point after
6829        // this (mid fixer call, mid follow-up review) must not lose the fact
6830        // that this was requested, for which findings, and why. Everything
6831        // past this point reads and writes through `request_index` rather
6832        // than a local variable, since `request` itself is moved here.
6833        self.state.operator_fixes.push(request);
6834        self.state.save()?;
6835        let request_index = self.state.operator_fixes.len() - 1;
6836
6837        // A fresh, dedicated worktree for this one call, never the winner's
6838        // own worktree in place: that one may already be gone (folded away),
6839        // and reusing it in place would leave the branch checked out there
6840        // when the follow-up review below tries to check it out again. Freed
6841        // immediately after, either way — but only once confirmed clean:
6842        // `worktree_remove` is a `git worktree remove --force`, which would
6843        // otherwise discard uncommitted work left there by the operator or
6844        // another process before this had a chance to even look at it.
6845        let repo = self.state.repo.clone();
6846        let coordination = self.coordinate(&repo).await?;
6847        if winner.worktree.exists() {
6848            // Lockfiles a rescue commit withheld stay untracked on purpose and
6849            // are already recorded; they are not the operator's work to protect.
6850            let dirty = git::git(
6851                &winner.worktree,
6852                &["status", "--porcelain", "--untracked-files=all"],
6853            )
6854            .await?;
6855            let only_withheld = dirty.lines().all(|l| {
6856                l.strip_prefix("?? ")
6857                    .is_some_and(|p| self.state.withheld.iter().any(|w| w.path == p))
6858            });
6859            if !only_withheld {
6860                bail!(
6861                    "`{}` has uncommitted changes; refusing to touch it — commit or \
6862                     discard them first",
6863                    winner.worktree.display()
6864                );
6865            }
6866            git::worktree_remove(&self.state.repo, &winner.worktree)
6867                .await
6868                .ok();
6869        }
6870        let fix_worktree = self.state.worktree_root().join("operator-fix");
6871        let fix_worktree_s = fix_worktree.to_string_lossy().to_string();
6872        git::git(
6873            &self.state.repo,
6874            &["worktree", "add", &fix_worktree_s, winner.branch.as_str()],
6875        )
6876        .await
6877        .with_context(|| format!("checking out `{}` for the fix", winner.branch))?;
6878        if !git::is_clean(&fix_worktree).await? {
6879            git::worktree_remove(&self.state.repo, &fix_worktree)
6880                .await
6881                .ok();
6882            bail!(
6883                "`{}` has uncommitted changes; refusing to start a fix on a dirty tree",
6884                winner.branch
6885            );
6886        }
6887        let repo_for_setup = self.state.repo.clone();
6888        let setup = match ensure_setup_config(&mut self.state, &repo_for_setup).await {
6889            Ok(()) => {
6890                worktree_setup::prepare_with(
6891                    &self.state.config,
6892                    &repo_for_setup,
6893                    &fix_worktree,
6894                    crate::build_target::Coordination::Held(coordination.as_ref()),
6895                )
6896                .await
6897            }
6898            Err(e) => Err(e),
6899        };
6900        if let Err(e) = setup {
6901            git::worktree_remove(&self.state.repo, &fix_worktree)
6902                .await
6903                .ok();
6904            return Err(e);
6905        }
6906
6907        // This explicit operator request retries availability independently
6908        // of execute(); the previous call has already saved and cleaned up.
6909        self.state.resource_block = None;
6910
6911        let run_id = self.state.id.clone();
6912        let prompts = self.state.config.prompts.clone();
6913        let language = self.state.config.graph.language.clone();
6914        let sessions = self.state.config.graph.sessions;
6915        let artifacts = agent::artifacts_dir(&self.state.dir());
6916        let finding_list: Vec<Finding> = self.state.operator_fixes[request_index]
6917            .findings
6918            .iter()
6919            .map(|f| Finding {
6920                id: f.id.clone(),
6921                severity: f.severity,
6922                file: f.file.clone(),
6923                line: f.line,
6924                title: f.title.clone(),
6925                detail: f.detail.clone(),
6926            })
6927            .collect();
6928        let fix_prompt = prompt::operator_fix_in(
6929            &self.state.instruction,
6930            &finding_list,
6931            reason,
6932            &stale_details,
6933            &head_at_request,
6934            &language,
6935            &self.state.config.graph.github_language,
6936        );
6937        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
6938        drop(coordination);
6939        let (job, seat, out) = self
6940            .ask_fixer(&winner, "fix", None, |spec, seat| SeatJob {
6941                prompt: fix_prompt.clone(),
6942                spec,
6943                seat,
6944                cwd: fix_worktree.clone(),
6945                timeout,
6946                allow_write: true,
6947                sessions,
6948                artifacts: artifacts.clone(),
6949                stem: "operator-fix".to_owned(),
6950                handover: None,
6951            })
6952            .await;
6953        let agent_id = seat.agent.clone();
6954
6955        let mut fix = FixRecord {
6956            agent: agent_id,
6957            addressed: Vec::new(),
6958            rejected: Vec::new(),
6959            notes: String::new(),
6960            committed: false,
6961            failed: None,
6962            duration_ms: 0,
6963            continuation: None,
6964        };
6965        let mut final_seat = seat.clone();
6966        match out {
6967            AgentOutcome::Ok(o) => {
6968                fix.duration_ms = o.duration_ms;
6969                let parsed = verdict::extract_json::<FixReport>(&o.text);
6970                let incomplete_reason = match &parsed {
6971                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
6972                        "the reply parsed, but it reported a command whose own CLI \
6973                         never confirmed an exit status"
6974                            .to_owned(),
6975                    ),
6976                    Ok(_) => None,
6977                    Err(e) => Some(e.to_string()),
6978                };
6979                match incomplete_reason {
6980                    None => {
6981                        let report = parsed.expect("checked Ok above");
6982                        fix.addressed = report.addressed;
6983                        fix.rejected = report.rejected;
6984                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
6985                    }
6986                    Some(reason) => {
6987                        let (resumed_seat, resolved, failure, cont) = self
6988                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, 0)
6989                            .await;
6990                        fix.duration_ms += cont.cumulative_wait_ms;
6991                        fix.continuation = Some(cont);
6992                        final_seat = resumed_seat;
6993                        match resolved {
6994                            Some(report) => {
6995                                fix.addressed = report.addressed;
6996                                fix.rejected = report.rejected;
6997                                fix.notes =
6998                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
6999                            }
7000                            None => fix.failed = failure,
7001                        }
7002                    }
7003                }
7004            }
7005            AgentOutcome::Dropped(o) => {
7006                fix.duration_ms = o.duration_ms;
7007                let why = o
7008                    .dropped
7009                    .as_ref()
7010                    .map(|d| d.why.as_str())
7011                    .unwrap_or("the CLI ended the stream without delivering its answer");
7012                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
7013            }
7014            AgentOutcome::Quota(o) => {
7015                self.state.quota.push(QuotaLoss::from_report(
7016                    final_seat.key.clone(),
7017                    "fix",
7018                    o.quota.as_ref(),
7019                ));
7020                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
7021            }
7022            AgentOutcome::Failed(e) => fix.failed = Some(e),
7023            AgentOutcome::ResourceBlocked(e) => {
7024                fix.failed = Some(format!("the fixer was not started: {e}"));
7025            }
7026        }
7027        // Even a deferred call must rescue edits, release the worktree and
7028        // finalize its record below so an explicit `magi fix` can retry.
7029        if fix.continuation.is_none() {
7030            fix.continuation = Some(ContinuationRecord::not_needed());
7031        }
7032        self.state.seats.insert(final_seat.key.clone(), final_seat);
7033
7034        let rescue_message = format!(
7035            "magi: operator-selected fix ({}) (uncommitted work)",
7036            self.state.operator_fixes[request_index]
7037                .findings
7038                .iter()
7039                .map(|f| f.id.as_str())
7040                .collect::<Vec<_>>()
7041                .join(", ")
7042        );
7043        let repo = self.state.repo.clone();
7044        let coordination = self.coordinate(&repo).await?;
7045        if let Ok(r) = git::rescue_commit(&fix_worktree, &rescue_message).await {
7046            self.state.note_withheld("fix", &r.withheld);
7047        }
7048        let after = git::rev_parse(&fix_worktree, "HEAD").await?;
7049        fix.committed = after != head_at_request;
7050        git::worktree_remove(&self.state.repo, &fix_worktree)
7051            .await
7052            .ok();
7053        drop(coordination);
7054
7055        self.state.event(
7056            "fix",
7057            match &fix.failed {
7058                Some(reason) => format!(
7059                    "operator fix: adoption report was lost ({reason}); {}",
7060                    if fix.committed {
7061                        "committed"
7062                    } else {
7063                        "NO new commit"
7064                    }
7065                ),
7066                None => format!(
7067                    "operator fix: {} addressed, {} rejected, {}",
7068                    fix.addressed.len(),
7069                    fix.rejected.len(),
7070                    if fix.committed {
7071                        "committed"
7072                    } else {
7073                        "NO new commit"
7074                    }
7075                ),
7076            },
7077        );
7078
7079        // Every selected finding gets an outcome — never left `Pending` once
7080        // the fixer's own turn is over. A report that never came back at all
7081        // marks every one of them `Unreported`, not silently "not addressed":
7082        // quota, a dropped stream, or an exhausted continuation are gaps in
7083        // the report, not evidence about the finding itself (see [`SCHEMA`]'s
7084        // doc for schema 9 and [`OperatorFixOutcome::Unreported`]).
7085        for f in &mut self.state.operator_fixes[request_index].findings {
7086            f.outcome = if fix.failed.is_some() {
7087                OperatorFixOutcome::Unreported
7088            } else if fix.addressed.contains(&f.id) {
7089                OperatorFixOutcome::Addressed
7090            } else if let Some(r) = fix.rejected.iter().find(|r| r.id == f.id) {
7091                OperatorFixOutcome::Rejected { why: r.why.clone() }
7092            } else {
7093                OperatorFixOutcome::Unreported
7094            };
7095        }
7096
7097        let committed = fix.committed;
7098        if committed {
7099            self.state.operator_fixes[request_index].result_head = Some(after.clone());
7100        }
7101        self.state.operator_fixes[request_index].fix = Some(fix);
7102        // Saved again now that the fixer's own outcome is final, on top of
7103        // the save right after the request was first pushed above.
7104        self.state.save()?;
7105        if self.state.resource_block.is_some() {
7106            return self.stop_for_resource();
7107        }
7108
7109        if committed {
7110            self.state.event(
7111                "fix",
7112                format!(
7113                    "operator fix committed {}; opening a follow-up review-only run",
7114                    short(&after)
7115                ),
7116            );
7117            self.state.save()?;
7118            drop(execution);
7119            // The new review owns its own execution. Update only its audit link
7120            // afterwards, since publication may have changed the old record.
7121            let event_count = self.state.events.len();
7122            let save_follow_up = |state: &mut RunState| -> Result<()> {
7123                let _owner = crate::pr_head::owner_lock(&home, &state.id)?;
7124                let _execution = crate::driver::maintenance(&home, &state.id)?;
7125                let mut disk = RunState::load(&state.id)?;
7126                disk.events.extend(state.events.drain(event_count..));
7127                let follow_up = state.operator_fixes[request_index]
7128                    .follow_up_review_run
7129                    .clone();
7130                disk.operator_fixes[request_index].follow_up_review_run = follow_up;
7131                disk.save()?;
7132                *state = disk;
7133                Ok(())
7134            };
7135            // The operator asked for the fix, and the follow-up serves whatever
7136            // task the run it follows served.
7137            let origin =
7138                Origin::operator().serving(self.state.origin.as_ref().and_then(|o| o.task.clone()));
7139            match Self::review(
7140                &self.state.repo,
7141                &winner.branch,
7142                self.state.config.clone(),
7143                origin,
7144            )
7145            .await
7146            {
7147                Ok(mut follow_up) => {
7148                    follow_up.state.event(
7149                        "start",
7150                        format!(
7151                            "requested by an operator fix on run {} for finding(s) {}",
7152                            self.state.id,
7153                            self.state.operator_fixes[request_index]
7154                                .findings
7155                                .iter()
7156                                .map(|f| f.id.as_str())
7157                                .collect::<Vec<_>>()
7158                                .join(", "),
7159                        ),
7160                    );
7161                    follow_up.state.save()?;
7162                    let follow_up_id = follow_up.state.id.clone();
7163                    // The follow-up is a run like any other: it belongs to the
7164                    // task of the run it follows, or to one filed for it.
7165                    let adopted = match crate::direct::adopt(
7166                        &follow_up.state,
7167                        self.state.origin.as_ref().and_then(|o| o.task.as_deref()),
7168                    ) {
7169                        Ok(a) => a,
7170                        Err(e) => {
7171                            // An ownerless run must not spend agent calls; it
7172                            // stays saved, and `magi run --resume` adopts it.
7173                            self.state.event(
7174                                "fix",
7175                                format!(
7176                                    "follow-up review {follow_up_id} got no owning task and was not executed: {e:#}"
7177                                ),
7178                            );
7179                            save_follow_up(&mut self.state)?;
7180                            return Ok(());
7181                        }
7182                    };
7183                    let executed = follow_up.execute().await;
7184                    let failure = executed.as_ref().err().map(|e| format!("{e:#}"));
7185                    if let Some(a) = adopted {
7186                        a.finish(&follow_up.state, executed);
7187                    }
7188                    if let Some(e) = failure {
7189                        self.state.event(
7190                            "fix",
7191                            format!(
7192                                "follow-up review {follow_up_id} did not complete cleanly: {e:#}"
7193                            ),
7194                        );
7195                    }
7196                    self.state.operator_fixes[request_index].follow_up_review_run =
7197                        Some(follow_up_id);
7198                }
7199                Err(e) => {
7200                    self.state.event(
7201                        "fix",
7202                        format!("committed the fix but could not open a follow-up review: {e:#}"),
7203                    );
7204                }
7205            }
7206            save_follow_up(&mut self.state)?;
7207        }
7208
7209        Ok(())
7210    }
7211
7212    // --------------------------------------------------------------- review
7213
7214    /// Ask the fixer chain once for one fix call: the agents [`fixer::attempts`]
7215    /// names, in order, each at most once, moving on only when the call
7216    /// advances (an error, a quota hit or nothing usable - the same decision
7217    /// point `agent::chain_advances` is for the other chained roles).
7218    ///
7219    /// Each agent gets its own seat from `Runner::seat`: the same agent
7220    /// continues its conversation (the winner's own implementer seat when it
7221    /// is the winner's author, now that the competition is over), another
7222    /// takes a fresh one so the full prompt is sent again. A handover is
7223    /// recorded under `node`, which is what makes the fallback stick for the
7224    /// rest of the run (see `crate::fixer`). Only the last attempt's outcome
7225    /// is returned, so an exhausted chain reads exactly like a single failed
7226    /// fixer: one quota loss, the same wording, the same refund. An earlier
7227    /// attempt's edits are left in the tree and judged, with the final
7228    /// attempt's, by what git says afterwards.
7229    ///
7230    /// Returns the job that produced the outcome, for `continue_fix_report`.
7231    async fn ask_fixer(
7232        &mut self,
7233        winner: &Candidate,
7234        node: &'static str,
7235        round: Option<usize>,
7236        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
7237    ) -> (SeatJob, SeatState, AgentOutcome) {
7238        let attempts = fixer::attempts(&self.state, &self.roles, winner);
7239        self.ask_fixer_among(attempts, node, round, None, build)
7240            .await
7241    }
7242
7243    /// [`Self::ask_fixer`] over an explicit attempt list. `restore` is a
7244    /// worktree and a commit: before the next agent is asked after one that
7245    /// did not satisfy the call, the worktree is put back on that commit, so
7246    /// a failed agent's partial edits are not carried into the next one.
7247    async fn ask_fixer_among(
7248        &mut self,
7249        attempts: Vec<(AgentSpec, String)>,
7250        node: &'static str,
7251        round: Option<usize>,
7252        restore: Option<(&Path, &str)>,
7253        build: impl Fn(AgentSpec, SeatState) -> SeatJob,
7254    ) -> (SeatJob, SeatState, AgentOutcome) {
7255        let run_id = self.state.id.clone();
7256        let prompts = self.state.config.prompts.clone();
7257        let cache = self.state.config.cache_dir();
7258        let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
7259        let mut last = None;
7260        for (i, (spec, key)) in attempts.into_iter().enumerate() {
7261            let seat = self.seat(&key, &spec.id);
7262            let mut job = build(spec.clone(), seat);
7263            if i > 0 {
7264                job.stem = format!("{}-{}", job.stem, spec.id);
7265            }
7266            let ctx = WaveCtx {
7267                carry_seats: false,
7268                pauses: Some((&self.pause, &self.interrupt)),
7269                run: &run_id,
7270                node,
7271                prompts: &prompts,
7272                cache: cache.as_deref(),
7273                round,
7274            };
7275            let (seat, out) =
7276                run_one(job.clone(), Arc::clone(&self.sem), &ctx, &mut self.state, 0).await;
7277            // A resource block never advances the chain: the chosen agent
7278            // was not asked, so it must be the one asked again on resume.
7279            let advances = match &out {
7280                AgentOutcome::Ok(o) => agent::output_advances(o),
7281                AgentOutcome::ResourceBlocked(_) => false,
7282                _ => true,
7283            };
7284            if let Some(next) = ids.get(i + 1)
7285                && advances
7286            {
7287                self.state.seats.insert(seat.key.clone(), seat.clone());
7288                let class =
7289                    FailClass::of(&out).unwrap_or_else(|| FailClass::Other("unusable".to_owned()));
7290                let reason = match &out {
7291                    AgentOutcome::Ok(_) => "nothing usable".to_owned(),
7292                    other => fail_reason(other),
7293                };
7294                // A failed agent's edits must not reach the next one, and a
7295                // restore that did not work ends the chain: the call fails
7296                // and the caller's own (confirmed) restore decides.
7297                if let Some((wt, rev)) = restore
7298                    && let Err(e) = self.graft_restore(wt, rev).await
7299                {
7300                    let why =
7301                        format!("could not restore the worktree before the next fixer: {e:#}");
7302                    tracing::warn!("{why}");
7303                    let out = if e.is::<crate::repo_lock::ResourceBlocked>() {
7304                        AgentOutcome::ResourceBlocked(why)
7305                    } else {
7306                        AgentOutcome::Failed(why)
7307                    };
7308                    last = Some((job, seat, out));
7309                    break;
7310                }
7311                record_handover(
7312                    &mut self.state,
7313                    node,
7314                    &seat.key,
7315                    &spec.id,
7316                    next,
7317                    &class,
7318                    &reason,
7319                );
7320                continue;
7321            }
7322            last = Some((job, seat, out));
7323            break;
7324        }
7325        let (job, seat, out) = last.expect("the fixer chain always has an entry");
7326        if let AgentOutcome::Quota(output) = &out
7327            && node != "graft"
7328        {
7329            // Graft is best effort: its caller records the loss and restores
7330            // the pre-graft tree, then proceeds to review and gate.
7331            // Every fallback was tried. Machine outages cannot be repaired by
7332            // spending a fix round; use each caller's resumable resource path.
7333            let loss = QuotaLoss::from_report(seat.key.clone(), node, output.quota.as_ref());
7334            block_machine_outage(&mut self.state, node, std::slice::from_ref(&loss));
7335            self.state.quota.push(loss);
7336            self.state.seats.insert(seat.key.clone(), seat.clone());
7337            self.state.status = RunStatus::Blocked;
7338            return (
7339                job,
7340                seat,
7341                AgentOutcome::ResourceBlocked(
7342                    "fixer unavailable; restore agent availability and resume".into(),
7343                ),
7344            );
7345        }
7346        (job, seat, out)
7347    }
7348
7349    /// The one repair a verification-only failure earns (see
7350    /// [`crate::recovery`]), before the first review round of a run that took
7351    /// a branch over.
7352    ///
7353    /// Saved as started *before* the fixer is called, so a resume never
7354    /// repairs twice; a start found on re-entry is rolled back to the commit
7355    /// it began from. A failed or unusable fixer leaves the tree as it was and
7356    /// the review goes on over it, so the first round's own verification
7357    /// reports the failure again. The failure is never carried into a round as
7358    /// a result: verification is re-run on whatever commit this leaves.
7359    async fn recovery_repair(&mut self, winner: &Candidate) -> Result<()> {
7360        use crate::recovery::{Mode, Repair};
7361        if !self.state.reviews.is_empty() {
7362            return Ok(());
7363        }
7364        let Some(mut rec) = self.state.recovery.clone() else {
7365            return Ok(());
7366        };
7367        if rec.mode != Mode::VerifyRepair {
7368            return Ok(());
7369        }
7370        let wt = winner.worktree.clone();
7371        let mut head = git::rev_parse(&wt, "HEAD").await?;
7372        match rec.repair.clone() {
7373            Repair::Done { .. } => return Ok(()),
7374            Repair::WaitingForRestore { before } => {
7375                self.graft_restore(&wt, &before).await?;
7376                head = before;
7377                rec.repair = Repair::NotStarted;
7378                self.state.recovery = Some(rec.clone());
7379                self.state.save()?;
7380            }
7381            Repair::Started { before } => {
7382                // Interrupted: the unfinished edits are not trusted.
7383                // An unconfirmed rollback blocks the run with `Started` kept,
7384                // so a resume retries it; the tree is never reviewed as is.
7385                if let Err(e) = self.graft_restore(&wt, &before).await {
7386                    if e.is::<crate::repo_lock::ResourceBlocked>() {
7387                        return Err(e);
7388                    }
7389                    return self
7390                        .stop_recovery(rec, &before, format!("interrupted; rollback failed: {e:#}"))
7391                        .await;
7392                }
7393                rec.repair = Repair::Done {
7394                    before: before.clone(),
7395                    after: before,
7396                    committed: false,
7397                    failed: Some("interrupted; rolled back".to_owned()),
7398                };
7399                self.state
7400                    .event("recovery", "the repair was interrupted and rolled back");
7401                self.state.recovery = Some(rec);
7402                self.state.save()?;
7403                return Ok(());
7404            }
7405            Repair::NotStarted => {}
7406        }
7407        if crate::recovery::recheck(&mut rec, &head) {
7408            self.state.event("recovery", rec.summary());
7409            self.state.recovery = Some(rec);
7410            self.state.save()?;
7411            return Ok(());
7412        }
7413        rec.repair = Repair::Started {
7414            before: head.clone(),
7415        };
7416        self.state.recovery = Some(rec.clone());
7417        self.state.save()?;
7418
7419        let language = self.state.config.graph.language.clone();
7420        let sessions = self.state.config.graph.sessions;
7421        let artifacts = agent::artifacts_dir(&self.state.dir());
7422        let fix_prompt = prompt::recovery_fix(
7423            &self.state.instruction,
7424            &rec,
7425            self.state.config.graph.review_rounds,
7426            &language,
7427        );
7428        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
7429        self.state.event(
7430            "recovery",
7431            format!(
7432                "repair: the fixer starts from the failed verification on {}",
7433                short(&head)
7434            ),
7435        );
7436        let (_job, seat, out) = self
7437            .ask_fixer(winner, "fix", None, |spec, seat| SeatJob {
7438                prompt: fix_prompt.clone(),
7439                spec,
7440                seat,
7441                cwd: wt.clone(),
7442                timeout,
7443                allow_write: true,
7444                sessions,
7445                artifacts: artifacts.clone(),
7446                stem: "fix-recovery".to_owned(),
7447                handover: None,
7448            })
7449            .await;
7450        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
7451            rec.repair = Repair::WaitingForRestore { before: head };
7452            self.state.recovery = Some(rec);
7453            return self.stop_for_resource();
7454        }
7455        let failed = match &out {
7456            AgentOutcome::Ok(_) | AgentOutcome::ResourceBlocked(_) => None,
7457            AgentOutcome::Quota(o) => {
7458                self.state.quota.push(QuotaLoss::from_report(
7459                    seat.key.clone(),
7460                    "fix",
7461                    o.quota.as_ref(),
7462                ));
7463                Some("rate limited (quota); the fixer could not run".to_owned())
7464            }
7465            AgentOutcome::Dropped(_) => Some("the CLI dropped the stream".to_owned()),
7466            AgentOutcome::Failed(e) => Some(e.clone()),
7467        };
7468        self.state.seats.insert(seat.key.clone(), seat);
7469        let coordination = self.coordinate(&wt).await?;
7470        let failed = match failed {
7471            // The agent's partial edits are not kept.
7472            Some(why) => {
7473                if let Err(e) = git::restore_to(&wt, &head).await {
7474                    return self
7475                        .stop_recovery(rec, &head, format!("{why}; restore failed: {e:#}"))
7476                        .await;
7477                }
7478                Some(why)
7479            }
7480            None => {
7481                if let Ok(r) = git::rescue_commit(
7482                    &wt,
7483                    "magi: recovery repair of the failed verification (uncommitted work)",
7484                )
7485                .await
7486                {
7487                    self.state.note_withheld("fix", &r.withheld);
7488                }
7489                None
7490            }
7491        };
7492        let after = git::rev_parse(&wt, "HEAD").await?;
7493        drop(coordination);
7494        self.state.event(
7495            "recovery",
7496            match &failed {
7497                Some(why) => format!("repair: nothing kept ({why})"),
7498                None if after != head => {
7499                    format!("repair: committed {}", short(&after))
7500                }
7501                None => "repair: the fixer made no commit".to_owned(),
7502            },
7503        );
7504        rec.repair = Repair::Done {
7505            before: head.clone(),
7506            committed: after != head,
7507            after,
7508            failed,
7509        };
7510        self.state.recovery = Some(rec);
7511        self.state.save()?;
7512        Ok(())
7513    }
7514
7515    /// A repair whose rollback could not be confirmed: the run is blocked and
7516    /// resumable, and the unconfirmed state is never reviewed.
7517    async fn stop_recovery(
7518        &mut self,
7519        mut rec: crate::recovery::RecoveryRecord,
7520        head: &str,
7521        why: String,
7522    ) -> Result<()> {
7523        // `Started` stays recorded: a resume retries the restore.
7524        rec.repair = crate::recovery::Repair::Started {
7525            before: head.to_owned(),
7526        };
7527        self.state.recovery = Some(rec);
7528        self.state
7529            .event("recovery", format!("repair could not be undone: {why}"));
7530        self.state.status = RunStatus::Blocked;
7531        self.state.save()?;
7532        bail!("recovery repair could not be rolled back: {why}")
7533    }
7534
7535    async fn review_loop(&mut self) -> Result<()> {
7536        if self.hold_base_sync().await? {
7537            return Ok(());
7538        }
7539        loop {
7540            if self
7541                .state
7542                .base_sync
7543                .as_ref()
7544                .is_some_and(|s| s.conflict.is_some())
7545            {
7546                return Ok(());
7547            }
7548            if self.catchup_repairable() {
7549                let record = self.state.reviews.last().expect("repairable round").clone();
7550                let winner = self
7551                    .state
7552                    .winner()
7553                    .cloned()
7554                    .context("catch-up repair has no winner")?;
7555                if !self.fix_review_round(&winner, record).await? {
7556                    return Ok(());
7557                }
7558            }
7559            self.review_loop_pass().await?;
7560            if !self.catchup_repairable() {
7561                return Ok(());
7562            }
7563        }
7564    }
7565
7566    /// Derive an owed catch-up repair from durable round evidence, including
7567    /// reentry after a crash before the fixer was dispatched.
7568    fn catchup_repairable(&self) -> bool {
7569        self.state.reviews.len() < self.state.config.graph.review_rounds
7570            && self.state.reviews.last().is_some_and(|r| {
7571                !r.clean
7572                    && r.blocking == 0
7573                    && r.fix.is_none()
7574                    && r.e2e_status() == E2eStatus::Failed
7575            })
7576    }
7577
7578    async fn review_loop_pass(&mut self) -> Result<()> {
7579        // A base that would not rebase is a person's decision, not a review
7580        // round: nothing here would change the answer, and reviewers and a
7581        // fixer would be spending real budget on a tree that cannot land
7582        // regardless of what they find.
7583        if self
7584            .state
7585            .base_sync
7586            .as_ref()
7587            .is_some_and(|s| s.conflict.is_some())
7588        {
7589            return Ok(());
7590        }
7591        // Attribution for every agent this node spawns: `MAGI_RUN` lets a task the
7592        // agent files with `magi task add` name the run that paid for it. The
7593        // prompt overlay is cloned alongside it because the waves borrow it
7594        // while `self` is mutably borrowed by the node's own bookkeeping.
7595        let run_id = self.state.id.clone();
7596        let prompts = self.state.config.prompts.clone();
7597        let Some(winner) = self.state.winner().cloned() else {
7598            return Ok(());
7599        };
7600        let granted_review = self
7601            .state
7602            .repair_grants
7603            .last()
7604            .filter(|g| g.phase == crate::repair_budget::Phase::Reviewing)
7605            .cloned();
7606        let fresh_review = granted_review
7607            .as_ref()
7608            .is_some_and(|g| self.state.reviews.len() == g.review_start);
7609        let max_rounds = granted_review
7610            .as_ref()
7611            .map_or(self.state.config.graph.review_rounds, |g| {
7612                g.review_start.saturating_add(1)
7613            });
7614        // A clean round, an exhausted round budget, or a stalled tree (see
7615        // `STAGNANT_LIMIT`) are all already-decided conclusions the moment
7616        // they are recorded — recomputed here, not read off `status`, so a
7617        // reentry into a run that already stopped restates the identical
7618        // verdict instead of silently handing back whatever an earlier node
7619        // in this same walk clobbered `status` to (a solo-candidate
7620        // `judge`/`deliberate` skip rewrites it on every reentry). The loop
7621        // below runs an empty range once the budget is spent, and would
7622        // otherwise fall through without touching `status` at all.
7623        if let Some(status) =
7624            review_conclusion(&self.state.reviews, max_rounds).filter(|_| !fresh_review)
7625        {
7626            // A reentry after a crash between the last round's save and
7627            // `stop_reviewing` reaches the hand-off here, not there.
7628            if status == RunStatus::Gating {
7629                self.record_contested_handoff();
7630            }
7631            self.state.status = status;
7632            self.state.save()?;
7633            return Ok(());
7634        }
7635        self.state.status = RunStatus::Reviewing;
7636        // A last recorded round whose own verification never resolved
7637        // (`ResourceBlocked` — the shared build cache, not the patch) is
7638        // never a concluded round, whatever the round budget says: starting
7639        // a fresh round on top of it would spend a whole new reviewer wave
7640        // re-reading an unchanged patch instead of just retrying the one
7641        // check that actually needs it, and once the budget is spent the
7642        // loop below has nothing left to do at all (its range is empty).
7643        // Retry that check directly instead, exactly the same retry
7644        // `stop_reviewing` already does for its own catch-up case.
7645        if !fresh_review
7646            && self.state.reviews.last().is_some_and(|r| {
7647                r.e2e_status() == E2eStatus::ResourceBlocked
7648                    || (r.e2e_status() == E2eStatus::Deferred && r.blocking == 0 && r.fix.is_none())
7649            })
7650        {
7651            let shell = self.state.config.shell();
7652            return self
7653                .stop_unresolved_review(
7654                    "the last round's own verification never resolved",
7655                    &shell,
7656                    &winner.worktree,
7657                )
7658                .await;
7659        }
7660
7661        if granted_review.is_none() {
7662            self.recovery_repair(&winner).await?;
7663        }
7664        if self.resource_halt()? {
7665            return Ok(());
7666        }
7667
7668        let repo = self.state.repo.clone();
7669        let root = self.state.worktree_root();
7670        let language = self.state.config.graph.language.clone();
7671        let sessions = self.state.config.graph.sessions;
7672        let artifacts = self.merge_repair_artifacts();
7673        let base = self.landing_base();
7674        let base_short = short(&base);
7675        let reviewers = self.roles.reviewers.clone();
7676        let shell = self.state.config.shell();
7677
7678        for round in (self.state.reviews.len() + 1)..=max_rounds {
7679            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
7680            let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
7681            let stat = git::diff_stat(&winner.worktree, &base, "HEAD").await?;
7682            // The prior round's own record, already persisted — never a
7683            // hand-carried variable of just its failing output: that is
7684            // exactly what let a round's e2e result drift out of sync with
7685            // which commit it was actually about (see `SCHEMA`'s doc for
7686            // schema 8). Judged against `head`, the commit reviewers are
7687            // about to look at now, so the summary always reads as "an
7688            // earlier head" here — this round's own patch has not been
7689            // checked yet.
7690            let prev_verification = self
7691                .state
7692                .reviews
7693                .last()
7694                .and_then(|r| r.verification_summary(&head));
7695            // Only the first round of a run that took a branch over: later
7696            // rounds have this run's own history.
7697            let prior_section = match (&self.state.recovery, round) {
7698                (Some(rec), 1) if self.state.reviews.is_empty() => {
7699                    let since = match (rec.mode, rec.reviewed_head.as_deref()) {
7700                        (crate::recovery::Mode::VerifyRepair, Some(reviewed)) => {
7701                            Some(crate::recovery::head_of(
7702                                &git::diff(&winner.worktree, reviewed, "HEAD")
7703                                    .await
7704                                    .unwrap_or_default(),
7705                                crate::recovery::SINCE_DIFF_MAX,
7706                            ))
7707                        }
7708                        _ => None,
7709                    };
7710                    Some(prompt::recovery_review(rec, since.as_deref()))
7711                }
7712                _ => None,
7713            };
7714
7715            // Each reviewer gets its own detached checkout of exactly this
7716            // commit: nobody can perturb the winner's tree, and the fixer can
7717            // keep working without racing a reviewer.
7718            let mut jobs = Vec::new();
7719            let coordination = if self.state.config.worktree.pre_clean.is_empty() {
7720                self.coordinate(&repo).await?
7721            } else {
7722                None
7723            };
7724            for (r, spec) in reviewers.iter().cloned().enumerate() {
7725                let wt = root.join(format!("review-{}", r + 1));
7726                // `clean -fdx` in a reset wipes setup's products, so every
7727                // round sets the seat up again.
7728                if wt.exists() {
7729                    crate::worktree_clean::reset(&mut self.state, &wt, Some(&head)).await?;
7730                } else {
7731                    let _lease = if self.state.config.worktree.pre_clean.is_empty() {
7732                        None
7733                    } else {
7734                        self.coordinate(&repo).await?
7735                    };
7736                    git::worktree_add_detached(&repo, &wt, &head).await?;
7737                }
7738                let _setup_lease = if self.state.config.worktree.pre_clean.is_empty() {
7739                    None
7740                } else {
7741                    self.coordinate(&repo).await?
7742                };
7743                self.setup_seat_worktree(
7744                    &repo,
7745                    &wt,
7746                    false,
7747                    coordination.as_ref().or(_setup_lease.as_ref()),
7748                )
7749                .await?;
7750                let seat_key = format!("review-{}", r + 1);
7751                // The seat starts the round on whoever answered it last, not
7752                // on the agent the spec names, so a failure is not re-paid.
7753                let spec = pick_start_spec(
7754                    &self.roles.reviewer_roster,
7755                    spec,
7756                    self.state.seat_history.get(&seat_key),
7757                );
7758                let seat = self.seat(&seat_key, &spec.id);
7759                jobs.push(SeatJob {
7760                    prompt: prompt::review(&prompt::ReviewCtx {
7761                        instruction: &self.state.instruction,
7762                        branch: &winner.branch,
7763                        base_short: &base_short,
7764                        stat: &stat,
7765                        patch: &patch,
7766                        verification: prev_verification.as_ref(),
7767                        prior: prior_section.as_deref(),
7768                        reviewers: reviewers.len(),
7769                        round,
7770                        rounds: max_rounds,
7771                        // A review-only run has no rankings, so nothing
7772                        // competed for this patch and the reviewer is told so.
7773                        competed: self.state.tally.as_ref().is_some_and(|t| t.rankings > 0),
7774                        lens: Lens::for_seat(r),
7775                        language: &language,
7776                        github_language: &self.state.config.graph.github_language,
7777                    }),
7778                    spec,
7779                    seat,
7780                    cwd: wt,
7781                    timeout: Duration::from_secs(self.state.config.graph.timeout_review),
7782                    allow_write: false,
7783                    sessions,
7784                    artifacts: artifacts.clone(),
7785                    stem: format!("review-{round}-{}", r + 1),
7786                    handover: None,
7787                });
7788            }
7789
7790            drop(coordination);
7791            self.state.event(
7792                "review",
7793                format!(
7794                    "round {round}: {} reviewers on {}",
7795                    jobs.len(),
7796                    short(&head)
7797                ),
7798            );
7799            let mut quota_losses = Vec::new();
7800            let review_retries = self.state.config.graph.retries;
7801            let review_cache = self.state.config.cache_dir();
7802            let ctx = WaveCtx {
7803                carry_seats: true,
7804                pauses: Some((&self.pause, &self.interrupt)),
7805                run: &run_id,
7806                node: "review",
7807                prompts: &prompts,
7808                cache: review_cache.as_deref(),
7809                round: Some(round),
7810            };
7811            let results = ask_json_wave::<Review>(
7812                jobs,
7813                Arc::clone(&self.sem),
7814                review_retries,
7815                &self.roles.reviewer_roster,
7816                &ctx,
7817                &mut quota_losses,
7818                &mut self.state,
7819                &|_: &Review| Ok(()),
7820            )
7821            .await;
7822            if self.state.resource_block.is_some() {
7823                return self.stop_for_resource();
7824            }
7825            // Counted before the move below: how many of *this* round's
7826            // reviewer seats were lost to their own rate limit, as opposed to
7827            // a crash, a timeout, or unparsable output — see `round_is_clean`.
7828            let round_quota_missing = quota_losses.len();
7829            self.state.quota.extend(quota_losses);
7830
7831            let mut records = Vec::new();
7832            let mut all_findings = Vec::new();
7833            for (r, (seat, res, attempts)) in results.into_iter().enumerate() {
7834                let agent_id = seat.agent.clone();
7835                self.state.seats.insert(seat.key.clone(), seat);
7836                let mut record = ReviewRecord {
7837                    reviewer: r + 1,
7838                    agent: agent_id,
7839                    summary: String::new(),
7840                    findings: Vec::new(),
7841                    vote: None,
7842                    failed: None,
7843                    duration_ms: 0,
7844                    // Set for both outcomes: `failed: Some(_)` with
7845                    // `attempts > 0` is a seat every retry still lost, not a
7846                    // recovered one — only `failed: None` with `attempts > 0`
7847                    // reads as "answered after a nudge" (see this field's own
7848                    // doc).
7849                    attempts,
7850                };
7851                match res {
7852                    Ok((review, out)) => {
7853                        // Sanitized here, at the point every other piece of
7854                        // agent prose in this file is (candidate summaries,
7855                        // deliberation turns, vote reasons): a reviewer's own
7856                        // words are the one thing about it that could name
7857                        // it, and reconsideration below broadcasts this same
7858                        // summary and these same findings to every other
7859                        // seat on the panel.
7860                        record.summary =
7861                            blind::sanitize_prose(&review.summary, &self.state.config.blind);
7862                        record.vote = Some(review.vote);
7863                        record.duration_ms = out.duration_ms;
7864                        for (n, mut f) in review.findings.into_iter().enumerate() {
7865                            // ids are magi's, never the agent's: the fixer's
7866                            // adoption report is keyed by them.
7867                            f.id = format!("R{round}-{}-{}", r + 1, n + 1);
7868                            f.title = blind::sanitize_prose(&f.title, &self.state.config.blind);
7869                            f.detail = blind::sanitize_prose(&f.detail, &self.state.config.blind);
7870                            // `file` is agent-supplied prose too, never
7871                            // checked against the real tree — the same
7872                            // exposure `title`/`detail` above have, just in
7873                            // a field easy to forget because it looks like a
7874                            // path rather than free text.
7875                            f.file = f
7876                                .file
7877                                .map(|file| blind::sanitize_prose(&file, &self.state.config.blind));
7878                            all_findings.push(f.clone());
7879                            record.findings.push(f);
7880                        }
7881                        self.state.event(
7882                            "review",
7883                            format!(
7884                                "round {round}: reviewer {} voted {} with {} finding(s)",
7885                                r + 1,
7886                                review.vote.label(),
7887                                record.findings.len()
7888                            ),
7889                        );
7890                    }
7891                    Err(e) => {
7892                        record.failed = Some(e.to_string());
7893                        self.state.event(
7894                            "review",
7895                            format!("round {round}: reviewer {} produced nothing: {e}", r + 1),
7896                        );
7897                    }
7898                }
7899                records.push(record);
7900            }
7901
7902            // Tally the round's votes and, if they split, spend the one
7903            // round of reconsideration the split -> deliberate -> revote
7904            // shape `judge`/`vote` use for the panel, sized down to what a
7905            // read-only review round can afford: one round, and a revote
7906            // rather than an argument, because the panel already wrote its
7907            // reasoning down as findings the first time around.
7908            let initial_votes: Vec<ReviewVote> = records.iter().filter_map(|r| r.vote).collect();
7909            let vote_split =
7910                initial_votes.len() > 1 && !initial_votes.iter().all(|v| *v == initial_votes[0]);
7911            let mut reconsideration: Vec<ReviewRevoteRecord> = Vec::new();
7912            if vote_split {
7913                self.state.event(
7914                    "review",
7915                    format!(
7916                        "round {round}: votes split ({}) — one round of reconsideration",
7917                        initial_votes
7918                            .iter()
7919                            .map(|v| v.label())
7920                            .collect::<Vec<_>>()
7921                            .join(", ")
7922                    ),
7923                );
7924                // Seats read every seat's findings and votes, still numbered
7925                // and never named — the same anonymity `review` itself keeps.
7926                let panel: Vec<ReviewSeatReport<'_>> = records
7927                    .iter()
7928                    .filter_map(|r| {
7929                        r.vote.map(|vote| ReviewSeatReport {
7930                            reviewer: r.reviewer,
7931                            vote,
7932                            summary: &r.summary,
7933                            findings: &r.findings,
7934                        })
7935                    })
7936                    .collect();
7937
7938                let mut jobs = Vec::new();
7939                let mut seats_at = Vec::new();
7940                for (r, spec) in reviewers.iter().cloned().enumerate() {
7941                    // A seat with no initial vote has nothing to reconsider
7942                    // from and stays absent, the same as it stayed absent
7943                    // from `panel` above.
7944                    if records[r].vote.is_none() {
7945                        continue;
7946                    }
7947                    let wt = root.join(format!("review-{}", r + 1));
7948                    let seat_key = format!("review-{}", r + 1);
7949                    let spec = self.occupant(&seat_key, spec);
7950                    let seat = self.seat(&seat_key, &spec.id);
7951                    // A seat with no live session has already forgotten the
7952                    // initial review's prompt — restate the patch it is
7953                    // voting on, the same as `deliberate`/`vote` do for a
7954                    // judge in the same position.
7955                    // The panel already carries this seat's own review and
7956                    // vote, so restating the patch makes the prompt whole for
7957                    // a seat handed to another agent.
7958                    let build = |with_patch: bool| {
7959                        prompt::review_reconsider(&ReviewReconsiderCtx {
7960                            instruction: &self.state.instruction,
7961                            reviewer: r + 1,
7962                            lens: Lens::for_seat(r),
7963                            panel: &panel,
7964                            patch: with_patch.then_some(ReviewPatch {
7965                                branch: &winner.branch,
7966                                base_short: &base_short,
7967                                stat: &stat,
7968                                patch: &patch,
7969                            }),
7970                            round,
7971                            rounds: max_rounds,
7972                            language: &language,
7973                        })
7974                    };
7975                    let full = build(true);
7976                    let prompt = if has_context(&spec, &seat, sessions) {
7977                        build(false)
7978                    } else {
7979                        full.clone()
7980                    };
7981                    jobs.push(SeatJob {
7982                        prompt,
7983                        spec,
7984                        seat,
7985                        cwd: wt,
7986                        timeout: Duration::from_secs(self.state.config.graph.timeout_review),
7987                        allow_write: false,
7988                        sessions,
7989                        artifacts: artifacts.clone(),
7990                        stem: format!("review-{round}-reconsider-{}", r + 1),
7991                        handover: Some(full),
7992                    });
7993                    seats_at.push(r);
7994                }
7995
7996                let mut recon_quota_losses = Vec::new();
7997                let recon_cache = self.state.config.cache_dir();
7998                let recon_ctx = WaveCtx {
7999                    carry_seats: true,
8000                    pauses: Some((&self.pause, &self.interrupt)),
8001                    run: &run_id,
8002                    node: "review",
8003                    prompts: &prompts,
8004                    cache: recon_cache.as_deref(),
8005                    round: Some(round),
8006                };
8007                let recon_results = ask_json_wave::<ReviewRevote>(
8008                    jobs,
8009                    Arc::clone(&self.sem),
8010                    review_retries,
8011                    &self.roles.reviewer_roster,
8012                    &recon_ctx,
8013                    &mut recon_quota_losses,
8014                    &mut self.state,
8015                    &|_: &ReviewRevote| Ok(()),
8016                )
8017                .await;
8018                if self.state.resource_block.is_some() {
8019                    return self.stop_for_resource();
8020                }
8021                self.state.quota.extend(recon_quota_losses);
8022
8023                for (&r, (seat, res, _attempts)) in seats_at.iter().zip(recon_results) {
8024                    let agent_id = seat.agent.clone();
8025                    self.state.seats.insert(seat.key.clone(), seat);
8026                    let mut rec = ReviewRevoteRecord {
8027                        reviewer: r + 1,
8028                        agent: agent_id,
8029                        vote: None,
8030                        reason: String::new(),
8031                        failed: None,
8032                    };
8033                    match res {
8034                        Ok((rv, _)) => {
8035                            rec.vote = Some(rv.vote);
8036                            rec.reason =
8037                                blind::sanitize_prose(&rv.reason, &self.state.config.blind);
8038                            self.state.event(
8039                                "review",
8040                                format!(
8041                                    "round {round}: reviewer {} revoted {}",
8042                                    r + 1,
8043                                    rv.vote.label()
8044                                ),
8045                            );
8046                        }
8047                        Err(e) => {
8048                            rec.failed = Some(e.to_string());
8049                            self.state.event(
8050                                "review",
8051                                format!("round {round}: reviewer {} did not revote: {e}", r + 1),
8052                            );
8053                        }
8054                    }
8055                    reconsideration.push(rec);
8056                }
8057            } else if initial_votes.len() > 1 {
8058                self.state.event(
8059                    "review",
8060                    format!(
8061                        "round {round}: votes agreed ({}) — no reconsideration",
8062                        initial_votes[0].label()
8063                    ),
8064                );
8065            }
8066
8067            let blocking = all_findings.iter().filter(|f| f.severity.blocks()).count();
8068            let verify_timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
8069            // A round that already has a blocking finding and a round left to
8070            // try is going back to the fixer no matter what `verify.e2e`
8071            // says, so running it first only spends the loop's slowest step
8072            // (minutes, for a Rust repo's full test suite) on a head about
8073            // to be rewritten. Deferred, never skipped: `verify.e2e` still
8074            // runs once a round has no blocking findings left (see
8075            // `round_is_clean`, which a deferred — empty — `e2e` can never
8076            // satisfy since `blocking` is nonzero whenever this branch is
8077            // taken), and `stop_reviewing` forces a real run before it will
8078            // ever read a deferred round as green.
8079            let defer_e2e =
8080                blocking > 0 && round < max_rounds && !self.state.config.graph.e2e_every_round;
8081            let (e2e, verify_retried, e2e_deferred, e2e_defer_reason) = if defer_e2e {
8082                let reason =
8083                    format!("{blocking} blocking finding(s) already required a fix this round");
8084                self.state.event(
8085                    "verify",
8086                    format!(
8087                        "round {round}: {reason} — e2e deferred to the fixer (reviewed head \
8088                         {}); it will run once a round has none left",
8089                        short(&head)
8090                    ),
8091                );
8092                (Vec::new(), false, true, Some(reason))
8093            } else {
8094                let e2e_commands = self.state.config.verify.e2e.clone();
8095                let cache_dir = self.state.config.cache_dir();
8096                let context = format!("round {round}");
8097                let wait = self.repository_wait();
8098                let (e2e, verify_retried) = with_cache_lease(
8099                    &mut self.state,
8100                    cache_dir.as_deref(),
8101                    "e2e",
8102                    "e2e",
8103                    &winner.worktree,
8104                    &head,
8105                    verify_timeout,
8106                    &context,
8107                    &wait,
8108                    |state, budget| {
8109                        let shell = shell.clone();
8110                        let e2e_commands = e2e_commands.clone();
8111                        let worktree = winner.worktree.clone();
8112                        let context = context.clone();
8113                        let winner = winner.clone();
8114                        async move {
8115                            if !e2e_commands.is_empty() {
8116                                // The suite certifies one SHA. Format before it
8117                                // runs, or the commit `pre_gate` makes at the
8118                                // gate owes the whole suite again.
8119                                Self::run_pre_gate(state, &winner).await;
8120                            }
8121                            run_e2e_with_retry(
8122                                state,
8123                                &shell,
8124                                &e2e_commands,
8125                                &worktree,
8126                                budget,
8127                                &context,
8128                                Some(round),
8129                            )
8130                            .await
8131                        }
8132                    },
8133                )
8134                .await?;
8135                (e2e, verify_retried, false, None)
8136            };
8137
8138            let expected = records.len();
8139            let answered = records.iter().filter(|r| r.failed.is_none()).count();
8140            let incomplete = answered < expected;
8141            let e2e_ok = e2e.iter().all(CommandOutcome::ok);
8142            let policy = self.state.config.graph.incomplete_review;
8143            let clean = round_is_clean(
8144                blocking,
8145                e2e_ok,
8146                answered,
8147                expected,
8148                round_quota_missing,
8149                policy,
8150            );
8151
8152            let mut round_record = ReviewRound {
8153                round,
8154                head: head.clone(),
8155                verified_head: None,
8156                verified_at: None,
8157                reviews: records,
8158                e2e,
8159                verify_retried,
8160                e2e_deferred,
8161                e2e_defer_reason,
8162                fix: None,
8163                blocking,
8164                answered,
8165                expected,
8166                clean,
8167                progressed: false,
8168                vote_split,
8169                reconsideration,
8170                verdict: None,
8171            };
8172            // The final vote per seat is its revote where reconsideration
8173            // ran and answered, its initial vote otherwise — the same
8174            // fallback `tally` uses for a judge whose private vote failed.
8175            round_record.verdict = ReviewVote::worst(
8176                round_record
8177                    .final_votes()
8178                    .into_iter()
8179                    .map(|(_, _, vote)| vote),
8180            );
8181            // Which commit and when magi actually attempted to check —
8182            // known the moment a command was dispatched against `head`,
8183            // whether or not it finished: a resource-blocked attempt still
8184            // targeted a specific commit at a specific time, and leaving
8185            // that unrecorded is exactly what made `verification_summary`
8186            // report a fresh attempt as "commit unknown ... recorded before
8187            // this was tracked", indistinguishable from a genuinely old,
8188            // untracked record. Only a deferred or unconfigured round never
8189            // ran at all and has nothing to record — see
8190            // `ReviewRound::verified_head`'s own doc.
8191            if !matches!(
8192                round_record.e2e_status(),
8193                E2eStatus::Deferred | E2eStatus::NotConfigured
8194            ) {
8195                // HEAD, not the reviewed `head`: `pre_gate` may have committed
8196                // mechanical fixes before the commands ran.
8197                round_record.verified_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
8198                round_record.verified_at = Some(Timestamp::now());
8199            }
8200
8201            if incomplete {
8202                let missing: Vec<String> = round_record
8203                    .reviews
8204                    .iter()
8205                    .filter(|r| r.failed.is_some())
8206                    .map(|r| format!("review-{}", r.reviewer))
8207                    .collect();
8208                self.state.event(
8209                    "review",
8210                    format!(
8211                        "round {round}: {answered}/{expected} reviewer(s) answered ({} never answered)",
8212                        missing.join(", ")
8213                    ),
8214                );
8215            }
8216
8217            if clean {
8218                self.state.event(
8219                    "review",
8220                    if incomplete && policy == IncompleteReviewPolicy::Warn {
8221                        format!(
8222                            "round {round}: clean (warn policy, incomplete panel) — no \
8223                             blocking findings from the seats that answered, verification green"
8224                        )
8225                    } else if incomplete {
8226                        format!(
8227                            "round {round}: clean ({} rate-limited reviewer(s) excluded from \
8228                             quorum) — no blocking findings from the seats that answered, \
8229                             verification green",
8230                            expected - answered
8231                        )
8232                    } else {
8233                        format!("round {round}: clean — no blocking findings, verification green")
8234                    },
8235                );
8236                self.state.reviews.push(round_record);
8237                self.state.status = RunStatus::Gating;
8238                self.state.save()?;
8239                return Ok(());
8240            }
8241
8242            // Nothing was raised and verification passed, but not every seat
8243            // answered and `round_is_clean` still refused to call it clean —
8244            // either a seat is missing for a reason other than its own quota
8245            // (a crash, a timeout, unparsable output — worth another try), or
8246            // every seat that could have answered lost its quota and nobody
8247            // is left to decide on: re-review rather than send the fixer
8248            // after a round with nothing to fix.
8249            if incomplete && blocking == 0 && e2e_ok {
8250                self.state.reviews.push(round_record);
8251                self.state.save()?;
8252                if round == max_rounds {
8253                    self.state.status = RunStatus::Blocked;
8254                    self.state.event(
8255                        "review",
8256                        format!(
8257                            "{} reviewer seat(s) never answered after {max_rounds} rounds; \
8258                             refusing to call it clean",
8259                            expected - answered
8260                        ),
8261                    );
8262                    return Ok(());
8263                }
8264                continue;
8265            }
8266
8267            // Nothing for the fixer to act on (`blocking == 0`) and the only
8268            // reason this round is not clean is that magi itself never got
8269            // a command to run — the shared build cache, not the patch (see
8270            // `CommandOutcome::resource_blocked`'s own doc). Sending that to
8271            // the fixer would invite a change to appease contention that has
8272            // nothing to do with the diff, and would leave this attempt
8273            // sitting in the next round's prompt as if it were about an
8274            // earlier, superseded commit rather than what it actually is:
8275            // the same head, still waiting to be checked. Wait for it the
8276            // same way the final round's own contention is already handled,
8277            // whatever round this happens to be.
8278            if blocking == 0 && round_record.e2e_status() == E2eStatus::ResourceBlocked {
8279                self.state.reviews.push(round_record);
8280                return self
8281                    .stop_unresolved_review(
8282                        "the round's own verification could not run",
8283                        &shell,
8284                        &winner.worktree,
8285                    )
8286                    .await;
8287            }
8288
8289            if round == max_rounds {
8290                self.state.reviews.push(round_record);
8291                return self
8292                    .stop_reviewing(
8293                        &format!(
8294                            "{blocking} blocking finding(s) still open after {max_rounds} round(s)"
8295                        ),
8296                        &shell,
8297                        &winner.worktree,
8298                    )
8299                    .await;
8300            }
8301
8302            if !self.fix_review_round(&winner, round_record).await? {
8303                return Ok(());
8304            }
8305        }
8306        Ok(())
8307    }
8308
8309    /// Run the same fix chain for an in-loop failure or a persisted catch-up failure.
8310    /// False means admission or continuation policy stopped the review loop.
8311    async fn fix_review_round(
8312        &mut self,
8313        winner: &Candidate,
8314        mut round_record: ReviewRound,
8315    ) -> Result<bool> {
8316        let round = round_record.round;
8317        let shell = self.state.config.shell();
8318        let step = self.run_fix_round(winner, &mut round_record).await?;
8319        if matches!(step, FixStep::Resource) {
8320            self.stop_for_resource()?;
8321            return Ok(false);
8322        }
8323        if self.state.reviews.len() < round {
8324            self.state.reviews.push(round_record);
8325        } else {
8326            self.state.reviews[round - 1] = round_record;
8327        }
8328        self.state.save()?;
8329
8330        // The fixer's own report never came back this round, even after
8331        // `continue_fix_report`'s own budget was spent on it — not an
8332        // ordinary "no report" (dropped stream, quota, plain failure),
8333        // which already reads that way and is left to the existing round
8334        // budget. Stopping here, rather than opening another round, is
8335        // what keeps a next reviewer/fixer wave from ever being
8336        // dispatched onto `winner.worktree` while whatever the seat's
8337        // last call may still have running there is unaccounted for: no
8338        // process liveness check exists (and none is being added — see
8339        // AGENTS.md/this task's own scope), so the only way to honour
8340        // "nothing starts before a valid report returns" is to not start
8341        // anything further on this worktree from this run at all.
8342        if matches!(step, FixStep::Recorded { report_lost: true }) {
8343            self.stop_reviewing(
8344                "the fixer's adoption report never came back, even after resuming its \
8345                         own seat; refusing to start another round against the same worktree \
8346                         while that is unresolved",
8347                &shell,
8348                &winner.worktree,
8349            )
8350            .await?;
8351            return Ok(false);
8352        }
8353
8354        let streak = self
8355            .state
8356            .reviews
8357            .iter()
8358            .rev()
8359            .take_while(|r| !r.progressed)
8360            .count();
8361        if streak >= STAGNANT_LIMIT {
8362            self.stop_reviewing(
8363                &format!("the tree has not moved against base for {streak} round(s) in a row"),
8364                &shell,
8365                &winner.worktree,
8366            )
8367            .await?;
8368            return Ok(false);
8369        }
8370        Ok(true)
8371    }
8372
8373    /// Execute the shared fixer chain; the caller owns persistence and stop policy.
8374    async fn run_fix_round(
8375        &mut self,
8376        winner: &Candidate,
8377        round_record: &mut ReviewRound,
8378    ) -> Result<FixStep> {
8379        let round = round_record.round;
8380        let max_rounds = self.state.config.graph.review_rounds;
8381        let run_id = self.state.id.clone();
8382        let prompts = self.state.config.prompts.clone();
8383        let language = self.state.config.graph.language.clone();
8384        let sessions = self.state.config.graph.sessions;
8385        let artifacts = self.merge_repair_artifacts();
8386        let base = self.landing_base();
8387        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
8388        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
8389        let this_round_verification = round_record.verification_summary(&head);
8390        let all_findings: Vec<_> = round_record
8391            .reviews
8392            .iter()
8393            .flat_map(|r| r.findings.iter().cloned())
8394            .collect();
8395        // Fix. The winner's own implementer seat continues its conversation:
8396        // the competition is over, so context is pure benefit now.
8397        let blocking_findings: Vec<_> = all_findings
8398            .iter()
8399            .filter(|f| f.severity.blocks())
8400            .cloned()
8401            .collect();
8402        let fix_prompt = prompt::fix_in(
8403            &self.state.instruction,
8404            &blocking_findings,
8405            this_round_verification.as_ref(),
8406            round,
8407            max_rounds,
8408            &language,
8409            &self.state.config.graph.github_language,
8410        );
8411        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
8412        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
8413        let (job, seat, out) = self
8414            .ask_fixer(winner, "fix", Some(round), |spec, seat| SeatJob {
8415                prompt: fix_prompt.clone(),
8416                spec,
8417                seat,
8418                cwd: winner.worktree.clone(),
8419                timeout,
8420                allow_write: true,
8421                sessions,
8422                artifacts: artifacts.clone(),
8423                stem: format!("fix-{round}"),
8424                handover: None,
8425            })
8426            .await;
8427        // Not asked: the round is not recorded (so a resume repeats it),
8428        // no fixer was handed over to, and the seat is left as it was.
8429        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
8430            return Ok(FixStep::Resource);
8431        }
8432        let agent_id = seat.agent.clone();
8433
8434        let mut fix = FixRecord {
8435            agent: agent_id,
8436            addressed: Vec::new(),
8437            rejected: Vec::new(),
8438            notes: String::new(),
8439            committed: false,
8440            failed: None,
8441            duration_ms: 0,
8442            continuation: None,
8443        };
8444        let mut continuation = ContinuationRecord::not_needed();
8445        let mut final_seat = seat.clone();
8446        match out {
8447            AgentOutcome::Ok(o) => {
8448                fix.duration_ms = o.duration_ms;
8449                let parsed = verdict::extract_json::<FixReport>(&o.text);
8450                // A parsed report standing next to a command this same
8451                // reply's own CLI never confirmed the exit status of is
8452                // not a resolved answer — the identical `CommandEvidence`
8453                // `state.jobs` renders, read here instead of only on
8454                // display, per the completion judgment and the shown
8455                // record needing to agree.
8456                let incomplete_reason = match &parsed {
8457                    Ok(_) if has_unconfirmed_command(&o.commands) => Some(
8458                        "the reply parsed, but it reported a command whose own CLI never \
8459                             confirmed an exit status"
8460                            .to_owned(),
8461                    ),
8462                    Ok(_) => None,
8463                    Err(e) => Some(e.to_string()),
8464                };
8465                match incomplete_reason {
8466                    None => {
8467                        let report = parsed.expect("checked Ok above");
8468                        fix.addressed = report.addressed;
8469                        fix.rejected = report.rejected;
8470                        fix.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
8471                    }
8472                    Some(reason) => {
8473                        let (resumed_seat, resolved, failure, cont) = self
8474                            .continue_fix_report(seat, reason, &job, &prompts, &run_id, round)
8475                            .await;
8476                        fix.duration_ms += cont.cumulative_wait_ms;
8477                        continuation = cont;
8478                        final_seat = resumed_seat;
8479                        match resolved {
8480                            Some(report) => {
8481                                fix.addressed = report.addressed;
8482                                fix.rejected = report.rejected;
8483                                fix.notes =
8484                                    blind::sanitize_prose(&report.notes, &self.state.config.blind);
8485                            }
8486                            None => fix.failed = failure,
8487                        }
8488                    }
8489                }
8490            }
8491            // The CLI's raw error JSON is not a fix report to parse.
8492            AgentOutcome::Dropped(o) => {
8493                fix.duration_ms = o.duration_ms;
8494                let why = o
8495                    .dropped
8496                    .as_ref()
8497                    .map(|d| d.why.as_str())
8498                    .unwrap_or("the CLI ended the stream without delivering its answer");
8499                fix.failed = Some(format!("the CLI dropped the stream ({why})"));
8500            }
8501            AgentOutcome::Quota(o) => {
8502                self.state.quota.push(QuotaLoss::from_report(
8503                    final_seat.key.clone(),
8504                    "fix",
8505                    o.quota.as_ref(),
8506                ));
8507                fix.failed = Some("rate limited (quota); fixer could not run".to_owned());
8508            }
8509            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => fix.failed = Some(e),
8510        }
8511        if self.state.resource_block.is_some() {
8512            self.state.seats.insert(final_seat.key.clone(), final_seat);
8513            return Ok(FixStep::Resource);
8514        }
8515        fix.continuation = Some(continuation);
8516        self.state.seats.insert(final_seat.key.clone(), final_seat);
8517        let coordination = self.coordinate(&winner.worktree).await?;
8518        if let Ok(r) = git::rescue_commit(
8519            &winner.worktree,
8520            &format!("magi: review round {round} fixes (uncommitted work)"),
8521        )
8522        .await
8523        {
8524            self.state.note_withheld("fix", &r.withheld);
8525        }
8526        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
8527        fix.committed = after != before;
8528        // Judged by what `git` says moved against base, never by the
8529        // fixer's own `addressed`/`rejected` count — see
8530        // `ReviewRound::progressed`. Propagated with `?`, the same as the
8531        // `patch` snapshot above: swallowing this error would default
8532        // `diff_after` to empty, which almost always differs from a
8533        // non-empty `patch` and reads as "progressed" — exactly backwards
8534        // for a `git` failure the stagnation check cannot see through.
8535        let diff_after = git::diff(&winner.worktree, &base, "HEAD").await?;
8536        drop(coordination);
8537        let progressed = diff_after != patch;
8538        let commit_note = if fix.committed {
8539            "committed"
8540        } else {
8541            "NO new commit"
8542        };
8543        let tree_note = if progressed {
8544            "changed vs base"
8545        } else {
8546            "unchanged vs base"
8547        };
8548        self.state.event(
8549            "fix",
8550            match &fix.failed {
8551                // Distinct on purpose from "0 addressed, 0 rejected": the
8552                // fixer's own diff still landed (blocking counts do keep
8553                // falling round over round), only its adoption report did
8554                // not come back, so this must never read like every
8555                // finding was reviewed and declined.
8556                Some(reason) => {
8557                    format!(
8558                        "round {round}: fixer's adoption report was lost ({reason}); \
8559                             {commit_note}, tree {tree_note}"
8560                    )
8561                }
8562                None => format!(
8563                    "round {round}: {} addressed, {} rejected, {commit_note}, tree \
8564                         {tree_note}{}",
8565                    fix.addressed.len(),
8566                    fix.rejected.len(),
8567                    if continuation.outcome == ContinuationOutcome::Resumed {
8568                        format!(
8569                            " (adoption report recovered after {} continuation(s))",
8570                            continuation.attempts
8571                        )
8572                    } else {
8573                        String::new()
8574                    },
8575                ),
8576            },
8577        );
8578        round_record.fix = Some(fix);
8579        round_record.progressed = progressed;
8580        Ok(FixStep::Recorded {
8581            report_lost: matches!(
8582                continuation.outcome,
8583                ContinuationOutcome::Exhausted
8584                    | ContinuationOutcome::QuotaLost
8585                    | ContinuationOutcome::NoSession
8586            ),
8587        })
8588    }
8589
8590    /// Decide, from the last recorded round's own verification, whether
8591    /// stopping the review loop is a hand-off or a genuine block.
8592    ///
8593    /// Called once the loop has given up trying — the round budget is spent,
8594    /// or the tree stopped moving (see [`STAGNANT_LIMIT`]) — with blocking
8595    /// findings still open, never while a round is still clean or the
8596    /// incomplete-panel case handled inline above. Gate and e2e are facts
8597    /// about the tree; a lingering review finding is an opinion, and this
8598    /// workload's own `magi stats` puts reviewer precision low enough
8599    /// (12-33%, 0.18-0.29 adopted per round) that a panel of open findings
8600    /// must not by itself stand between a green, verified change and the
8601    /// human who decides what to do with it. A red e2e is not an opinion, so
8602    /// that case still blocks, with the failing command and a tail of its
8603    /// output recorded here rather than left in `run.json` for someone to go
8604    /// find.
8605    ///
8606    /// A round that deferred its own e2e (see [`Config::graph`]'s
8607    /// `e2e_every_round`) is never read as that green: its `e2e` is empty
8608    /// only because nothing ran, and treating an empty list as a passing one
8609    /// here is exactly the "deferred painted green" bug this function exists
8610    /// to not have. When the last round's own verification never resolved —
8611    /// deferred on purpose, or a real attempt the shared build cache blocked
8612    /// — this makes (or retries) the real run, on the actual worktree this
8613    /// loop is about to stop touching, before deciding anything. A
8614    /// resource-blocked attempt is likewise never read as either green or
8615    /// red: it is evidence about the machine, not the patch (see
8616    /// [`CommandOutcome::resource_blocked`]'s own doc), so a persistently
8617    /// blocked cache leaves this call without deciding rather than guessing
8618    /// — the caller retries on a later reentry.
8619    /// Record, once, that the review loop handed off over a blocking finding
8620    /// a reviewer rejected on (see [`ReviewRound::contested_handoff`]), so
8621    /// `land` asks the owner even with `land_approval` off. Called from every
8622    /// path that concludes `Gating`; a reentry keeps the first record.
8623    fn record_contested_handoff(&mut self) {
8624        if self.state.contested_handoff.is_some() {
8625            return;
8626        }
8627        let Some(contested) = self
8628            .state
8629            .reviews
8630            .last()
8631            .and_then(ReviewRound::contested_handoff)
8632        else {
8633            return;
8634        };
8635        self.state.event(
8636            "review",
8637            format!(
8638                "{} blocking finding(s) open and {} reviewer(s) rejecting — the merge will \
8639                 wait for the owner's approval",
8640                contested.findings.len(),
8641                contested.rejecters.len()
8642            ),
8643        );
8644        self.state.contested_handoff = Some(contested);
8645    }
8646
8647    async fn stop_unresolved_review(
8648        &mut self,
8649        why: &str,
8650        shell: &[String],
8651        worktree: &Path,
8652    ) -> Result<()> {
8653        self.stop_reviewing_inner(why, shell, worktree, true).await
8654    }
8655
8656    async fn stop_reviewing(&mut self, why: &str, shell: &[String], worktree: &Path) -> Result<()> {
8657        self.stop_reviewing_inner(why, shell, worktree, false).await
8658    }
8659
8660    async fn stop_reviewing_inner(
8661        &mut self,
8662        why: &str,
8663        shell: &[String],
8664        worktree: &Path,
8665        repairable: bool,
8666    ) -> Result<()> {
8667        let round_idx = self.state.reviews.len() - 1;
8668        // A deferred round and a resource-blocked one are the same shape
8669        // here: neither has a real result yet, and both get one more
8670        // attempt. Read off `e2e_status` — the single source for this —
8671        // rather than `e2e.is_empty()` alone, so a resource-blocked attempt
8672        // (whose `e2e` is *not* empty; see `CommandOutcome::resource_blocked`)
8673        // still retries instead of being read as a settled result the
8674        // instant it stops being empty.
8675        let needs_catchup_run = matches!(
8676            self.state.reviews[round_idx].e2e_status(),
8677            E2eStatus::Deferred | E2eStatus::ResourceBlocked
8678        );
8679        if needs_catchup_run {
8680            let round = self.state.reviews[round_idx].round;
8681            let timeout = Duration::from_secs(self.state.config.graph.verify_timeout());
8682            let commands = self.state.config.verify.e2e.clone();
8683            let before_head = git::rev_parse(worktree, "HEAD").await?;
8684            let winner = self.state.winner().cloned();
8685            let cache_dir = self.state.config.cache_dir();
8686            let context = format!(
8687                "round {round}: verification unresolved, catching up before the final decision"
8688            );
8689            let wait = self.repository_wait();
8690            let (outcomes, verify_retried) = with_cache_lease(
8691                &mut self.state,
8692                cache_dir.as_deref(),
8693                "e2e",
8694                "e2e",
8695                worktree,
8696                &before_head,
8697                timeout,
8698                &context,
8699                &wait,
8700                |state, budget| {
8701                    let shell = shell.to_vec();
8702                    let commands = commands.clone();
8703                    let context = context.clone();
8704                    async move {
8705                        if let Some(winner) = winner.filter(|_| !commands.is_empty()) {
8706                            // Same reason as in the round itself: format before
8707                            // the suite, not after it.
8708                            Self::run_pre_gate(state, &winner).await;
8709                        }
8710                        run_e2e_with_retry(
8711                            state,
8712                            &shell,
8713                            &commands,
8714                            worktree,
8715                            budget,
8716                            &context,
8717                            Some(round),
8718                        )
8719                        .await
8720                    }
8721                },
8722            )
8723            .await?;
8724            // After `pre_gate`: the commit the commands actually ran against.
8725            let attempted_head = git::rev_parse(worktree, "HEAD").await?;
8726            if !outcomes.is_empty() && !verify_inconclusive(&outcomes) {
8727                self.state.record_base_progress(&attempted_head);
8728            }
8729            let last = &mut self.state.reviews[round_idx];
8730            last.e2e = outcomes;
8731            last.verify_retried = verify_retried;
8732            // Always the commit and time this attempt actually targeted,
8733            // whether or not it happens to equal the reviewed `head` and
8734            // whether or not a command finished — see
8735            // `ReviewRound::verified_head`'s own doc. A still-inconclusive
8736            // attempt is recorded too, so a later reader sees "attempted
8737            // again at T2" rather than silence.
8738            last.verified_head = Some(attempted_head);
8739            last.verified_at = Some(Timestamp::now());
8740            if verify_inconclusive(&last.e2e) {
8741                // Still not a real result: `e2e_deferred` is left exactly
8742                // as it was, so `needs_catchup_run` above reads
8743                // `ResourceBlocked` (via `e2e_status`, which checks
8744                // `resource_blocked` before `e2e_deferred`) and retries
8745                // again on the next reentry, rather than recording
8746                // contention as a red e2e and blocking the run on it.
8747                self.state.save()?;
8748                return Ok(());
8749            }
8750            last.e2e_deferred = false;
8751            // A complete panel may have been saved as unclean solely because
8752            // verification could not run. Refresh that verdict with the new
8753            // outcomes before a granted repair consumes the round's result.
8754            // Incomplete panels retain their original policy/quota decision.
8755            if last.answered == last.expected {
8756                last.clean = round_is_clean(
8757                    last.blocking,
8758                    last.e2e.iter().all(CommandOutcome::ok),
8759                    last.answered,
8760                    last.expected,
8761                    0,
8762                    self.state.config.graph.incomplete_review,
8763                );
8764            }
8765        }
8766        let last = &self.state.reviews[round_idx];
8767        let open: usize = last.reviews.iter().map(|r| r.findings.len()).sum();
8768
8769        match last.e2e_status() {
8770            E2eStatus::Failed => {
8771                let red: Vec<String> = last
8772                    .e2e
8773                    .iter()
8774                    .filter(|o| !o.ok())
8775                    .map(|o| {
8776                        let comparison = crate::verify_evidence::outcome_comparison_summary(o)
8777                            .map(|c| format!(" ({c})"))
8778                            .unwrap_or_default();
8779                        format!(
8780                            "`{}` -> {:?}{comparison}\n{}",
8781                            o.command,
8782                            o.code,
8783                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
8784                        )
8785                    })
8786                    .collect();
8787                let can_repair = last.blocking == 0 && last.fix.is_none();
8788                self.state.reviews[round_idx].clean = false;
8789                self.state
8790                    .event("review", format!("{why}; e2e failed:\n{}", red.join("\n")));
8791                self.state.status = RunStatus::Blocked;
8792                if repairable
8793                    && can_repair
8794                    && self.state.reviews.len() < self.state.config.graph.review_rounds
8795                {
8796                    self.state.status = RunStatus::Reviewing;
8797                }
8798            }
8799            // `needs_catchup_run` above already retried once this call; if
8800            // it is still blocked, this is magi's own admission it could
8801            // not get a command to run, never a verdict on the patch — the
8802            // run is left exactly where a later reentry can retry again.
8803            E2eStatus::ResourceBlocked => {
8804                self.state.event(
8805                    "review",
8806                    format!(
8807                        "{why}; e2e could not run (resource unavailable); not \
8808                         deciding yet"
8809                    ),
8810                );
8811            }
8812            E2eStatus::Passed | E2eStatus::Deferred | E2eStatus::NotConfigured => {
8813                self.state.event(
8814                    "review",
8815                    format!("{why}; e2e is green — handing off with {open} finding(s) still open"),
8816                );
8817                self.record_contested_handoff();
8818                self.state.status = RunStatus::Gating;
8819            }
8820        }
8821        self.state.save()?;
8822        Ok(())
8823    }
8824
8825    // ----------------------------------------------------------------- gate
8826
8827    async fn gate(&mut self) -> Result<()> {
8828        if self.hold_base_sync().await? {
8829            return Ok(());
8830        }
8831        // Judged by the review record itself, not by `status`: a solo
8832        // candidate's `judge`/`deliberate` skip rewrites `status` on every
8833        // reentry (see `judge`), and trusting it here is exactly how a run
8834        // that exhausted its review budget got gated and merged a second
8835        // time around. `review_conclusion` recomputes the review loop's own
8836        // verdict from the round records themselves — `Gating` for a clean
8837        // round or a hand-off (see `stop_reviewing`), anything else means the
8838        // loop is still going or genuinely blocked.
8839        // A base the winner could not be replayed onto is a decision, not a
8840        // round: there is no landing tree to gate. Read as its own record for
8841        // the same reason the review verdict is.
8842        if self.state.status == RunStatus::Failed
8843            || self
8844                .state
8845                .base_sync
8846                .as_ref()
8847                .is_some_and(|s| s.conflict.is_some())
8848            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
8849                != Some(RunStatus::Gating)
8850        {
8851            return Ok(());
8852        }
8853        let Some(winner) = self.state.winner().cloned() else {
8854            return Ok(());
8855        };
8856        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
8857        self.state.reconcile_verification_head(&head);
8858        self.state.save()?;
8859        let wait = self.repository_wait();
8860        if !verify_current_head(&mut self.state, &winner, &wait).await? {
8861            return Ok(());
8862        }
8863        if self.state.gate_ran {
8864            // `review_loop` derives its conclusion from the clean review
8865            // record on every reentry and therefore puts a completed run back
8866            // in `Gating`. A recorded gate is a stronger, terminal fact:
8867            // retain its original command output (or lack of any, for a repo
8868            // with no `verify.gate` commands — see `RunState::gate_ran`'s own
8869            // doc) and restore `Blocked` on a real failure rather than
8870            // pretending the command is still running or running it a second
8871            // time. `gate_ran == false` remains the only shape — unattempted,
8872            // or a resource-blocked retry — that may still need to execute a
8873            // command.
8874            if self.state.gate.iter().any(|outcome| !outcome.ok()) {
8875                self.state.status = RunStatus::Blocked;
8876                self.state.save()?;
8877            }
8878            return Ok(());
8879        }
8880        self.state.status = RunStatus::Gating;
8881        let mut outcomes = self.run_gate(&winner).await?;
8882        let mut attempted_head = self.state.gate_head.clone();
8883        loop {
8884            // A resource-blocked outcome means the gate command never actually
8885            // ran - the shared build cache could not be acquired or confirmed
8886            // fresh in time - which is evidence about the machine, not about
8887            // the tree (see `CommandOutcome::resource_blocked`'s own doc).
8888            // Recording it as a red gate would mark a run `Blocked` on nothing
8889            // but contention magi has already logged; leaving `self.state.gate`
8890            // empty and `self.state.gate_ran` false instead keeps the shape
8891            // this function already treats as "still needs to run" (see the
8892            // early-return above), so the next call retries the command
8893            // rather than concluding anything.
8894            if verify_inconclusive(&outcomes) {
8895                self.state.save()?;
8896                return Ok(());
8897            }
8898            if outcomes.iter().all(CommandOutcome::ok) {
8899                break;
8900            }
8901            let fixes_before = self.state.gate_fixes.len();
8902            match self.gate_fix_round(&winner, &outcomes).await? {
8903                GateFix::Retry => {
8904                    outcomes = self.run_gate(&winner).await?;
8905                    attempted_head = self.state.gate_head.clone();
8906                }
8907                GateFix::Stop => {
8908                    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
8909                    if self.state.gate_fixes.len() > fixes_before
8910                        && attempted_head.as_deref() != Some(current.as_str())
8911                        && verify_current_head(&mut self.state, &winner, &wait).await?
8912                    {
8913                        // A new SHA owes a gate even when a spent fixer changed only
8914                        // commit metadata. This does not grant another repair round.
8915                        outcomes = self.run_gate(&winner).await?;
8916                        attempted_head = self.state.gate_head.clone();
8917                    } else {
8918                        break;
8919                    }
8920                }
8921                GateFix::Defer => {
8922                    self.state.save()?;
8923                    return Ok(());
8924                }
8925            }
8926        }
8927        let passed = outcomes.iter().all(CommandOutcome::ok);
8928        self.state.gate = outcomes;
8929        self.state.gate_ran = true;
8930        self.state.gate_head = attempted_head;
8931        if !self.state.gate.is_empty()
8932            && !verify_inconclusive(&self.state.gate)
8933            && let Some(head) = self.state.gate_head.clone()
8934        {
8935            self.state.record_base_progress(&head);
8936        }
8937        self.state.save()?;
8938        if !verify_current_head(&mut self.state, &winner, &wait).await? {
8939            return Ok(());
8940        }
8941        if !passed {
8942            self.state.status = RunStatus::Blocked;
8943            let spent = self.state.gate_fixes.len();
8944            self.state.event(
8945                "gate",
8946                if spent == 0 {
8947                    "gate failed; not merging".to_owned()
8948                } else {
8949                    format!("gate failed after {spent} gate-fix round(s); not merging")
8950                },
8951            );
8952        }
8953        self.state.save()?;
8954        Ok(())
8955    }
8956
8957    /// Run `verify.pre_gate` in the winner's worktree, then fold whatever it
8958    /// changed into one commit. Runs before `verify.e2e` in the review loop
8959    /// and again before the gate commands, always on the winner and never on
8960    /// a candidate awaiting judging.
8961    ///
8962    /// Before e2e as well as before the gate because command evidence belongs
8963    /// to a SHA ([`verify_current_head`]): a commit made only at the gate is a
8964    /// commit e2e never saw, and the suite ran again for a formatter's diff -
8965    /// 5 of the 22 gated runs on this repository in November 2026. The gate's
8966    /// own call then finds nothing left to change. The commands must be
8967    /// idempotent; one that is not makes a commit per call.
8968    ///
8969    /// Never fails the run: a non-zero exit or timeout is a warning and a
8970    /// recorded outcome, and the gate remains the single arbiter. Nothing
8971    /// configured means nothing happens - no event, no commit. `commit_all`
8972    /// commits any leftover change under the neutral identity and returns
8973    /// `false` when the tree is clean, so no empty commit is ever made.
8974    async fn run_pre_gate(state: &mut RunState, winner: &Candidate) {
8975        let commands = state.config.verify.pre_gate.clone();
8976        if commands.is_empty() {
8977            return;
8978        }
8979        let shell = state.config.shell();
8980        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
8981        let (outcomes, _) = run_commands(
8982            state,
8983            "pre_gate",
8984            "pre_gate",
8985            0,
8986            &shell,
8987            &commands,
8988            &winner.worktree,
8989            timeout,
8990        )
8991        .await;
8992        for o in &outcomes {
8993            if !o.ok() {
8994                tracing::warn!(
8995                    "pre_gate `{}` failed ({:?}); the gate decides",
8996                    o.command,
8997                    o.code
8998                );
8999            }
9000            state.event(
9001                "pre_gate",
9002                format!(
9003                    "`{}` -> {}",
9004                    o.command,
9005                    if o.ok() {
9006                        "pass".to_owned()
9007                    } else {
9008                        format!(
9009                            "FAIL ({:?})\n{}",
9010                            o.code,
9011                            summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
9012                        )
9013                    }
9014                ),
9015            );
9016        }
9017        state.pre_gate = outcomes;
9018        match git::commit_all(&winner.worktree, "magi: pre_gate (mechanical fixes)").await {
9019            Ok(true) => match git::rev_parse(&winner.worktree, "HEAD").await {
9020                Ok(head) => {
9021                    state.event("pre_gate", format!("committed mechanical fixes ({head})"));
9022                    state.pre_gate_commit = Some(head);
9023                }
9024                Err(e) => tracing::warn!("pre_gate committed but HEAD unreadable: {e:#}"),
9025            },
9026            Ok(false) => {}
9027            Err(e) => tracing::warn!("pre_gate could not commit its changes: {e:#}"),
9028        }
9029        if let Err(e) = state.save() {
9030            tracing::warn!("could not persist the pre_gate record: {e:#}");
9031        }
9032    }
9033
9034    /// Run `verify.gate` once against the winner's current tree, logging one
9035    /// event per command. Empty when nothing is configured.
9036    async fn run_gate(&mut self, winner: &Candidate) -> Result<Vec<CommandOutcome>> {
9037        let wait = self.repository_wait();
9038        run_landing_gate(&mut self.state, winner, &wait).await
9039    }
9040
9041    /// One bounded fix round for a failing gate.
9042    ///
9043    /// The fixer is told the failure came from the gate itself, not from a
9044    /// reviewer, and is shown the failed commands, their exit codes and a tail
9045    /// of their output - whatever `[verify].gate` holds, nothing here knows
9046    /// what those commands run. Only a normal non-zero exit that printed
9047    /// something earns a round (see [`gate_fixable`]): a timeout, a missing
9048    /// command or a full disk says nothing about the code, and a fixer sent
9049    /// after it can only appease the machine. The round is judged by what git
9050    /// says moved, never by the fixer's own report, and `verify.e2e` runs
9051    /// again before the gate does, so a fix cannot trade a green gate for a
9052    /// red e2e unnoticed.
9053    async fn gate_fix_round(
9054        &mut self,
9055        winner: &Candidate,
9056        outcomes: &[CommandOutcome],
9057    ) -> Result<GateFix> {
9058        let cap = if self.state.repair_grants.last().is_some_and(|g| {
9059            g.phase == crate::repair_budget::Phase::Fixing
9060                && g.receipt.request.kind == crate::repair_budget::Kind::Gate
9061        }) {
9062            self.state.gate_fixes.len().saturating_add(1)
9063        } else {
9064            self.state.config.graph.gate_fix_rounds
9065        };
9066        let spent = self.state.gate_fixes.len();
9067        if spent >= cap {
9068            if cap > 0 {
9069                self.state.event(
9070                    "gate",
9071                    format!("{spent} gate-fix round(s) spent and the gate still fails"),
9072                );
9073            }
9074            return Ok(GateFix::Stop);
9075        }
9076        if !gate_fixable(outcomes) {
9077            self.state.event(
9078                "gate",
9079                "gate failure is not an ordinary non-zero exit with output (timeout, missing \
9080                 command or similar); not spending a fix round on it",
9081            );
9082            return Ok(GateFix::Stop);
9083        }
9084        let min_free = self.state.config.disk.min_free_bytes;
9085        if min_free > 0 {
9086            match crate::disk::free_bytes(&winner.worktree) {
9087                Ok(free) if crate::disk::enough_space(free, min_free) => {}
9088                Ok(free) => {
9089                    self.state.event(
9090                        "gate",
9091                        format!(
9092                            "only {free} bytes free ({min_free} required by `[disk] \
9093                             min_free_bytes`); not spending a fix round on a failure the disk \
9094                             may explain"
9095                        ),
9096                    );
9097                    return Ok(GateFix::Stop);
9098                }
9099                Err(e) => {
9100                    self.state.event(
9101                        "gate",
9102                        format!("free disk space could not be measured ({e:#}); no fix round"),
9103                    );
9104                    return Ok(GateFix::Stop);
9105                }
9106            }
9107        }
9108
9109        let attempt = spent + 1;
9110        let failed: Vec<CommandOutcome> = outcomes.iter().filter(|o| !o.ok()).cloned().collect();
9111        let base = self.landing_base();
9112        let fix_prompt = prompt::gate_fix_in(
9113            &self.state.instruction,
9114            &failed,
9115            attempt,
9116            cap,
9117            &self.state.config.graph.language,
9118            &self.state.config.graph.github_language,
9119        );
9120        let timeout = Duration::from_secs(self.state.config.graph.timeout_fix);
9121        let sessions = self.state.config.graph.sessions;
9122        let artifacts = self.merge_repair_artifacts();
9123        self.state.event(
9124            "gate",
9125            format!("gate failed; gate-fix round {attempt} of {cap}"),
9126        );
9127        let before = git::rev_parse(&winner.worktree, "HEAD").await?;
9128        let patch = git::diff(&winner.worktree, &base, "HEAD").await?;
9129        // Persist before invoking the fixer: it may commit and then be
9130        // interrupted before its result (or the following e2e) is saved.
9131        self.state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
9132            before.clone(),
9133            false,
9134            Vec::new(),
9135        ));
9136        self.state.save()?;
9137        let (_, seat, out) = self
9138            .ask_fixer(winner, "gate-fix", None, |spec, seat| SeatJob {
9139                prompt: fix_prompt.clone(),
9140                spec,
9141                seat,
9142                cwd: winner.worktree.clone(),
9143                timeout,
9144                allow_write: true,
9145                sessions,
9146                artifacts: artifacts.clone(),
9147                stem: format!("gate-fix-{attempt}"),
9148                handover: None,
9149            })
9150            .await;
9151        // The fixer was never asked: no round is spent (nothing is recorded)
9152        // and a later reentry asks the same agent again.
9153        if matches!(out, AgentOutcome::ResourceBlocked(_)) {
9154            return Ok(GateFix::Defer);
9155        }
9156        let mut record = GateFixRecord {
9157            agent: seat.agent.clone(),
9158            failed,
9159            notes: String::new(),
9160            committed: false,
9161            error: None,
9162        };
9163        match out {
9164            AgentOutcome::Ok(o) => {
9165                // A missing report is not a failed fix: the round is judged
9166                // by the tree below, and the report only carries prose.
9167                if let Ok(report) = verdict::extract_json::<FixReport>(&o.text) {
9168                    record.notes = blind::sanitize_prose(&report.notes, &self.state.config.blind);
9169                }
9170            }
9171            AgentOutcome::Dropped(_) => {
9172                record.error = Some("the CLI dropped the stream".to_owned());
9173            }
9174            AgentOutcome::Quota(o) => {
9175                self.state.quota.push(QuotaLoss::from_report(
9176                    seat.key.clone(),
9177                    "gate-fix",
9178                    o.quota.as_ref(),
9179                ));
9180                record.error = Some("rate limited (quota); fixer could not run".to_owned());
9181            }
9182            AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => record.error = Some(e),
9183        }
9184        self.state.seats.insert(seat.key.clone(), seat);
9185        let coordination = self.coordinate(&winner.worktree).await?;
9186        if let Ok(r) = git::rescue_commit(
9187            &winner.worktree,
9188            &format!("magi: gate fix {attempt} (uncommitted work)"),
9189        )
9190        .await
9191        {
9192            self.state.note_withheld("gate-fix", &r.withheld);
9193        }
9194        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
9195        record.committed = after != before;
9196        let changed = git::diff(&winner.worktree, &base, "HEAD").await? != patch;
9197        let note = record.error.clone();
9198        self.state.gate_fixes.push(record);
9199        self.state.save()?;
9200        if !changed {
9201            self.state.event(
9202                "gate",
9203                match note {
9204                    Some(why) => format!("gate-fix round {attempt}: fixer failed ({why})"),
9205                    None => format!("gate-fix round {attempt}: the tree did not change"),
9206                },
9207            );
9208            return Ok(GateFix::Stop);
9209        }
9210        self.state.event(
9211            "gate",
9212            format!("gate-fix round {attempt}: tree changed vs base; re-running verify.e2e"),
9213        );
9214
9215        drop(coordination);
9216        let wait = self.repository_wait();
9217        check_gate_repair_e2e(&mut self.state, winner, &wait).await
9218    }
9219
9220    // ---------------------------------------------------------------- merge
9221
9222    /// One read-only rewrite by the summary's author; a text the gate still
9223    /// withholds goes to the owner (see `github_text`) and the fixed fallback
9224    /// applies on their word or on silence. `None` means the run is parked on
9225    /// that question and nothing may be pushed or opened yet.
9226    async fn guarded_pr_message(
9227        &mut self,
9228        winner: &Candidate,
9229        facts: Option<&BranchFacts>,
9230        posting: bool,
9231    ) -> Result<Option<PrMessage>> {
9232        let final_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
9233        let head = match final_head.as_deref() {
9234            Some(h) => crate::pr_outcome::FinalHead::At(h),
9235            None => crate::pr_outcome::FinalHead::Unknown,
9236        };
9237        // Only a pull request that is about to be posted pays for a summary.
9238        let summarized = if posting {
9239            Some(self.summarize_change(winner, final_head.as_deref()).await)
9240        } else {
9241            None
9242        };
9243        // A busy shared resource is not a permanent cause: publishing an
9244        // "unavailable" description would stick (a later head move never
9245        // edits the body). Stop before anything is pushed or opened; the
9246        // run is `Blocked` and a resume asks the summary again.
9247        if self.state.resource_block.is_some() {
9248            self.state.event(
9249                "pr-summary",
9250                "a shared resource was busy; nothing was published, resume to summarize again",
9251            );
9252            return Ok(None);
9253        }
9254        if posting && git::rev_parse(&winner.worktree, "HEAD").await.ok() != final_head {
9255            anyhow::bail!(
9256                "the final commit moved during public description generation; retry before publishing"
9257            );
9258        }
9259        let note = match (&summarized, &self.state.change_summary) {
9260            (Some(Ok(())), Some(c)) => ChangeNote::Summary(c),
9261            (Some(Err(why)), _) => ChangeNote::Unavailable(why),
9262            (Some(Ok(())), None) => ChangeNote::Unavailable("no summary was recorded"),
9263            (None, _) => ChangeNote::NotAsked,
9264        };
9265        let mut pr = pr_message_raw(&self.state, winner.label, facts, head, note);
9266        if !posting {
9267            let identity = crate::scrub::Identity::current();
9268            return Ok(Some(PrMessage {
9269                title: crate::scrub::scrub(&pr.title, &identity),
9270                body: crate::scrub::scrub(&pr.body, &identity),
9271            }));
9272        }
9273        // This very text was already rejected and asked about: no second
9274        // judge call, rewrite or question, just carry the record on.
9275        let raw_fp = crate::github_text::fingerprint(&pr.title, &pr.body);
9276        if let Some(known) = self
9277            .state
9278            .github_text
9279            .clone()
9280            .filter(|g| g.fingerprint == raw_fp)
9281        {
9282            return self.settle_withheld(winner, &pr, known).await;
9283        }
9284        let mut decision = self.judge_pr_language(&winner.worktree, &pr).await;
9285        let mut violations =
9286            crate::github_text::check_for(&self.state.config.graph, &pr.title, &pr.body, decision);
9287        let identity = crate::scrub::Identity::current();
9288        if (crate::scrub::scrub(&pr.title, &identity) != pr.title
9289            || crate::scrub::scrub(&pr.body, &identity) != pr.body)
9290            && !violations.contains(&crate::github_text::Violation::SensitiveData)
9291        {
9292            violations.push(crate::github_text::Violation::SensitiveData);
9293        }
9294        // A rewrite cannot fix sensitive data (e.g. a quoted original task), so
9295        // only a language violation starts one; sensitive data alone goes
9296        // straight to the owner, with the redacted text as the fallback.
9297        let has_language = violations
9298            .iter()
9299            .any(|v| *v != crate::github_text::Violation::SensitiveData);
9300        if self.state.config.graph.github_text_guard && !violations.is_empty() {
9301            self.state.event(
9302                "github-text",
9303                if has_language {
9304                    format!("description rejected: {violations:?}; requesting one rewrite")
9305                } else {
9306                    format!("description rejected: {violations:?}; asking the owner")
9307                },
9308            );
9309            let mut rewritten = false;
9310            let mut rejected_rewrite = None;
9311            if has_language && let Some(text) = self.rewrite_pr_text(winner, &pr, &violations).await
9312            {
9313                let output = text;
9314                if let Some(title) = summary_title(&output) {
9315                    // Judge the redacted candidate that will actually be posted.
9316                    // Sensitive data alone must not discard a useful rewrite.
9317                    let raw_body = summary_without_title(&output);
9318                    let clean_title = crate::scrub::scrub(&title, &identity);
9319                    let mut body = crate::scrub::scrub(&raw_body, &identity);
9320                    let redacted = clean_title != title || body != raw_body;
9321                    let title = clean_title;
9322                    let complete = crate::pr_outcome::covers_required_findings(&self.state, &body);
9323                    if !complete {
9324                        self.state.event(
9325                            "github-text",
9326                            "description rewrite omitted required findings",
9327                        );
9328                    }
9329                    if !body.trim().is_empty() {
9330                        body.push_str("\n\n");
9331                        body.push_str(&public_pr_evidence(&self.state, head));
9332                    }
9333                    let marker = format!("magi:run/{}", self.state.id);
9334                    if !body.trim().is_empty() && !body.contains(&marker) {
9335                        body.push_str(&format!("\n\n{marker}"));
9336                    }
9337                    let rewrite = PrMessage {
9338                        title: title.clone(),
9339                        body: body.clone(),
9340                    };
9341                    let redecision = self.judge_pr_language(&winner.worktree, &rewrite).await;
9342                    let mut failed = crate::github_text::check_for(
9343                        &self.state.config.graph,
9344                        &title,
9345                        &body,
9346                        redecision,
9347                    );
9348                    if (!crate::github_text::shareable(&title)
9349                        || !crate::github_text::shareable(&body))
9350                        && !failed.contains(&crate::github_text::Violation::SensitiveData)
9351                    {
9352                        failed.push(crate::github_text::Violation::SensitiveData);
9353                    }
9354                    if complete
9355                        && !title.trim().is_empty()
9356                        && !body.trim().is_empty()
9357                        && !failed.is_empty()
9358                    {
9359                        rejected_rewrite = Some(crate::run::GithubTextRewrite {
9360                            title: title.clone(),
9361                            body: body.clone(),
9362                            failed: failed
9363                                .iter()
9364                                .map(|v| crate::github_text::category(*v).to_owned())
9365                                .collect(),
9366                        });
9367                    }
9368                    if complete
9369                        && !title.trim().is_empty()
9370                        && !raw_body.trim().is_empty()
9371                        && failed.is_empty()
9372                    {
9373                        decision = redecision;
9374                        pr = PrMessage { title, body };
9375                        rewritten = true;
9376                        self.state
9377                            .event("github-text", "description rewrite passed");
9378                        if redacted {
9379                            self.state.event(
9380                                "github-text",
9381                                "sensitive data removed from description rewrite",
9382                            );
9383                        }
9384                    }
9385                }
9386            }
9387            if !rewritten {
9388                self.state.event(
9389                    "github-text",
9390                    "description rewrite unavailable or rejected; asking the owner",
9391                );
9392                if let Some(w) =
9393                    crate::github_text::Withheld::from_check(&violations, &pr.title, &pr.body)
9394                {
9395                    // A different text than the one asked about before: that
9396                    // question no longer describes anything.
9397                    self.retire_github_text_question("the withheld text changed");
9398                    let record = crate::run::GithubTextAsk {
9399                        rewrite: rejected_rewrite,
9400                        fingerprint: raw_fp,
9401                        title: w.title,
9402                        body: w.body,
9403                        categories: w.categories.iter().map(|c| (*c).to_owned()).collect(),
9404                        question: None,
9405                        asks: 0,
9406                        resolved: false,
9407                        chosen_title: None,
9408                        choice: None,
9409                        publication: None,
9410                    };
9411                    return self.settle_withheld(winner, &pr, record).await;
9412                }
9413            }
9414        }
9415        let (title, body) =
9416            crate::github_text::prepare_with(&mut self.state, &pr.title, &pr.body, decision);
9417        Ok(Some(PrMessage { title, body }))
9418    }
9419
9420    /// Describe the whole change from its final diff in either run mode.
9421    ///
9422    /// The summary is tied to the final commit and to the merge base of the
9423    /// resolved remote base; a record for any other pair is dropped and the
9424    /// agent asked again, so a description never outlives the diff it was
9425    /// written from. The seat is read-only and the prompt tells it to read the
9426    /// diff and the code around it. `[roles] synthesizer` selects the agents
9427    /// (unset: the default pick), each asked at most once, advancing on an
9428    /// error, quota, unusable answer or a reply with no `TITLE:` line. `Err`
9429    /// carries the reason it is unavailable; nothing is invented then.
9430    async fn summarize_change(
9431        &mut self,
9432        winner: &Candidate,
9433        head: Option<&str>,
9434    ) -> std::result::Result<(), String> {
9435        let Some(head) = head else {
9436            return Err("the final commit could not be read".to_owned());
9437        };
9438        let remote = self.state.config.merge.remote.clone();
9439        let tracking = format!("{remote}/{}", self.state.base_branch);
9440        if !git::rev_exists(&winner.worktree, &tracking).await {
9441            return Err(format!("the remote base `{tracking}` could not be read"));
9442        }
9443        let base = match git::merge_base(&winner.worktree, &tracking, head).await {
9444            Ok(b) if !b.is_empty() => b,
9445            _ => return Err("the merge base with the remote base could not be read".to_owned()),
9446        };
9447        let evidence = crate::pr_outcome::summary_evidence(
9448            &self.state,
9449            crate::pr_outcome::FinalHead::At(head),
9450        );
9451        let fingerprint = crate::pr_outcome::summary_fingerprint(&self.state, &evidence);
9452        if self
9453            .state
9454            .change_summary
9455            .as_ref()
9456            .is_some_and(|c| c.head == head && c.base == base && c.evidence == fingerprint)
9457        {
9458            return Ok(());
9459        }
9460        if self.state.change_summary.take().is_some() {
9461            self.state.event(
9462                "pr-summary",
9463                "the final diff or evidence changed; the earlier change summary was discarded",
9464            );
9465        }
9466        // Save the source snapshot even if no generation agent is available.
9467        if let Err(e) = write_artifact(
9468            &self.state,
9469            &format!("public-description-{fingerprint}.md"),
9470            &format!("Final diff: {base}..{head}\n\n{evidence}"),
9471        ) {
9472            tracing::warn!("could not save public description evidence: {e:#}");
9473        }
9474        let chain = match agent::pick_chain(
9475            &self.state.config.agents,
9476            self.state.config.roles.synthesizer.as_ref(),
9477            &agent::installed,
9478            "synthesizer",
9479        ) {
9480            Ok(chain) => chain,
9481            Err(e) => {
9482                tracing::warn!("no agent for the change summary: {e:#}");
9483                self.state.event("pr-summary", "no summary agent available");
9484                return Err("no agent was available to summarize it".to_owned());
9485            }
9486        };
9487        let subjects = git::subjects(&winner.worktree, &base, head)
9488            .await
9489            .unwrap_or_default();
9490        let stat = git::diff_stat(&winner.worktree, &base, head)
9491            .await
9492            .unwrap_or_default();
9493        let stat: String = stat.chars().take(6_000).collect();
9494        let mut prompt = crate::prompt::change_summary_in(
9495            &base,
9496            head,
9497            &subjects,
9498            stat.trim(),
9499            &self.state.config.graph.github_language,
9500        );
9501        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."));
9502        let sessions = self.state.config.graph.sessions;
9503        let timeout = Duration::from_secs(self.state.config.graph.timeout_implement);
9504        let prompts = self.state.config.prompts.clone();
9505        let cache = self.state.config.cache_dir();
9506        let run = self.state.id.clone();
9507        for (i, spec) in chain.into_iter().enumerate() {
9508            let seat = crate::fixer::seat_for(&mut self.state, "change-summary", &spec.id);
9509            let github_spec = match agent::for_github_text(
9510                &spec,
9511                &self.state.config.graph.github_language,
9512                &winner.worktree,
9513            ) {
9514                Ok(spec) => spec,
9515                Err(e) => {
9516                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9517                    continue;
9518                }
9519            };
9520            let job = SeatJob {
9521                spec: github_spec,
9522                seat,
9523                cwd: winner.worktree.clone(),
9524                prompt: prompt.clone(),
9525                timeout,
9526                allow_write: false,
9527                sessions,
9528                artifacts: agent::artifacts_dir(&self.state.dir()),
9529                stem: if i == 0 {
9530                    "change-summary".to_owned()
9531                } else {
9532                    format!("change-summary-{}", spec.id)
9533                },
9534                handover: None,
9535            };
9536            let ctx = WaveCtx {
9537                run: &run,
9538                node: "pr-summary",
9539                prompts: &prompts,
9540                cache: cache.as_deref(),
9541                round: None,
9542                carry_seats: false,
9543                pauses: Some((&self.pause, &self.interrupt)),
9544            };
9545            let (seat, outcome) =
9546                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9547            self.state.seats.insert(seat.key.clone(), seat);
9548            let text = match outcome {
9549                AgentOutcome::Ok(o) if !agent::output_advances(&o) => o.text,
9550                AgentOutcome::ResourceBlocked(why) => {
9551                    // No agent was asked: the run stops resumably before
9552                    // anything is published (see `guarded_pr_message`).
9553                    if self.state.resource_block.is_none() {
9554                        self.state.resource_block = Some(crate::run::ResourceBlock {
9555                            cause: crate::run::ResourceBlockCause::Other,
9556                            node: "pr-summary".to_owned(),
9557                            kind: "shared resource".to_owned(),
9558                            detail: why,
9559                            at: Timestamp::now(),
9560                        });
9561                    }
9562                    return Err("a shared resource was busy".to_owned());
9563                }
9564                _ => continue,
9565            };
9566            let blind = &self.state.config.blind;
9567            let Some(title) = summary_title(&text) else {
9568                continue;
9569            };
9570            let body: String = summary_without_title(&text)
9571                .lines()
9572                .filter(|l| !l.contains("magi:run/"))
9573                .collect::<Vec<_>>()
9574                .join("\n");
9575            let body = blind::sanitize_prose(body.trim(), blind);
9576            let title = blind::sanitize_prose(&title, blind);
9577            if body.trim().is_empty() || title.trim().is_empty() {
9578                continue;
9579            }
9580            if !crate::pr_outcome::covers_required_findings(&self.state, &body) {
9581                continue;
9582            }
9583            // The branch must still be the one the agent was shown.
9584            if git::rev_parse(&winner.worktree, "HEAD")
9585                .await
9586                .ok()
9587                .as_deref()
9588                != Some(head)
9589            {
9590                return Err("the branch moved while the summary was written".to_owned());
9591            }
9592            if git::merge_base(&winner.worktree, &tracking, head)
9593                .await
9594                .ok()
9595                .as_deref()
9596                != Some(base.as_str())
9597                || crate::pr_outcome::summary_evidence(
9598                    &self.state,
9599                    crate::pr_outcome::FinalHead::At(head),
9600                ) != evidence
9601            {
9602                return Err("the summary evidence changed while it was written".to_owned());
9603            }
9604            self.state.change_summary = Some(crate::run::ChangeSummary {
9605                head: head.to_owned(),
9606                base,
9607                evidence: fingerprint,
9608                title,
9609                body,
9610            });
9611            self.state.event(
9612                "pr-summary",
9613                format!("change summary written by {} for the final diff", spec.id),
9614            );
9615            if let Err(e) = self.state.save() {
9616                tracing::warn!("could not save the change summary: {e:#}");
9617            }
9618            return Ok(());
9619        }
9620        self.state
9621            .event("pr-summary", "no agent produced a change summary");
9622        Err("the summarizing agents were unavailable or gave no usable answer".to_owned())
9623    }
9624
9625    /// One read-only rewrite request for a withheld description. The
9626    /// implementer's own conversation is tried first when it exists and can be
9627    /// resumed; then the `[roles] language_judge` chain (or the default pick)
9628    /// writes it in a separate conversation, skipping the implementer's agent.
9629    /// The prompt carries the whole text, so no agent needs any memory. Each
9630    /// agent is asked at most once and the chain advances on an error, quota,
9631    /// unusable answer or a reply with no `TITLE:` line: a resumed implementer
9632    /// that has run out of quota must not end the rewrite. Nothing is recorded
9633    /// as a handover.
9634    async fn rewrite_pr_text(
9635        &mut self,
9636        winner: &Candidate,
9637        pr: &PrMessage,
9638        violations: &[crate::github_text::Violation],
9639    ) -> Option<String> {
9640        let prompt = format!(
9641            "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{}",
9642            pr.title, pr.body
9643        );
9644        let sessions = self.state.config.graph.sessions;
9645        let timeout_full = Duration::from_secs(self.state.config.graph.timeout_implement);
9646        // (spec, the resumed implementer's seat). A fallback seat is created
9647        // only when its turn comes, so an unused fallback leaves no record.
9648        let mut attempts: Vec<(AgentSpec, Option<SeatState>)> = Vec::new();
9649        let key = format!("impl-{}", winner.label);
9650        if let Some(spec) = self
9651            .state
9652            .config
9653            .agents
9654            .iter()
9655            .find(|a| a.id == winner.agent)
9656            .cloned()
9657            && let Some(existing) = self.state.seats.get(&key)
9658            && existing.agent == spec.id
9659            && agent::has_session(spec.kind, existing, sessions)
9660        {
9661            attempts.push((spec, Some(existing.clone())));
9662        }
9663        match agent::pick_chain(
9664            &self.state.config.agents,
9665            self.state.config.roles.language_judge.as_ref(),
9666            &agent::installed,
9667            "language_judge",
9668        ) {
9669            Ok(chain) => {
9670                for spec in chain {
9671                    if attempts.iter().any(|(tried, _)| tried.id == spec.id) {
9672                        continue;
9673                    }
9674                    attempts.push((spec, None));
9675                }
9676            }
9677            Err(e) if attempts.is_empty() => {
9678                tracing::warn!("no agent for the description rewrite: {e:#}");
9679                self.state
9680                    .event("github-text", "no rewrite agent available");
9681                return None;
9682            }
9683            Err(e) => tracing::warn!("no fallback agent for the description rewrite: {e:#}"),
9684        }
9685        let prompts = self.state.config.prompts.clone();
9686        let cache = self.state.config.cache_dir();
9687        let run = self.state.id.clone();
9688        for (i, (spec, resumed_seat)) in attempts.into_iter().enumerate() {
9689            let resumed = resumed_seat.is_some();
9690            let seat = resumed_seat.unwrap_or_else(|| {
9691                crate::fixer::seat_for(&mut self.state, "github-text-rewrite", &spec.id)
9692            });
9693            let github_spec = match agent::for_github_text(
9694                &spec,
9695                &self.state.config.graph.github_language,
9696                &winner.worktree,
9697            ) {
9698                Ok(spec) => spec,
9699                Err(e) => {
9700                    tracing::warn!(agent = %spec.id, "cannot prepare GitHub text settings: {e:#}");
9701                    continue;
9702                }
9703            };
9704            let job = SeatJob {
9705                spec: github_spec,
9706                seat,
9707                cwd: winner.worktree.clone(),
9708                prompt: prompt.clone(),
9709                timeout: retry_budget(timeout_full, resumed),
9710                allow_write: false,
9711                sessions,
9712                artifacts: agent::artifacts_dir(&self.state.dir()),
9713                stem: if i == 0 {
9714                    "github-text-rewrite".to_owned()
9715                } else {
9716                    format!("github-text-rewrite-{}", spec.id)
9717                },
9718                handover: None,
9719            };
9720            let ctx = WaveCtx {
9721                run: &run,
9722                node: "github-text",
9723                prompts: &prompts,
9724                cache: cache.as_deref(),
9725                round: None,
9726                carry_seats: false,
9727                pauses: Some((&self.pause, &self.interrupt)),
9728            };
9729            let (seat, outcome) =
9730                run_one(job, Arc::clone(&self.sem), &ctx, &mut self.state, 1).await;
9731            self.state.seats.insert(seat.key.clone(), seat);
9732            match outcome {
9733                AgentOutcome::Ok(o)
9734                    if !agent::output_advances(&o) && summary_title(&o.text).is_some() =>
9735                {
9736                    return Some(o.text);
9737                }
9738                AgentOutcome::ResourceBlocked(_) => return None,
9739                _ => {}
9740            }
9741        }
9742        None
9743    }
9744
9745    /// Abandon the standing posting-gate question, if any.
9746    fn retire_github_text_question(&mut self, why: &str) {
9747        let Some(id) = self
9748            .state
9749            .github_text
9750            .as_ref()
9751            .and_then(|g| g.question.clone())
9752        else {
9753            return;
9754        };
9755        let _ = ask::Questions::open().update(&id, |q| {
9756            q.abandon(why);
9757            Ok(())
9758        });
9759    }
9760
9761    /// Carry a withheld text to its end: file the question, park while it is
9762    /// open, and on an answer, silence or timeout pick the text to post. The
9763    /// decision is saved before it is used, so it applies once.
9764    async fn settle_withheld(
9765        &mut self,
9766        winner: &Candidate,
9767        pr: &PrMessage,
9768        mut g: crate::run::GithubTextAsk,
9769    ) -> Result<Option<PrMessage>> {
9770        use crate::github_text as gt;
9771        let store = ask::Questions::open();
9772        let timeout = self.state.config.graph.answer_timeout;
9773        if !g.resolved {
9774            let mut standing = g
9775                .question
9776                .as_ref()
9777                .and_then(|id| store.list_for_effects().into_iter().find(|q| &q.id == id));
9778            if let Some(q) = standing.as_ref()
9779                && q.status.open()
9780                && !store.held_reply(&q.id)
9781                && gt::expired(q, timeout)
9782            {
9783                let why = format!("no answer within {}s of asking", timeout.max(1));
9784                standing = store
9785                    .update(&q.id, |q| {
9786                        q.abandon(&why);
9787                        Ok(())
9788                    })
9789                    .ok()
9790                    .map(|(q, ())| q);
9791            }
9792            let mut ask_again: Option<Option<Vec<String>>> = None;
9793            match standing {
9794                // Recorded but never written (a stop between the two saves),
9795                // or removed: ask again without spending the retry.
9796                None if g.asks <= 1 => {
9797                    g.asks = 0;
9798                    ask_again = Some(None);
9799                }
9800                None => {
9801                    g.resolved = true;
9802                    g.chosen_title = None;
9803                    g.choice = Some(GithubTextChoice::Fallback);
9804                }
9805                Some(q) if q.status.open() => {
9806                    self.park_on_github_text(&g)?;
9807                    return Ok(None);
9808                }
9809                Some(q) => match gt::read_reply(&q) {
9810                    gt::Reply::Fallback => {
9811                        g.resolved = true;
9812                        g.chosen_title = None;
9813                        g.choice = Some(GithubTextChoice::Fallback);
9814                    }
9815                    gt::Reply::Original => {
9816                        g.resolved = true;
9817                        g.chosen_title = None;
9818                        g.choice = Some(GithubTextChoice::Original);
9819                    }
9820                    gt::Reply::Rewrite => {
9821                        g.resolved = true;
9822                        g.chosen_title = None;
9823                        g.choice = Some(if g.rewrite.is_some() {
9824                            GithubTextChoice::Rewrite
9825                        } else {
9826                            GithubTextChoice::Fallback
9827                        });
9828                    }
9829                    gt::Reply::Title(text) => {
9830                        let first = text
9831                            .lines()
9832                            .map(str::trim)
9833                            .find(|l| !l.is_empty())
9834                            .unwrap_or("");
9835                        let decision = if first.is_empty() {
9836                            None
9837                        } else {
9838                            let candidate = PrMessage {
9839                                title: first.to_owned(),
9840                                body: String::new(),
9841                            };
9842                            self.judge_pr_language(&winner.worktree, &candidate).await
9843                        };
9844                        match gt::vet_title(
9845                            &text,
9846                            decision,
9847                            self.state.config.graph.github_english(),
9848                        ) {
9849                            Ok(title) => {
9850                                g.resolved = true;
9851                                g.chosen_title = Some(title);
9852                                g.choice = Some(GithubTextChoice::MyTitle);
9853                            }
9854                            Err(cats) if g.asks < 2 => {
9855                                ask_again = Some(Some(
9856                                    cats.into_iter().map(str::to_owned).collect::<Vec<_>>(),
9857                                ))
9858                            }
9859                            Err(_) => {
9860                                g.resolved = true;
9861                                g.chosen_title = None;
9862                                g.choice = Some(GithubTextChoice::Fallback);
9863                            }
9864                        }
9865                    }
9866                },
9867            }
9868            if let Some(rejected) = ask_again {
9869                // A retry (after a rejected replacement title) is still about
9870                // the original text: the same ORIGINAL / FALLBACK comparison.
9871                let w = gt::Withheld {
9872                    title: g.title,
9873                    body: g.body,
9874                    categories: g.categories.clone(),
9875                };
9876                // Named by the original text's fingerprint alone, so a resume
9877                // rewrites the same file and the detail stays identical.
9878                let artifact = match crate::run::write_artifact(
9879                    &self.state,
9880                    &gt::artifact_name(&gt::fingerprint(&pr.title, &pr.body)),
9881                    &gt::artifact_text(&w, &pr.title, &pr.body, &self.state.id, g.rewrite.as_ref()),
9882                ) {
9883                    Ok(p) => Some(p),
9884                    Err(e) => {
9885                        tracing::warn!("could not write the withheld-text artifact: {e:#}");
9886                        None
9887                    }
9888                };
9889                let (detail, comparison) = gt::question_content(
9890                    &w,
9891                    &pr.title,
9892                    &pr.body,
9893                    &self.state.id,
9894                    rejected.as_deref(),
9895                    artifact.as_deref(),
9896                    g.rewrite.as_ref(),
9897                );
9898                let mut q = ask::Question::new(
9899                    self.state.id.clone(),
9900                    gt::ASK_NODE.to_owned(),
9901                    gt::ASK_SEAT.to_owned(),
9902                    gt::question_summary(&self.state.config.graph.language, &w),
9903                    detail,
9904                    gt::question_choices(&w, g.rewrite.as_ref()),
9905                );
9906                q.posting_comparison = Some(comparison);
9907                q.answer_timeout = timeout;
9908                // Recorded before it is written: a stop in between leaves a
9909                // record naming a question the resume then files again.
9910                g.question = Some(q.id.clone());
9911                g.asks += 1;
9912                self.state.github_text = Some(g.clone());
9913                self.state.event(
9914                    "github-text",
9915                    format!("asking the owner about the withheld text ({})", q.short()),
9916                );
9917                self.state.save()?;
9918                store
9919                    .put_executable(&mut q)
9920                    .context("file the posting-gate question")?;
9921                if let Err(e) = ask::notify(&self.state.config.notify, &q).await {
9922                    tracing::warn!(
9923                        "could not notify about posting-gate question {}: {e:#}",
9924                        q.short()
9925                    );
9926                }
9927                self.park_on_github_text(&g)?;
9928                return Ok(None);
9929            }
9930        }
9931        let resolved = g.chosen_title.clone();
9932        let original = g.choice == Some(GithubTextChoice::Original);
9933        // Field names only: the event log never records the text.
9934        self.state.event(
9935            "github-text",
9936            if original {
9937                format!(
9938                    "posting the original text for: {}",
9939                    match (g.title, g.body) {
9940                        (true, true) => "title, description",
9941                        (true, false) => "title",
9942                        _ => "description",
9943                    }
9944                )
9945            } else if g.choice == Some(GithubTextChoice::Rewrite) && g.rewrite.is_some() {
9946                "posting the saved rewrite title and description".to_owned()
9947            } else if resolved.is_some() {
9948                "posting the owner's replacement title".to_owned()
9949            } else {
9950                "posting the neutral text for the withheld fields".to_owned()
9951            },
9952        );
9953        self.state.github_text = Some(g.clone());
9954        self.state.save()?;
9955        if g.choice == Some(GithubTextChoice::Rewrite)
9956            && let Some(r) = g.rewrite.as_ref()
9957        {
9958            return Ok(Some(PrMessage {
9959                title: r.title.clone(),
9960                body: r.body.clone(),
9961            }));
9962        }
9963        let w = gt::Withheld {
9964            title: g.title,
9965            body: g.body,
9966            categories: g.categories.clone(),
9967        };
9968        let (mut title, body) = gt::fallback_text(&w, &pr.title, &pr.body, &self.state.id);
9969        if let Some(t) = resolved {
9970            title = t;
9971        }
9972        // Every withheld field is now neutral or vetted English.
9973        let english = gt::LanguageDecision {
9974            title_english: true,
9975            body_english: true,
9976            body_complete: true,
9977        };
9978        let (mut title, mut body) = gt::prepare_with(&mut self.state, &title, &body, Some(english));
9979        if original {
9980            // The owner's explicit choice overrides the gate for the fields it
9981            // was made for; the others keep what the gate produced.
9982            if g.title {
9983                title = pr.title.clone();
9984            }
9985            if g.body {
9986                body = pr.body.clone();
9987            }
9988        }
9989        Ok(Some(PrMessage { title, body }))
9990    }
9991
9992    fn park_on_github_text(&mut self, g: &crate::run::GithubTextAsk) -> Result<()> {
9993        self.state.github_text = Some(g.clone());
9994        self.state.end_pass_parked(ParkCause::Question);
9995        self.state.parked = true;
9996        self.state.event(
9997            "github-text",
9998            "parked awaiting the owner's word on the withheld pull request text - resumes once answered",
9999        );
10000        self.state.save()
10001    }
10002
10003    /// Ask `[roles] language_judge` about this text and record which source
10004    /// decided; the text itself is never recorded.
10005    async fn judge_pr_language(
10006        &mut self,
10007        cwd: &Path,
10008        pr: &PrMessage,
10009    ) -> Option<crate::github_text::LanguageDecision> {
10010        self.state.config.roles.language_judge.as_ref()?;
10011        if !self.state.config.graph.language_gate() {
10012            return None;
10013        }
10014        let decision =
10015            crate::github_text::judge_language(&self.state.config, cwd, &pr.title, &pr.body).await;
10016        self.state.event(
10017            "github-text",
10018            if decision.is_some() {
10019                "language decided by the language judge"
10020            } else {
10021                "language judge unavailable; using built-in heuristics"
10022            },
10023        );
10024        decision
10025    }
10026
10027    fn merge(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
10028        Box::pin(self.merge_inner())
10029    }
10030
10031    async fn merge_inner(&mut self) -> Result<()> {
10032        if self.resource_halt()? || self.hold_base_sync().await? {
10033            return Ok(());
10034        }
10035        // Same reasoning as `gate`: ask the review and gate records directly
10036        // rather than `status`, which a solo-candidate `judge`/`deliberate`
10037        // skip can rewrite on reentry to something that no longer says
10038        // `Blocked`. `review_conclusion` is the same derivation `gate` uses,
10039        // so a hand-off (open findings, green verification) reaches merge
10040        // exactly like a genuinely clean round does.
10041        //
10042        // A run resumed mid-`land` never reaches here at all: `execute`
10043        // recognises `RunStatus::Landing` before it even calls `prep`, and
10044        // routes straight to `run_land` instead. That has to happen a level
10045        // up from this function, not with a check in here, because
10046        // `review_loop`'s own status recomputation (see its doc) runs
10047        // *before* `merge` on every reentry and would otherwise overwrite
10048        // the `Landing` marker with `Gating` before this node ever saw it.
10049        if self
10050            .state
10051            .base_sync
10052            .as_ref()
10053            .is_some_and(|s| s.conflict.is_some())
10054            || review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
10055                != Some(RunStatus::Gating)
10056            // `gate_ran == false` is not "passed" - `gate` leaves it false
10057            // both before it has ever run and when its last attempt was
10058            // resource-blocked (see `Runner::gate`'s own doc), and neither is
10059            // permission to merge on nothing but the review record. Only a
10060            // gate that actually ran may proceed; an intentional local
10061            // review can also finish with verification explicitly not configured.
10062            // `RunState::gate_status` computes that distinction.
10063            || !self.state.gate_allows_progress()
10064        {
10065            return Ok(());
10066        }
10067        // This node's own record, not `status`: `status == Ready` is not
10068        // unique to the harmless `MergeMode::None` path this line was
10069        // written for. `land` (below) sets it too, when a `MergeMode::Pr`
10070        // run's PR was closed without merging — and on that run `mode` is
10071        // still `Pr`, so a reentry that fell through here would push and
10072        // open a second pull request. `self.state.merge` is set exactly once
10073        // this node (or `land`) has already produced a verdict, under every
10074        // mode, which is what "already done" actually means here.
10075        if self.state.merge.is_some() && !self.state.pr_publication_pending {
10076            return Ok(());
10077        }
10078        let Some(winner) = self.state.winner().cloned() else {
10079            return Ok(());
10080        };
10081        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
10082        if self.state.gate_head.as_deref() != Some(head.as_str()) {
10083            self.state.status = RunStatus::Blocked;
10084            self.state.event(
10085                "gate",
10086                "winner changed after gate; fresh verification required",
10087            );
10088            self.state.save()?;
10089            return Ok(());
10090        }
10091        let wait = self.repository_wait();
10092        if !verify_current_head(&mut self.state, &winner, &wait).await? {
10093            return Ok(());
10094        }
10095        let repo = self.state.repo.clone();
10096        let base = self.state.base_branch.clone();
10097        let mode = self.state.config.merge.mode;
10098        let style = self.state.config.merge.style;
10099        let facts = if is_review_run(&self.state) {
10100            refresh_reviewed_commits(&mut self.state, &winner.branch).await;
10101            let start = review_base(
10102                &repo,
10103                &self.state.config.merge.remote,
10104                &base,
10105                &self.state.base_commit,
10106                &winner.branch,
10107            )
10108            .await;
10109            branch_facts(&repo, &start, &winner.branch).await
10110        } else {
10111            None
10112        };
10113        // `None` when the base could not be freshly read: then an adopted
10114        // pull request's title is left alone.
10115        let leaked = if is_review_run(&self.state) {
10116            leaked_subjects(&self.state, &winner.branch).await
10117        } else {
10118            Some(Vec::new())
10119        };
10120        // `None`: parked on the owner's word about a withheld title or body.
10121        // Nothing has been pushed or opened, and `merge` stays unrecorded so
10122        // the resume arrives here again.
10123        let Some(pr) = self
10124            .guarded_pr_message(&winner, facts.as_ref(), mode == MergeMode::Pr)
10125            .await?
10126        else {
10127            return Ok(());
10128        };
10129        let message = pr.commit_message();
10130
10131        let delivery_head = git::rev_parse(&winner.worktree, "HEAD").await?;
10132        if !crate::foreign_checkout::write_back(&mut self.state, &delivery_head).await? {
10133            return Ok(());
10134        }
10135        let outcome = match mode {
10136            MergeMode::None => MergeOutcome {
10137                mode,
10138                ok: true,
10139                detail: manual_merge_command(style, &repo, &winner.branch, &message),
10140                empty: false,
10141            },
10142            MergeMode::Pr | MergeMode::Local
10143                if merge_is_empty(&repo, &self.state, &winner.branch, mode).await =>
10144            {
10145                MergeOutcome {
10146                    mode,
10147                    ok: false,
10148                    detail: empty_candidate_detail(&self.state, &base),
10149                    empty: true,
10150                }
10151            }
10152            MergeMode::Local => {
10153                let on = git::current_branch(&repo).await?;
10154                if on.as_deref() != Some(base.as_str()) {
10155                    MergeOutcome {
10156                        mode,
10157                        ok: false,
10158                        detail: format!(
10159                            "{} has {} checked out, not the base branch {base}",
10160                            repo.display(),
10161                            on.unwrap_or_else(|| "a detached HEAD".to_owned())
10162                        ),
10163                        empty: false,
10164                    }
10165                } else if !git::is_clean(&repo).await? {
10166                    MergeOutcome {
10167                        mode,
10168                        ok: false,
10169                        detail: format!("{} is dirty; refusing to merge", repo.display()),
10170                        empty: false,
10171                    }
10172                } else {
10173                    let out = match style {
10174                        MergeStyle::Merge => {
10175                            git::merge_no_ff(&repo, &winner.branch, &message).await?
10176                        }
10177                        MergeStyle::Squash => {
10178                            git::merge_squash(&repo, &winner.branch, &message).await?
10179                        }
10180                        MergeStyle::Rebase => git::merge_ff_only(&repo, &winner.branch).await?,
10181                    };
10182                    MergeOutcome {
10183                        mode,
10184                        ok: out.ok(),
10185                        detail: if out.ok() { out.stdout } else { out.stderr },
10186                        empty: false,
10187                    }
10188                }
10189            }
10190            MergeMode::Pr if self.state.task_pr_branch().is_some() => {
10191                self.state.pr_publication_pending = true;
10192                self.state.save()?;
10193                let out =
10194                    crate::pr_head::publish(&mut self.state, &winner, &pr.title, &pr.body).await;
10195                self.state.pr_publication_pending = out.is_err();
10196                MergeOutcome {
10197                    mode,
10198                    ok: out.is_ok(),
10199                    detail: match out {
10200                        Ok(url) => url,
10201                        Err(e) => format!("{e:#}"),
10202                    },
10203                    empty: false,
10204                }
10205            }
10206            MergeMode::Pr => {
10207                let remote = self.state.config.merge.remote.clone();
10208                let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
10209                let pushed = if self.state.foreign_checkout.is_some() {
10210                    let refspec = format!("{delivery_head}:refs/heads/{public}");
10211                    git::git_raw(&winner.worktree, &["push", &remote, &refspec]).await?
10212                } else {
10213                    git::push(&winner.worktree, &remote, &winner.branch).await?
10214                };
10215                if !pushed.ok() {
10216                    MergeOutcome {
10217                        mode,
10218                        ok: false,
10219                        detail: pushed.stderr,
10220                        empty: false,
10221                    }
10222                } else {
10223                    if self.state.foreign_checkout.is_some() {
10224                        self.state.pr_pushed_head = Some(delivery_head.clone());
10225                    }
10226                    // A retry or resume of a run whose branch already has an
10227                    // open pull request adopts it rather than failing on a
10228                    // duplicate. Only this winner branch into this base:
10229                    // `branch_for` derives the name from the run id, so a
10230                    // different run's pull request never matches.
10231                    let found = land::find_open_pr(&winner.worktree, &public, &base).await;
10232                    let out = match pr_merge_plan(found) {
10233                        PrPlan::Create => {
10234                            gh_pr_create(&winner.worktree, &base, &public, &pr.title, &pr.body)
10235                                .await
10236                        }
10237                        PrPlan::Adopt { url, title } => {
10238                            self.state
10239                                .event("merge", format!("Pr: adopted open pull request {url}"));
10240                            if self.state.explicit_github_text_selection() {
10241                                // An explicit publication selection applies the prepared
10242                                // payload; acceptance alone is not publication proof.
10243                                land::set_pr_text_verbatim(
10244                                    &winner.worktree,
10245                                    &url,
10246                                    &pr.title,
10247                                    &pr.body,
10248                                )
10249                                .await
10250                                .map(|()| url)
10251                            } else {
10252                                if title != pr.title
10253                                    && (!is_review_run(&self.state)
10254                                        || leaked
10255                                            .as_deref()
10256                                            .is_some_and(|l| should_retitle(&title, &pr.title, l)))
10257                                    && let Err(e) =
10258                                        if self.state.github_text.as_ref().is_some_and(|g| {
10259                                            g.resolved
10260                                                && g.title
10261                                                && g.choice == Some(GithubTextChoice::Original)
10262                                        }) {
10263                                            // The owner chose to post this title unmodified.
10264                                            land::set_pr_title_verbatim(
10265                                                &winner.worktree,
10266                                                &url,
10267                                                &pr.title,
10268                                            )
10269                                            .await
10270                                        } else {
10271                                            land::set_pr_title(
10272                                                &mut self.state,
10273                                                &winner.worktree,
10274                                                &url,
10275                                                &pr.title,
10276                                            )
10277                                            .await
10278                                        }
10279                                {
10280                                    tracing::warn!("could not refresh title of {url}: {e:#}");
10281                                    self.state
10282                                        .event("merge", format!("Pr: title refresh failed: {e:#}"));
10283                                }
10284                                Ok(url)
10285                            }
10286                        }
10287                        PrPlan::Stop(why) => Err(anyhow::anyhow!(why)),
10288                    };
10289                    match out {
10290                        Ok(url) => MergeOutcome {
10291                            mode,
10292                            ok: true,
10293                            detail: url,
10294                            empty: false,
10295                        },
10296                        Err(e) => MergeOutcome {
10297                            mode,
10298                            ok: false,
10299                            detail: e.to_string(),
10300                            empty: false,
10301                        },
10302                    }
10303                }
10304            }
10305        };
10306
10307        self.state.status = match (mode, outcome.ok) {
10308            (MergeMode::None, _) => RunStatus::Ready,
10309            (_, true) if outcome.empty => RunStatus::Ready,
10310            (MergeMode::Pr, true) => RunStatus::Ready,
10311            (_, true) => RunStatus::Merged,
10312            (_, false) => RunStatus::Blocked,
10313        };
10314        self.state.event(
10315            "merge",
10316            format!(
10317                "{:?}: {}",
10318                mode,
10319                outcome.detail.lines().next().unwrap_or("")
10320            ),
10321        );
10322        if mode == MergeMode::Pr && outcome.ok && !outcome.empty {
10323            self.state.record_github_text_publication(&outcome.detail);
10324        }
10325        self.state.merge = Some(outcome);
10326        self.state.save()?;
10327
10328        // The PR is open and the run would historically stop here, leaving the
10329        // operator to watch checks, feed review comments back to a fixer, and
10330        // merge. That was done by hand six times in one session before this
10331        // existed. Opt-in, because merging is the one irreversible thing magi
10332        // can do to a repository.
10333        if self.state.config.graph.land
10334            && mode == MergeMode::Pr
10335            && self.state.merge.as_ref().is_some_and(|m| m.ok && !m.empty)
10336        {
10337            self.run_land().await?;
10338        }
10339        // `run_land` may have left `status` at `Landing` - still waiting on
10340        // CI or the owner's approval, not actually settled - so this has to
10341        // read whatever `status` ended up as here, not the `Merged` this
10342        // function set a few lines up.
10343        self.settle_questions();
10344        Ok(())
10345    }
10346
10347    /// Enter `land`.
10348    ///
10349    /// Shared between a fresh run's first pass through [`Runner::merge`] and
10350    /// a resumed run's re-entry. `land::land` itself is what serialises the
10351    /// two git-mutating moments inside the loop — the rebase push and
10352    /// `gh pr merge` — per repository (see its own doc); nothing here needs
10353    /// to hold a lock across the whole call, and doing so would serialise
10354    /// this run's CI wait against a *different* run's land-approval resume
10355    /// in the same repository, which is exactly the "must not wait on
10356    /// another task" property the daemon's slot-freeing exists to give.
10357    fn run_land(&mut self) -> impl std::future::Future<Output = Result<()>> + '_ {
10358        Box::pin(self.run_land_inner())
10359    }
10360
10361    async fn run_land_inner(&mut self) -> Result<()> {
10362        crate::pr_head::ensure_owner(&self.state)?;
10363        let url = self
10364            .state
10365            .pr
10366            .as_ref()
10367            .map(|pr| pr.url.clone())
10368            .or_else(|| self.state.merge.as_ref().map(|m| m.detail.clone()))
10369            .unwrap_or_default();
10370        let url = url.lines().next().unwrap_or("").trim().to_owned();
10371        if !url.starts_with("http") {
10372            return Ok(());
10373        }
10374        // A land failure is not a lost run: the work is on a branch and the
10375        // pull request is open, which is exactly where a human takes over.
10376        loop {
10377            match land::land(&mut self.state, &url).await {
10378                Ok(_)
10379                    if self
10380                        .state
10381                        .merge_repairs
10382                        .last()
10383                        .is_some_and(|r| r.phase == crate::run::MergeRepairPhase::Requested) =>
10384                {
10385                    if self.repair_merge_review().await? {
10386                        continue;
10387                    }
10388                }
10389                Ok(_) if self.state.resource_block.is_some() => {
10390                    return self.stop_for_resource();
10391                }
10392                Ok(pr) if self.state.parked => {
10393                    // `land` already saved the parked marker; nothing here
10394                    // overrides `status` back to a terminal value while an
10395                    // approval is still outstanding.
10396                    let _ = pr;
10397                }
10398                Ok(_) if self.state.merge_decision.as_ref().is_some_and(|d| d.closed) => {
10399                    self.state.status = RunStatus::Superseded;
10400                    self.state.save()?;
10401                }
10402                Ok(pr) => {
10403                    self.state.status = match pr.state {
10404                        land::PrLifecycle::Merged => RunStatus::Merged,
10405                        _ => RunStatus::Blocked,
10406                    };
10407                    // Downstream of a confirmed merge only - see
10408                    // `bump::should_release_bump`'s own doc for why this one
10409                    // check covers all three of `land`'s success paths.
10410                    // Best-effort: the run already landed, so a failure here
10411                    // (the decision call, `gh`, `cargo`) is recorded and never
10412                    // turns a landed run into a failed one.
10413                    if bump::should_release_bump(self.state.status)
10414                        && let Err(e) = bump::after_merge(&mut self.state, &pr.url).await
10415                    {
10416                        // The event is the run's own record. Not-eligible cases
10417                        // (disabled, no `Cargo.toml`, ...) return `Ok`, so an
10418                        // `Err` is a bump that was tried and failed:
10419                        // `after_merge` itself raises the operator notice for
10420                        // that, whether or not a release PR exists yet.
10421                        self.state
10422                            .event("bump", format!("release bump skipped: {e:#}"));
10423                    }
10424                    // Independent of the bump, and best-effort in the same way:
10425                    // findings the merge left open become follow-up tasks.
10426                    if self.state.status == RunStatus::Merged {
10427                        crate::followup::after_merge(&mut self.state, &pr.url).await;
10428                    }
10429                    self.state.save()?;
10430                }
10431                Err(e) => {
10432                    if e.is::<crate::repo_lock::ResourceBlocked>() {
10433                        return Err(e);
10434                    }
10435                    self.state.status = RunStatus::Blocked;
10436                    self.state.event("land", format!("gave up: {e}"));
10437                    self.state.save()?;
10438                }
10439            }
10440            break;
10441        }
10442        Ok(())
10443    }
10444
10445    /// One repair cycle stays under the existing driver/task claim. An
10446    /// interrupted fixer is rolled back and held rather than run twice.
10447    async fn repair_merge_review(&mut self) -> Result<bool> {
10448        use crate::run::MergeRepairPhase as Phase;
10449        crate::pr_head::ensure_owner(&self.state)?;
10450        let i = self.state.merge_repairs.len() - 1;
10451        let request = self.state.merge_repairs[i].clone();
10452        if request.phase == Phase::Fixing {
10453            let restored = match self.state.winner().cloned() {
10454                Some(winner) => self.graft_restore(&winner.worktree, &request.head).await,
10455                None => Err(anyhow::anyhow!("repair has no winning branch")),
10456            };
10457            let why = match restored {
10458                Ok(()) => "repair was interrupted during the fixer and rolled back; inspect its artifacts and the PR head, then run an explicit review".to_owned(),
10459                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => return Err(e),
10460                Err(e) => format!("repair was interrupted; rollback failed: {e:#}; restore the reviewed branch before running an explicit review"),
10461            };
10462            self.hold_merge_repair(i, why)?;
10463            return Ok(false);
10464        }
10465        // A completed repair gate is a publication checkpoint. On reentry,
10466        // reject external changes before the ordinary gate path can replace
10467        // that evidence by verifying a new head. Requested repairs still
10468        // start their own review generation below.
10469        if request.phase == Phase::Reviewing && self.state.gate_ran {
10470            let winner = self
10471                .state
10472                .winner()
10473                .context("repair has no winning branch")?;
10474            let head = git::rev_parse(&winner.worktree, "HEAD").await?;
10475            if self.state.gate_head.as_deref() != Some(head.as_str())
10476                || !git::is_clean(&winner.worktree).await?
10477            {
10478                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())?;
10479                return Ok(false);
10480            }
10481        }
10482        let failure = if i >= self.state.config.graph.land_rounds
10483            || self.state.config.graph.review_rounds == 0
10484        {
10485            Some("repair generation budget exhausted or review disabled; increase the configured budget and request a new review explicitly".to_owned())
10486        } else {
10487            None
10488        };
10489        if let Some(why) = failure {
10490            self.hold_merge_repair(i, why)?;
10491            return Ok(false);
10492        }
10493        if request.phase == Phase::Requested {
10494            let pr = match land::repair_preflight(&self.state, &request.pr, &request.head).await {
10495                Ok(pr) => pr,
10496                Err(e) => {
10497                    self.hold_merge_repair(i, format!("cannot resume repair: {e:#}; restore the reviewed PR branch and run an explicit review"))?;
10498                    return Ok(false);
10499                }
10500            };
10501            self.state.merge_repairs[i].phase = Phase::Fixing;
10502            self.state.land_approval = None;
10503            self.state.land_armed_head = None;
10504            self.state.save()?;
10505            // Serialize the exact records, including finding ids/details,
10506            // reconsideration reasons, final votes and verification output.
10507            let evidence = serde_json::to_string_pretty(&request)?;
10508            let reason = format!(
10509                "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}"
10510            );
10511            let budget = self.state.config.graph.land_rounds;
10512            let result = land::fix_round(&mut self.state, &pr, i + 1, budget, &reason, "").await;
10513            match result {
10514                Ok(land::Fixed::Committed { .. } | land::Fixed::Declined) => {}
10515                Ok(land::Fixed::Deferred) => {
10516                    // An unavailable fixer did not spend this repair request.
10517                    // Restore partial fallback work before retrying it, as for
10518                    // an interrupted repair, without closing the request.
10519                    let worktree = self
10520                        .state
10521                        .winner()
10522                        .context("repair has no winning branch")?
10523                        .worktree
10524                        .clone();
10525                    self.graft_restore(&worktree, &request.head).await?;
10526                    self.state.merge_repairs[i].phase = Phase::Requested;
10527                    self.stop_for_resource()?;
10528                    return Ok(false);
10529                }
10530                Ok(land::Fixed::Failed(why)) => {
10531                    self.hold_merge_repair(
10532                        i,
10533                        format!(
10534                            "repair failed: {why}; inspect the branch and run an explicit review"
10535                        ),
10536                    )?;
10537                    return Ok(false);
10538                }
10539                Err(e) => {
10540                    self.hold_merge_repair(
10541                        i,
10542                        format!(
10543                            "repair failed: {e:#}; inspect the branch and run an explicit review"
10544                        ),
10545                    )?;
10546                    return Ok(false);
10547                }
10548            }
10549            // Even no change gets a real new reviewer wave. The previous
10550            // evidence remains in the request; a former clean/concluded round
10551            // cannot short-circuit the new review or gate.
10552            self.begin_merge_repair_review(i)?;
10553        }
10554        self.review_loop().await?;
10555        self.gate().await?;
10556        if self.resource_halt()? || self.state.parked {
10557            return Ok(false);
10558        }
10559        if review_conclusion(&self.state.reviews, self.state.config.graph.review_rounds)
10560            != Some(RunStatus::Gating)
10561            || !self.state.gate_allows_progress()
10562        {
10563            self.hold_merge_repair(i, "updated review or gate did not pass; inspect the new results and resume review explicitly".to_owned())?;
10564            return Ok(false);
10565        }
10566        // Review and gate may have added commits after the initial repair.
10567        // Publish exactly their final head to the existing PR, with a lease.
10568        let winner = self
10569            .state
10570            .winner()
10571            .cloned()
10572            .context("repair has no winning branch")?;
10573        let after = git::rev_parse(&winner.worktree, "HEAD").await?;
10574        if self.state.gate_head.as_deref() != Some(after.as_str())
10575            || !git::is_clean(&winner.worktree).await?
10576        {
10577            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())?;
10578            return Ok(false);
10579        }
10580        let expected = self
10581            .state
10582            .pr_pushed_head
10583            .as_deref()
10584            .unwrap_or(&request.head)
10585            .to_owned();
10586        let public = self.state.pr_branch().unwrap_or(&winner.branch).to_owned();
10587        // Push the checked commit itself: a local ref moving after the check
10588        // must not change which commit the forge receives.
10589        if !crate::foreign_checkout::write_back(&mut self.state, &after).await? {
10590            return Ok(false);
10591        }
10592        let lease = format!("--force-with-lease=refs/heads/{public}:{expected}");
10593        let refspec = format!("{after}:refs/heads/{public}");
10594        let push = git::git_raw(
10595            &winner.worktree,
10596            &["push", &lease, &self.state.config.merge.remote, &refspec],
10597        )
10598        .await;
10599        match push {
10600            Ok(out) if out.ok() => self.state.pr_pushed_head = Some(after),
10601            Ok(out) => {
10602                self.hold_merge_repair(i, format!("publishing reviewed repair failed: {}; inspect the PR head and resume review explicitly", out.stderr))?;
10603                return Ok(false);
10604            }
10605            Err(e) => {
10606                self.hold_merge_repair(i, format!("publishing reviewed repair failed: {e:#}; inspect the PR head and resume review explicitly"))?;
10607                return Ok(false);
10608            }
10609        }
10610        self.state.merge_repairs[i].phase = Phase::Complete;
10611        self.state.status = RunStatus::Landing;
10612        self.state.event(
10613            "repair",
10614            "new review and gate completed; fresh owner merge decision required",
10615        );
10616        self.state.save()?;
10617        Ok(true)
10618    }
10619
10620    fn merge_repair_artifacts(&self) -> PathBuf {
10621        let artifacts = agent::artifacts_dir(&self.state.dir());
10622        match self
10623            .state
10624            .merge_repairs
10625            .last()
10626            .filter(|r| r.phase == crate::run::MergeRepairPhase::Reviewing)
10627        {
10628            Some(r) => artifacts.join(format!("merge-repair-{}", r.question)),
10629            None => artifacts,
10630        }
10631    }
10632
10633    fn begin_merge_repair_review(&mut self, index: usize) -> Result<()> {
10634        if let Some(e2e) = self.state.head_e2e.take() {
10635            self.state
10636                .verification_history
10637                .push(crate::run::VerificationEvidence {
10638                    superseded_by: None,
10639                    archived_at: Some(Timestamp::now()),
10640                    fixes_spent: Some(self.state.gate_fixes.len()),
10641                    gate_head: None,
10642                    gate_ran: false,
10643                    gate: Vec::new(),
10644                    e2e: Some(e2e),
10645                });
10646        }
10647        self.state.reviews.clear();
10648        self.state.gate.clear();
10649        self.state.gate_ran = false;
10650        self.state.gate_head = None;
10651        self.state.gate_fixes.clear();
10652        self.state.gate_repair_e2e = None;
10653        self.state.pre_gate.clear();
10654        self.state.pre_gate_commit = None;
10655        self.state.contested_handoff = None;
10656        self.state.land_reruns = None;
10657        self.state.land_approval = None;
10658        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Reviewing;
10659        self.state.status = RunStatus::Reviewing;
10660        self.state.save()
10661    }
10662
10663    fn hold_merge_repair(&mut self, index: usize, why: String) -> Result<()> {
10664        self.state.merge_repairs[index].phase = crate::run::MergeRepairPhase::Failed;
10665        self.state.merge_repairs[index].failure = Some(why.clone());
10666        self.state.status = RunStatus::Blocked;
10667        self.state.event("repair", why);
10668        self.state.save()
10669    }
10670
10671    // -------------------------------------------------------------- helpers
10672
10673    /// Fetch or create a seat, keeping its conversation across nodes.
10674    fn seat(&mut self, key: &str, agent: &str) -> SeatState {
10675        if let Some(existing) = self.state.seats.get(key)
10676            && existing.agent == agent
10677        {
10678            return existing.clone();
10679        }
10680        // A seat that changes agent mints its session id from the agent too,
10681        // like a handover: the old agent's uuid is already taken by the CLI.
10682        let fresh = if self.state.seats.contains_key(key) {
10683            handover_seat(key, agent, self.state.next_seat_seed())
10684        } else {
10685            SeatState::new(key, agent, self.state.seed)
10686        };
10687        self.state.seats.insert(key.to_owned(), fresh.clone());
10688        fresh
10689    }
10690
10691    /// The agent now holding seat `key`: `spec`, unless a handover moved the
10692    /// seat to another roster agent, in which case that agent. Nodes that
10693    /// continue a seat's conversation (deliberation, the votes, a reviewer's
10694    /// reconsideration) must keep talking to whoever answered it, not slip
10695    /// back to the agent that failed it.
10696    fn occupant(&self, key: &str, spec: AgentSpec) -> AgentSpec {
10697        match self.state.seats.get(key) {
10698            Some(s) if s.agent != spec.id => {
10699                self.state.config.agent(&s.agent).cloned().unwrap_or(spec)
10700            }
10701            _ => spec,
10702        }
10703    }
10704
10705    /// A candidate rendered for judging, with the leak policy applied.
10706    fn view(&self, c: &Candidate) -> CandidateView {
10707        let raw = crate::run::read_artifact(&self.state, &format!("cand-{}.patch", c.label))
10708            .unwrap_or_default();
10709        let (patch, _) = blind::sanitize_patch(
10710            &format!("candidate {} patch", c.label),
10711            &raw,
10712            &self.state.config.blind,
10713        );
10714        CandidateView {
10715            label: c.label,
10716            branch: c.branch.clone(),
10717            summary: c.summary.clone(),
10718            stat: c.stat.clone(),
10719            patch,
10720        }
10721    }
10722
10723    /// The full candidate set as prompt text, for seats with no live session.
10724    fn candidate_block(&self, candidates: &[Candidate], base_short: &str) -> String {
10725        let views: Vec<CandidateView> = candidates.iter().map(|c| self.view(c)).collect();
10726        prompt::judge(
10727            "(see above)",
10728            &views,
10729            self.roles.judges.len(),
10730            base_short,
10731            "en",
10732        )
10733    }
10734
10735    /// The final-vote prompt with everything a seat that has no session of its
10736    /// own needs: the candidates, the seat's own ranking and reasons, and the
10737    /// anonymised deliberation it took part in (only when there was one, so a
10738    /// handed-over seat never sees more than the seat it replaces did). The
10739    /// `Final vote` heading stays first.
10740    fn vote_prompt_full(
10741        &self,
10742        j: usize,
10743        labels: &[char],
10744        language: &str,
10745        candidates: &[Candidate],
10746        base_short: &str,
10747    ) -> String {
10748        let mut text = format!(
10749            "{}\n\n# The task the candidates were given\n\n{}\n\n# Candidates\n\n{}",
10750            prompt::final_vote(labels, language),
10751            self.state.instruction,
10752            self.candidate_block(candidates, base_short)
10753        );
10754        if let Some(own) = self
10755            .state
10756            .judgements
10757            .get(j)
10758            .filter(|r| !r.ranking.is_empty())
10759        {
10760            let reasons = own
10761                .reasons
10762                .iter()
10763                .map(|(k, v)| format!("- {k}: {v}"))
10764                .collect::<Vec<_>>()
10765                .join("\n");
10766            text.push_str(&format!(
10767                "\n\n# Your own earlier ranking\n\nYou ranked {}{}{reasons}\n",
10768                own.ranking.iter().collect::<String>(),
10769                if reasons.is_empty() {
10770                    ""
10771                } else {
10772                    ", because:\n"
10773                }
10774            ));
10775        }
10776        if !self.state.deliberation.is_empty() {
10777            text.push_str("\n# What was argued before this vote\n");
10778            for t in self.transcript(&[], j) {
10779                text.push_str(&format!(
10780                    "\n## {}{}\n\n{}\n",
10781                    t.who,
10782                    if t.is_self { " (you)" } else { "" },
10783                    t.body.trim()
10784                ));
10785            }
10786        }
10787        text
10788    }
10789
10790    /// Anonymised transcript for judge `self_idx`.
10791    ///
10792    /// The initial rankings are always the opening statements. Seeding them
10793    /// only when no turn had been taken yet meant every judge after the first
10794    /// argued against a single voice instead of against the actual split — the
10795    /// disagreement is the information, so it is always on the table.
10796    fn transcript(&self, current: &[DeliberationTurn], self_idx: usize) -> Vec<Turn> {
10797        let mut turns = Vec::new();
10798        for j in &self.state.judgements {
10799            if j.ranking.is_empty() {
10800                continue;
10801            }
10802            let reasons = j
10803                .reasons
10804                .iter()
10805                .map(|(k, v)| format!("- {k}: {v}"))
10806                .collect::<Vec<_>>()
10807                .join("\n");
10808            turns.push(Turn {
10809                who: format!("Judge {} (opening ranking)", j.judge),
10810                is_self: j.judge == self_idx + 1,
10811                body: format!(
10812                    "Ranked {}{}{reasons}",
10813                    j.ranking.iter().collect::<String>(),
10814                    if reasons.is_empty() {
10815                        ""
10816                    } else {
10817                        ", because:\n"
10818                    }
10819                ),
10820            });
10821        }
10822        for t in self
10823            .state
10824            .deliberation
10825            .iter()
10826            .flat_map(|r| r.turns.iter())
10827            .chain(current)
10828        {
10829            turns.push(Turn {
10830                who: format!("Judge {}", t.judge),
10831                is_self: t.judge == self_idx + 1,
10832                body: t.body.clone(),
10833            });
10834        }
10835        turns
10836    }
10837}
10838
10839/// Does this seat still hold the context a follow-up prompt would rely on?
10840fn has_context(spec: &AgentSpec, seat: &SeatState, sessions: bool) -> bool {
10841    agent::has_session(spec.kind, seat, sessions)
10842}
10843
10844/// The next entry in `roster` after `start`, never wrapping back to the
10845/// front, whose id is not in `tried` yet.
10846///
10847/// Starts one past `start` rather than at the front of `roster`: `start` is
10848/// the seat's own original position, and a seat whose candidate slot already
10849/// sits on the roster's second entry must fall through to the third next, not
10850/// restart at the first — which is very likely a different candidate's own
10851/// agent already. Never wraps back past `start`, for the same reason: an
10852/// entry earlier in the roster than the seat's own position is almost
10853/// certainly some *other* candidate slot's own agent, and once the tail of
10854/// the roster is exhausted there are no more untried agents for *this* seat
10855/// to fall through to — the caller's fallback chain ends there, exactly as
10856/// "no further untried agents remain in the list for that seat" asks for.
10857///
10858/// Matched by [`AgentSpec::id`], never the whole spec: a roster that names
10859/// the same id twice (an operator's `roles.implementers` typo, or a
10860/// `[[agents]]` list reused across roles) must not let
10861/// [`Runner::resume_seat_handovers`] retry that id forever — one forward pass
10862/// over `roster` either finds an untried id or runs out, so this always
10863/// terminates regardless of duplicates.
10864fn next_untried_in_roster<'a>(
10865    roster: &'a [AgentSpec],
10866    start: usize,
10867    tried: &BTreeSet<String>,
10868) -> Option<&'a AgentSpec> {
10869    roster
10870        .get(start + 1..)?
10871        .iter()
10872        .find(|s| !tried.contains(&s.id))
10873}
10874
10875/// The successor for a seat, shared by all four seat kinds (implement, judge,
10876/// review, advise). `others` holds the ids that *currently* occupy the other
10877/// seats of the same wave (after any earlier handover, as [`Runner::occupant`]
10878/// sees them), so roster entries beyond the seat count act as spares: a failed
10879/// seat goes to an agent no other seat holds whenever the roster permits.
10880///
10881/// `carried` is `Some` only for the review loop's carried failure history.
10882/// Order: (1) forward from `start`, never wrapping, untried, not a carried
10883/// failure, not another seat's occupant; (2) with `carried`, a rescue over the
10884/// whole roster: untried and not another seat's occupant; (3) the plain walk
10885/// ([`next_untried_in_roster`] / [`next_for_seat`]) that ignores `others`.
10886/// Step 3 is deliberate: a duplicate agent on two seats is a worse panel but
10887/// a better outcome than an empty seat, and it keeps the answer to "is there
10888/// a successor at all" exactly what it was before occupants were considered,
10889/// so no handover rule (`should_hand_over`, nudges, the tried-once bound)
10890/// moves. The rescue excludes occupants too, on the same reasoning: retrying a
10891/// carried failure is a cheaper bet than doubling an agent on the panel, and
10892/// if it fails again `tried` bounds it and step 3 takes over. Seats failing in
10893/// the same round are handled one at a time, so a seat later in the batch
10894/// sees an earlier one's new occupant but not yet its own freed agent.
10895fn pick_successor<'a>(
10896    roster: &'a [AgentSpec],
10897    start: usize,
10898    tried: &BTreeSet<String>,
10899    carried: Option<&BTreeSet<String>>,
10900    others: &BTreeSet<String>,
10901) -> Option<&'a AgentSpec> {
10902    let free = |s: &&AgentSpec| !tried.contains(&s.id) && !others.contains(&s.id);
10903    roster
10904        .get(start + 1..)
10905        .and_then(|tail| {
10906            tail.iter()
10907                .filter(free)
10908                .find(|s| carried.is_none_or(|c| !c.contains(&s.id)))
10909        })
10910        .or_else(|| {
10911            carried
10912                .is_some()
10913                .then(|| roster.iter().find(free))
10914                .flatten()
10915        })
10916        .or_else(|| match carried {
10917            Some(c) => next_for_seat(roster, start, tried, c),
10918            None => next_untried_in_roster(roster, start, tried),
10919        })
10920}
10921
10922/// The next agent for a seat that carries its failure history across rounds
10923/// (the review loop). `round_tried` is this round's own bound and starts
10924/// empty every round; `carried_failed` only decides priority.
10925///
10926/// First: an id walking forward from `start`, never wrapping, that is neither
10927/// tried this round nor failed in an earlier one. Only when that is exhausted
10928/// does it rescue: the first roster id (in roster order, so this one *does*
10929/// look before `start`) not yet tried this round, which is by then a carried
10930/// failure. Each id is rescued at most once per round, so it cannot loop.
10931fn next_for_seat<'a>(
10932    roster: &'a [AgentSpec],
10933    start: usize,
10934    round_tried: &BTreeSet<String>,
10935    carried_failed: &BTreeSet<String>,
10936) -> Option<&'a AgentSpec> {
10937    roster
10938        .get(start + 1..)?
10939        .iter()
10940        .find(|s| !round_tried.contains(&s.id) && !carried_failed.contains(&s.id))
10941        .or_else(|| roster.iter().find(|s| !round_tried.contains(&s.id)))
10942}
10943
10944/// Where a reviewer seat starts a round: the agent that last answered it when
10945/// it is still on the roster and not marked failed, else the spec's own agent
10946/// unless it failed, else the next roster agent that has not failed, else the
10947/// spec's own agent again (the whole roster failed). Ids no longer on the
10948/// roster are ignored. An empty roster has no handover, so the spec stands.
10949fn pick_start_spec(roster: &[AgentSpec], spec: AgentSpec, hist: Option<&SeatHistory>) -> AgentSpec {
10950    let Some(h) = hist.filter(|_| !roster.is_empty()) else {
10951        return spec;
10952    };
10953    let ok = |id: &str| !h.failed.contains(id);
10954    if let Some(last) = h.last_ok.as_deref()
10955        && ok(last)
10956        && let Some(s) = roster.iter().find(|s| s.id == last)
10957    {
10958        return s.clone();
10959    }
10960    if ok(&spec.id) {
10961        return spec;
10962    }
10963    let from = roster.iter().position(|s| s.id == spec.id).unwrap_or(0);
10964    roster
10965        .get(from + 1..)
10966        .into_iter()
10967        .flatten()
10968        .chain(roster.iter())
10969        .find(|s| ok(&s.id))
10970        .cloned()
10971        .unwrap_or(spec)
10972}
10973
10974/// A fresh seat for the agent taking over `key`. Mixes the agent id into the
10975/// seed so a CLI that mints its session id up front (`--session-id`) never
10976/// reuses the uuid the previous agent already opened under the same seat key.
10977pub(crate) fn handover_seat(key: &str, agent: &str, run_seed: u64) -> SeatState {
10978    SeatState::new(key, agent, run_seed ^ crate::rng::fnv1a(agent))
10979}
10980
10981/// What an agent's turn timed out as, in [`AgentOutcome::Failed`]. One const
10982/// so the classifier below and the code that builds the message cannot drift.
10983const TIMED_OUT: &str = "timed out";
10984
10985impl FailClass {
10986    /// `None` for an answer; otherwise how the turn failed.
10987    fn of(out: &AgentOutcome) -> Option<Self> {
10988        match out {
10989            AgentOutcome::Ok(_) => None,
10990            AgentOutcome::Quota(_) => Some(Self::Quota),
10991            AgentOutcome::Dropped(_) => Some(Self::Other("dropped".to_owned())),
10992            AgentOutcome::Failed(e) if e == TIMED_OUT => Some(Self::Timeout),
10993            AgentOutcome::Failed(e) => Some(Self::Other(failure_signature(e))),
10994            // Not a failure of the agent. Callers check for it first; `None`
10995            // here means "no class to hand over on".
10996            AgentOutcome::ResourceBlocked(_) => None,
10997        }
10998    }
10999
11000    /// The word in a handover's artifact stem (`impl-A-quota-beta`).
11001    fn stem_word(&self) -> &'static str {
11002        match self {
11003            Self::Quota => "quota",
11004            _ => "handover",
11005        }
11006    }
11007}
11008
11009/// The message's first line with its variable parts removed — digit runs and
11010/// path-like tokens — so "exit code 2" and "exit code 7" read
11011/// as one kind of failure.
11012fn failure_signature(msg: &str) -> String {
11013    let mut line = msg.lines().next().unwrap_or("").trim().to_lowercase();
11014    // `SeatHistory::last_fail` persists these signatures across resumes. Keep
11015    // the historical machine key while the process diagnosis uses readable prose.
11016    if let Some(code) = line
11017        .strip_prefix("process exited with no usable output (exit code ")
11018        .and_then(|s| s.strip_suffix(')'))
11019        .and_then(|s| s.parse::<i32>().ok())
11020    {
11021        line = format!("exited with some({code}) and no usable output");
11022    } else if matches!(
11023        line.as_str(),
11024        "process exited with no usable output (no exit code reported)"
11025            | "process exited with no usable output (exit code unavailable)"
11026    ) {
11027        line = "exited with none and no usable output".to_owned();
11028    }
11029    let mut out = Vec::new();
11030    for word in line.split_whitespace() {
11031        if word.contains('/') || word.contains('\\') {
11032            out.push("<path>".to_owned());
11033            continue;
11034        }
11035        let mut w = String::new();
11036        let mut in_digits = false;
11037        for c in word.chars() {
11038            if c.is_ascii_digit() {
11039                if !in_digits {
11040                    w.push('#');
11041                }
11042                in_digits = true;
11043            } else {
11044                in_digits = false;
11045                w.push(c);
11046            }
11047        }
11048        out.push(w);
11049    }
11050    out.join(" ").chars().take(120).collect()
11051}
11052
11053/// Whether a seat that just failed with `cur` may go to the next roster agent.
11054/// A quota or a timeout always may. Any other failure may not when the agent
11055/// before it failed the same way: an error the prompt causes would otherwise
11056/// walk the whole roster. `prev` is the class of the immediately preceding
11057/// agent's failure, so a quota or timeout in between breaks the run of
11058/// identical failures by itself.
11059fn should_hand_over(prev: Option<&FailClass>, cur: &FailClass) -> bool {
11060    match cur {
11061        FailClass::Quota | FailClass::Timeout => true,
11062        FailClass::Other(_) => prev != Some(cur),
11063    }
11064}
11065
11066/// A short human reason for a failed outcome, for the handover record.
11067fn fail_reason(out: &AgentOutcome) -> String {
11068    match out {
11069        AgentOutcome::Ok(_) => String::new(),
11070        AgentOutcome::Quota(_) => "rate limited (quota)".to_owned(),
11071        AgentOutcome::Dropped(o) => format!(
11072            "the CLI dropped the stream ({})",
11073            o.dropped
11074                .as_ref()
11075                .map(|d| d.why.as_str())
11076                .unwrap_or("it ended without delivering its answer")
11077        ),
11078        AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
11079            e.lines().next().unwrap_or("").chars().take(160).collect()
11080        }
11081    }
11082}
11083
11084/// Note one handover in the run: the structured record and, in the timeline,
11085/// the sentence a person reads. A quota keeps the wording it always had.
11086pub(crate) fn record_handover(
11087    state: &mut RunState,
11088    node: &str,
11089    seat: &str,
11090    from: &str,
11091    to: &str,
11092    class: &FailClass,
11093    reason: &str,
11094) {
11095    let message = if *class == FailClass::Quota {
11096        format!("{seat}: rate limited (quota) on {from}; retrying with {to}")
11097    } else {
11098        format!("{seat}: handed over {from} -> {to} ({reason})")
11099    };
11100    state.event(node, message);
11101    state.handovers.push(Handover {
11102        at: Timestamp::now(),
11103        node: node.to_owned(),
11104        seat: seat.to_owned(),
11105        from: from.to_owned(),
11106        to: to.to_owned(),
11107        reason: reason.to_owned(),
11108    });
11109}
11110
11111/// Did this reply report running a command whose own CLI never confirmed an
11112/// exit status?
11113///
11114/// An [`agent::CommandEvidence`] only ever exists when the CLI reported the
11115/// command *finished* (see that type's own doc), so this can only be `true`
11116/// for a command whose completion event carried no readable exit code — not
11117/// for one that simply is not mentioned at all. That is the one signal this
11118/// crate can read, from the same record `state.jobs` renders, about a reply
11119/// standing next to work its own CLI cannot vouch for finishing; it is
11120/// deliberately not a check on the exit code's *value* (a fixer legitimately
11121/// runs a command that fails mid-iteration before it succeeds) and not a
11122/// guess at a command still running in the background (which emits no event
11123/// at all, and so leaves no evidence here to find).
11124fn has_unconfirmed_command(commands: &[agent::CommandEvidence]) -> bool {
11125    commands.iter().any(|c| c.exit_code.is_none())
11126}
11127
11128/// Outcome of evaluating a candidate's reply against the `NO CHANGE NEEDED:`
11129/// adoption guard.
11130#[derive(Debug, Clone, PartialEq, Eq)]
11131enum NoopClaimVerdict {
11132    /// Reply did not open with `NO CHANGE NEEDED:`.
11133    Absent,
11134    /// Structured evidence passed schema, CLI command, and repository checks.
11135    Accepted,
11136    /// Reply opened with `NO CHANGE NEEDED:` but was disqualified with a
11137    /// concrete reason.
11138    Rejected(String),
11139}
11140
11141fn command_matches_check(cmd: &agent::CommandEvidence, check: &verdict::NoopCheck) -> bool {
11142    // Keep quoting and shell syntax intact: they can change the meaning of a command.
11143    cmd.description.trim() == check.method.trim()
11144}
11145
11146/// Checks cited by `requirements` plus the final check, deduplicated in order.
11147fn checks_to_cross_verify(report: &verdict::VerifiedNoopReport) -> Vec<&verdict::NoopCheck> {
11148    let mut out = report.cited_checks();
11149    if let Some(last) = report.checks.last()
11150        && !out
11151            .iter()
11152            .any(|c| c.id.trim().eq_ignore_ascii_case(last.id.trim()))
11153    {
11154        out.push(last);
11155    }
11156    out
11157}
11158
11159/// Cross-check claimed passing checks against structured CLI [`agent::CommandEvidence`]
11160/// when the backend reported commands. Empty `commands` is allowed because not
11161/// every backend emits structured command events.
11162fn check_command_evidence(
11163    report: &verdict::VerifiedNoopReport,
11164    commands: &[agent::CommandEvidence],
11165) -> std::result::Result<(), String> {
11166    if commands.is_empty() {
11167        return Ok(());
11168    }
11169    for check in checks_to_cross_verify(report) {
11170        let matching: Vec<&agent::CommandEvidence> = commands
11171            .iter()
11172            .filter(|cmd| command_matches_check(cmd, check))
11173            .collect();
11174        match check.kind {
11175            verdict::NoopEvidenceKind::Command
11176            | verdict::NoopEvidenceKind::Test
11177            | verdict::NoopEvidenceKind::Path => {
11178                let Some(last_cmd) = matching.last() else {
11179                    return Err(format!(
11180                        "contradictory command evidence: check `{}` (`{}`) claims `{}` passed, \
11181                         but no matching command was recorded by the CLI",
11182                        check.id.trim(),
11183                        check.kind,
11184                        check.target.trim()
11185                    ));
11186                };
11187                if last_cmd.exit_code != Some(0) {
11188                    return Err(format!(
11189                        "contradictory command evidence: check `{}` claims `{}` passed, \
11190                         but its last recorded CLI command (`{}`) exited with {}",
11191                        check.id.trim(),
11192                        check.target.trim(),
11193                        last_cmd.description.trim(),
11194                        crate::notices::exit_status(last_cmd.exit_code)
11195                    ));
11196                }
11197                if check.kind == verdict::NoopEvidenceKind::Test
11198                    && crate::verify_evidence::contradicts_passing_test(&last_cmd.result_summary)
11199                {
11200                    return Err(format!(
11201                        "contradictory command evidence: test check `{}` claims `{}` passed, \
11202                         but its last recorded CLI output reports failure or no passing tests",
11203                        check.id.trim(),
11204                        check.target.trim()
11205                    ));
11206                }
11207            }
11208            verdict::NoopEvidenceKind::Commit => {
11209                if let Some(last_cmd) = matching.last()
11210                    && last_cmd.exit_code != Some(0)
11211                {
11212                    return Err(format!(
11213                        "contradictory command evidence: commit check `{}` claims `{}` passed, \
11214                         but its last recorded CLI command (`{}`) exited with {}",
11215                        check.id.trim(),
11216                        check.target.trim(),
11217                        last_cmd.description.trim(),
11218                        crate::notices::exit_status(last_cmd.exit_code)
11219                    ));
11220                }
11221            }
11222        }
11223    }
11224    Ok(())
11225}
11226
11227/// Pure, synchronous half of the `NO CHANGE NEEDED:` adoption guard: clean CLI
11228/// exit, confirmed commands, strict structured JSON validation, and
11229/// `CommandEvidence` consistency.
11230fn evaluate_noop_claim(
11231    usable: bool,
11232    commands: &[agent::CommandEvidence],
11233    text: &str,
11234) -> std::result::Result<Option<verdict::VerifiedNoopReport>, String> {
11235    if !text
11236        .trim_start()
11237        .starts_with(verdict::NO_CHANGE_NEEDED_MARKER)
11238    {
11239        return Ok(None);
11240    }
11241    if !usable {
11242        return Err("turn did not finish cleanly (non-zero exit or timeout)".to_owned());
11243    }
11244    if has_unconfirmed_command(commands) {
11245        return Err("reply reported a command whose CLI never confirmed an exit status".to_owned());
11246    }
11247    let Some(parsed) = verdict::parse_verified_noop(text) else {
11248        return Ok(None);
11249    };
11250    let report = parsed?;
11251    check_command_evidence(&report, commands)?;
11252    Ok(Some(report))
11253}
11254
11255/// Cross-check verifiable commit SHAs and repository-relative paths cited by a
11256/// structured no-op report against the candidate's real Git history and
11257/// worktree. Existence alone never satisfies a requirement (the report still
11258/// had to carry concrete passing checks), while a missing commit/path or a
11259/// commit not on `base_commit` disqualifies the claim.
11260async fn verify_noop_repo_evidence(
11261    report: &verdict::VerifiedNoopReport,
11262    worktree: &Path,
11263    base_commit: &str,
11264) -> std::result::Result<(), String> {
11265    let wt_canon = std::fs::canonicalize(worktree).ok();
11266    for check in checks_to_cross_verify(report) {
11267        match check.kind {
11268            verdict::NoopEvidenceKind::Commit => {
11269                let target = check.target.trim();
11270                let Some(sha) = git::commit_of(worktree, target).await else {
11271                    return Err(format!(
11272                        "check `{}` cites commit `{target}`, which does not exist in git history",
11273                        check.id.trim()
11274                    ));
11275                };
11276                if !git::is_ancestor(worktree, &sha, base_commit).await {
11277                    return Err(format!(
11278                        "check `{}` cites commit `{target}`, which is not an ancestor of base commit `{}`",
11279                        check.id.trim(),
11280                        short(base_commit)
11281                    ));
11282                }
11283            }
11284            verdict::NoopEvidenceKind::Path => {
11285                let target = check.target.trim();
11286                let rel = verdict::strip_path_locator(target);
11287                let full = worktree.join(rel);
11288                if !full.exists() {
11289                    return Err(format!(
11290                        "check `{}` cites path `{target}`, which does not exist in the worktree",
11291                        check.id.trim()
11292                    ));
11293                }
11294                if let (Some(wt_canon), Ok(path_canon)) = (&wt_canon, std::fs::canonicalize(&full))
11295                    && !path_canon.starts_with(wt_canon)
11296                {
11297                    return Err(format!(
11298                        "check `{}` cites path `{target}`, which resolves outside the worktree",
11299                        check.id.trim()
11300                    ));
11301                }
11302            }
11303            verdict::NoopEvidenceKind::Test | verdict::NoopEvidenceKind::Command => {}
11304        }
11305    }
11306    Ok(())
11307}
11308
11309/// Full adoption guard for an implementer reply, including real Git history and
11310/// worktree path verification.
11311async fn verified_noop_claim_in_worktree(
11312    usable: bool,
11313    commands: &[agent::CommandEvidence],
11314    text: &str,
11315    worktree: &Path,
11316    base_commit: &str,
11317) -> NoopClaimVerdict {
11318    let report = match evaluate_noop_claim(usable, commands, text) {
11319        Ok(Some(r)) => r,
11320        Ok(None) => return NoopClaimVerdict::Absent,
11321        Err(reason) => return NoopClaimVerdict::Rejected(reason),
11322    };
11323    if let Err(reason) = verify_noop_repo_evidence(&report, worktree, base_commit).await {
11324        return NoopClaimVerdict::Rejected(reason);
11325    }
11326    NoopClaimVerdict::Accepted
11327}
11328
11329/// Whether a `NO CHANGE NEEDED` marker in an implementer's reply should be
11330/// trusted as a verified no-op — the adoption guard's pure text-and-command
11331/// half (repository history/path verification runs in
11332/// [`verified_noop_claim_in_worktree`]).
11333///
11334/// `usable` is the caller's `AgentOutput::usable()` (a clean CLI exit, not
11335/// timed out): a marker only earns the benefit of the doubt from a turn the
11336/// CLI itself vouches for finishing properly, the same house style
11337/// `resume_unconfirmed_commands` and `continue_fix_report` already hold a
11338/// *fix* report to for `commands`. A candidate that timed out, exited
11339/// non-zero, left a command unconfirmed, contradicted its CLI command evidence,
11340/// or failed structured validation returns `None`.
11341#[cfg(test)]
11342fn verified_noop_claim(
11343    usable: bool,
11344    commands: &[agent::CommandEvidence],
11345    text: &str,
11346) -> Option<String> {
11347    evaluate_noop_claim(usable, commands, text)
11348        .ok()
11349        .flatten()
11350        .map(|report| report.summary_text())
11351}
11352
11353fn short(commit: &str) -> String {
11354    commit.chars().take(7).collect()
11355}
11356
11357fn make_executable(path: &Path) -> Result<()> {
11358    #[cfg(unix)]
11359    {
11360        use std::os::unix::fs::PermissionsExt as _;
11361        let mut perms = std::fs::metadata(path)?.permissions();
11362        perms.set_mode(0o755);
11363        std::fs::set_permissions(path, perms)?;
11364    }
11365    #[cfg(not(unix))]
11366    {
11367        let _ = path;
11368    }
11369    Ok(())
11370}
11371
11372/// What every seat in one batch shares: where the answers are attributed, the
11373/// prompt overlay they inherit, and the build cache they are told to use.
11374///
11375/// A struct rather than four more parameters: `wave` also needs the run's
11376/// state (to record who is answering right now) and the attempt number, and
11377/// eight positional arguments is both unreadable and a clippy error.
11378struct WaveCtx<'a> {
11379    /// Exported as `MAGI_RUN`, so a task an agent files names the run that
11380    /// paid for it.
11381    run: &'a str,
11382    /// Exported as `MAGI_NODE`, and the key the prompt overlay is chosen by.
11383    node: &'a str,
11384    prompts: &'a Prompts,
11385    /// The shared `CARGO_TARGET_DIR`, when the config declares one.
11386    cache: Option<&'a Path>,
11387    /// The review round this wave belongs to, for `"review"`/`"fix"` — see
11388    /// `JobRecord::round`. `None` for every other node.
11389    round: Option<usize>,
11390    /// Carry each seat's failed-agent history across waves (the review loop
11391    /// only): start-of-round priority and handover choice read
11392    /// [`RunState::seat_history`], and every answer or failure writes it.
11393    carry_seats: bool,
11394    /// The run's park / interrupt requests, so a wait for a shared resource
11395    /// can be abandoned the moment the operator asks to park.
11396    pauses: Option<(&'a Pause, &'a Pause)>,
11397}
11398
11399/// Shared scheduling policy for operations and spawned seat invocations.
11400fn repository_wait(
11401    state: &RunState,
11402    pauses: Option<(&Pause, &Pause)>,
11403) -> crate::repo_lock::WaitPolicy {
11404    let pauses = pauses.map(|(a, b)| (a.clone(), b.clone()));
11405    let inherited = crate::repo_lock::WaitPolicy::current();
11406    crate::repo_lock::WaitPolicy::new(
11407        Duration::from_secs(state.config.graph.timeout_resource_wait),
11408        move || {
11409            inherited.cancelled()
11410                || pauses
11411                    .as_ref()
11412                    .is_some_and(|(a, b)| a.parked() || b.parked())
11413        },
11414    )
11415}
11416
11417fn record_repository_block(state: &mut RunState, error: &anyhow::Error) {
11418    if let Some(timeout) = error.downcast_ref::<agent::IsolatedSeatWait>() {
11419        state.event("resource", timeout.0.description());
11420        state.resource_block = Some(timeout.0.clone());
11421        return;
11422    }
11423    if error.is::<crate::repo_lock::ResourceBlocked>() {
11424        state.resource_block = Some(crate::run::ResourceBlock {
11425            cause: crate::run::ResourceBlockCause::Other,
11426            node: "repository".into(),
11427            kind: if error.is::<crate::build_target::AdmissionDiskWait>() {
11428                "disk admission"
11429            } else if error.to_string().contains("disk pressure") {
11430                "disk pressure"
11431            } else if error.to_string().contains("disk admission") {
11432                "disk admission"
11433            } else if error.to_string().contains(crate::incremental::BLOCKED) {
11434                "incremental cache admission"
11435            } else {
11436                "repository coordination"
11437            }
11438            .into(),
11439            detail: format!("{error:#}"),
11440            at: Timestamp::now(),
11441        });
11442        state.event("resource", error.to_string());
11443    }
11444}
11445
11446async fn coordinate_operation(
11447    state: &mut RunState,
11448    cwd: &Path,
11449    wait: &crate::repo_lock::WaitPolicy,
11450) -> Result<Option<crate::repo_lock::SeatLease>> {
11451    let result =
11452        crate::repo_lock::SeatLease::operation_with(cwd, state.config.coordination.as_ref(), wait)
11453            .await;
11454    if let Err(e) = &result {
11455        record_repository_block(state, e);
11456    }
11457    result
11458}
11459
11460/// Run one job, honouring the parallelism budget.
11461async fn run_one(
11462    job: SeatJob,
11463    sem: Arc<Semaphore>,
11464    ctx: &WaveCtx<'_>,
11465    state: &mut RunState,
11466    attempt: usize,
11467) -> (SeatState, AgentOutcome) {
11468    let (_, seat, out) = wave(vec![job], sem, ctx, state, attempt)
11469        .await
11470        .pop()
11471        .expect("one job in, one result out");
11472    (seat, out)
11473}
11474
11475/// Run every job concurrently, capped by the semaphore, preserving order.
11476///
11477/// Every seat in the batch is recorded into [`RunState::active`] before the
11478/// wave starts and cleared as each answer lands, so the run's own record says
11479/// who is still being waited on rather than only who finished.
11480async fn wave(
11481    jobs: Vec<SeatJob>,
11482    sem: Arc<Semaphore>,
11483    ctx: &WaveCtx<'_>,
11484    state: &mut RunState,
11485    attempt: usize,
11486) -> Vec<(usize, SeatState, AgentOutcome)> {
11487    let WaveCtx {
11488        run,
11489        node,
11490        prompts,
11491        cache,
11492        round,
11493        carry_seats: _,
11494        pauses,
11495    } = *ctx;
11496    let cache = cache.filter(|_| !crate::build_target::isolated(&state.config));
11497    for job in &jobs {
11498        state.seat_started(node, &job.seat.key, job.timeout, attempt);
11499    }
11500    if let Err(e) = state.save() {
11501        // A failed persist of "who is answering right now" must not abort the
11502        // wave: the seats are already being asked, and the alternative is
11503        // losing the answers to save a status line nobody may even be
11504        // watching.
11505        tracing::warn!("could not persist in-progress seats: {e:#}");
11506    }
11507    // Shared-mode waves keep their existing single lease. Isolated writers
11508    // acquire their own checkout's target at seat admission.
11509    let jobs_had_a_writer = jobs.iter().any(|j| j.allow_write);
11510    // The wait for the lease has its own bound, `timeout_resource_wait`; it is
11511    // never borrowed from a job's agent budget (and never charged to it either,
11512    // see below). The agent's clock starts in `agent::invoke`, at spawn.
11513    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
11514    let cache_guard = if let Some(cache_dir) = cache {
11515        if jobs_had_a_writer {
11516            let owner = crate::cache::Owner::here(run, node, "*", Path::new("(wave)"), "");
11517            let cancel = move || pauses.is_some_and(|(a, b)| a.parked() || b.parked());
11518            match acquire_cache_lease(
11519                state,
11520                cache_dir,
11521                &owner,
11522                resource_limit,
11523                node,
11524                node,
11525                &cancel,
11526            )
11527            .await
11528            {
11529                Ok(Some(g)) => Some(g),
11530                // Parking: leave without spawning anything. The run parks at
11531                // the next boundary and the seats are asked afresh on resume.
11532                Ok(None) => {
11533                    if let Some(block) = &mut state.resource_block {
11534                        block.cause = crate::run::ResourceBlockCause::Cancelled {
11535                            park: pauses.and_then(|(a, b)| b.cause().or_else(|| a.cause())),
11536                        };
11537                    }
11538                    return block_wave(
11539                        jobs,
11540                        state,
11541                        node,
11542                        attempt,
11543                        "parked while waiting for the shared build cache",
11544                    );
11545                }
11546                // An unreadable lease is not contention: keep the old
11547                // fallback (no shared cache for this wave's seats).
11548                Err(e) if e.downcast_ref::<CacheCheckError>().is_some() => None,
11549                Err(e) => {
11550                    // Writing seats may not build into a cache this run does
11551                    // not hold, and an agent that cannot be given one is not
11552                    // asked at all: the run stops resumably instead.
11553                    let why = format!("{e:#}");
11554                    state.event(
11555                        "resource",
11556                        format!("{node}: no agent was started - {why}; resume to ask the same agents again"),
11557                    );
11558                    return block_wave(jobs, state, node, attempt, &why);
11559                }
11560            }
11561        } else {
11562            None
11563        }
11564    } else {
11565        None
11566    };
11567    // Every job keeps its whole budget: the wait above was not the agent's.
11568    // Restart the seats' clocks so "started" means "being spawned now".
11569    state.seats_spawning(node, attempt);
11570    if let Err(e) = state.save() {
11571        tracing::warn!("could not persist the start of a wave: {e:#}");
11572    }
11573    // Queueing behind this wave's own seats for a parallelism slot is normal
11574    // (each of them is bounded by its own agent timeout); only a wait beyond
11575    // all of them plus the resource limit means the slots never came back.
11576    let slot_limit = resource_limit
11577        + jobs
11578            .iter()
11579            .map(|j| j.timeout)
11580            .max()
11581            .unwrap_or_default()
11582            .saturating_mul(jobs.len() as u32);
11583    let mut set = tokio::task::JoinSet::new();
11584    // Seats announce themselves here the moment they hold a parallelism
11585    // permit, i.e. just before their CLI is spawned.
11586    let (spawned_tx, mut spawned_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
11587    let overlay = prompts.overlay(node);
11588    let repository_wait = repository_wait(state, pauses);
11589    for (i, mut job) in jobs.into_iter().enumerate() {
11590        job.prompt = prompt::with_overlay(job.prompt, overlay.clone());
11591        if cache.is_some() {
11592            job.prompt.push('\n');
11593            job.prompt
11594                .push_str(&prompt::build_cache_note(node, job.allow_write));
11595        }
11596        let sem = Arc::clone(&sem);
11597        let run = run.to_owned();
11598        let node = node.to_owned();
11599        // Only implementers were told about the task's attachments, so only
11600        // their seats get the directory widened for reading.
11601        let attachments = if node == "implement" {
11602            state.attachments.clone()
11603        } else {
11604            Vec::new()
11605        };
11606        // A read-only seat is never handed `CARGO_TARGET_DIR` — see
11607        // `prompt::build_cache_note`'s doc for why setting it anyway is
11608        // exactly how a sandboxed reviewer's write refusal got reported as a
11609        // defect in the patch, not a property of its own seat. And a
11610        // write-allowed one is handed it only when the lease above was
11611        // actually acquired: a wave that could not get it (`cache_guard` is
11612        // `None`, see its own comment) must not send seats to build into a
11613        // directory this run does not hold - that is the exact concurrent,
11614        // unmanaged-write race this module exists to prevent, not something
11615        // "proceeding anyway" is allowed to reintroduce.
11616        let cache = cache
11617            .filter(|_| job.allow_write && cache_guard.is_some())
11618            .map(Path::to_path_buf);
11619        let spawned_tx = spawned_tx.clone();
11620        let repository_wait = repository_wait.clone();
11621        let coordination = state.config.coordination.clone();
11622        let fetched_base = state.fetched_base.clone();
11623        set.spawn(async move {
11624            // A wait for a parallelism slot is scheduling, not the agent: it
11625            // is bounded by its own limit and ends as a resource block, never
11626            // as a timeout of the agent that was not started.
11627            let _permit = match tokio::time::timeout(slot_limit, sem.acquire()).await {
11628                Ok(p) => p,
11629                Err(_) => {
11630                    return (
11631                        i,
11632                        job.seat,
11633                        AgentOutcome::ResourceBlocked(format!(
11634                            "no parallel slot became free within {}s",
11635                            slot_limit.as_secs()
11636                        )),
11637                        None,
11638                        false,
11639                    );
11640                }
11641            };
11642            spawned_tx.send(job.seat.key.clone()).ok();
11643            let mut seat = job.seat;
11644            let out = repository_wait
11645                .scope(agent::invoke(
11646                    &job.spec,
11647                    &mut seat,
11648                    &Invocation {
11649                        coordination: coordination.as_ref(),
11650                        fetched_base: fetched_base.as_ref(),
11651                        cwd: &job.cwd,
11652                        prompt: &job.prompt,
11653                        timeout: job.timeout,
11654                        allow_write: job.allow_write,
11655                        sessions: job.sessions,
11656                        artifacts: &job.artifacts,
11657                        stem: &job.stem,
11658                        run: &run,
11659                        node: &node,
11660                        cache_dir: cache.as_deref(),
11661                        attachments: &attachments,
11662                        writable: &[],
11663                    },
11664                ))
11665                .await;
11666            let cache_block = out
11667                .as_ref()
11668                .err()
11669                .and_then(|error| error.downcast_ref::<agent::IsolatedSeatWait>())
11670                .map(|timeout| timeout.0.clone());
11671            let interrupted = out
11672                .as_ref()
11673                .err()
11674                .is_some_and(|error| error.is::<agent::ExecutionInterrupted>());
11675            let out = match out {
11676                Ok(o) if o.quota_exhausted() => AgentOutcome::Quota(o),
11677                Ok(o) if o.usable() => AgentOutcome::Ok(o),
11678                // Billed work the CLI failed to hand over is not an ordinary
11679                // failure, but its text is the CLI's raw error JSON, not an
11680                // answer — `Dropped` keeps it out of `Ok` so a caller cannot
11681                // read it as one by forgetting to check. `usable()` is always
11682                // false here (dropped implies an empty response), so this has
11683                // to be checked before the catch-all `Failed` below or the
11684                // one shape this exists for is lost with the rest.
11685                Ok(o) if o.work_undelivered() => AgentOutcome::Dropped(o),
11686                Ok(o) if o.timed_out => AgentOutcome::Failed(TIMED_OUT.to_owned()),
11687                Ok(o) => AgentOutcome::Failed(format!(
11688                    "process exited with no usable output ({})",
11689                    crate::notices::exit_status(o.exit_code)
11690                )),
11691                Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
11692                    AgentOutcome::ResourceBlocked(e.to_string())
11693                }
11694                Err(e) => AgentOutcome::Failed(e.to_string()),
11695            };
11696            (i, seat, out, cache_block, interrupted)
11697        });
11698    }
11699    drop(spawned_tx);
11700    let mut collected: Vec<Option<(usize, SeatState, AgentOutcome)>> = Vec::new();
11701    loop {
11702        let joined = tokio::select! {
11703            Some(key) = spawned_rx.recv() => {
11704                // The clock of this seat starts now, not when it queued.
11705                state.seat_spawned(&key);
11706                if let Err(e) = state.save() {
11707                    tracing::warn!("could not persist a seat's start: {e:#}");
11708                }
11709                continue;
11710            }
11711            joined = set.join_next() => joined,
11712        };
11713        let Some(joined) = joined else {
11714            break;
11715        };
11716        let (i, seat, out, cache_block, interrupted) = match joined {
11717            Ok(v) => v,
11718            // No seat to clear: a panicked task never reported which one it
11719            // was. The defensive sweep below this loop is what stops that
11720            // seat's `active` entry from surviving forever.
11721            Err(e) => {
11722                tracing::error!("agent task panicked: {e}");
11723                continue;
11724            }
11725        };
11726        state.seat_finished(&seat.key);
11727        if interrupted
11728            && node == "implement"
11729            && let Some(label) = state
11730                .candidates
11731                .iter()
11732                .find(|candidate| seat.key == format!("impl-{}", candidate.label))
11733                .map(|candidate| candidate.label)
11734        {
11735            state.candidate_preservation.insert(
11736                label,
11737                "interrupted implementation awaiting persistence".into(),
11738            );
11739            state.interrupted_implementations.insert(label);
11740        }
11741        if let Some(block) = cache_block
11742            && state.resource_block.is_none()
11743        {
11744            state.event("resource", block.description());
11745            state.resource_block = Some(block);
11746        }
11747        if let AgentOutcome::ResourceBlocked(why) = &out
11748            && state.resource_block.is_none()
11749        {
11750            state.resource_block = Some(crate::run::ResourceBlock {
11751                cause: crate::run::ResourceBlockCause::Other,
11752                node: node.to_owned(),
11753                kind: if why.contains("disk pressure") {
11754                    "disk pressure"
11755                } else if why.contains("disk admission") {
11756                    "disk admission"
11757                } else if why.contains(crate::incremental::BLOCKED) {
11758                    "incremental cache admission"
11759                } else if why.contains(crate::build_target::KIND) {
11760                    crate::build_target::KIND
11761                } else if why.contains("repository coordination") {
11762                    "repository coordination"
11763                } else {
11764                    "parallel slot"
11765                }
11766                .to_owned(),
11767                detail: why.clone(),
11768                at: Timestamp::now(),
11769            });
11770            let activity = if interrupted {
11771                "agent execution interrupted"
11772            } else {
11773                "no agent was started"
11774            };
11775            state.event("resource", format!("{node}: {activity} - {why}"));
11776        }
11777        record_jobs(state, node, round, &seat.key, &out);
11778        if let Err(e) = state.save() {
11779            tracing::warn!("could not persist a seat's completion: {e:#}");
11780        }
11781        if collected.len() <= i {
11782            collected.resize_with(i + 1, || None);
11783        }
11784        collected[i] = Some((i, seat, out));
11785    }
11786    // Belt-and-braces for the panic branch above: every seat this exact batch
11787    // started shares this `(node, attempt)` pair, and every seat that finished
11788    // normally already cleared itself, so anything left tagged with it here
11789    // can only be a panicked task's leftover. Cleared unconditionally rather
11790    // than left to read as still answering forever.
11791    if state
11792        .active
11793        .values()
11794        .any(|a| a.node == node && a.attempt == attempt)
11795    {
11796        state
11797            .active
11798            .retain(|_, a| !(a.node == node && a.attempt == attempt));
11799        if let Err(e) = state.save() {
11800            tracing::warn!("could not persist the end of a wave: {e:#}");
11801        }
11802    }
11803    // Whether or not the lease above was actually held, several worktrees
11804    // may just have built into the cache with nothing here able to name one
11805    // coherent (worktree, head) for it - see `cache::invalidate_identity`'s
11806    // own doc. Forgetting the old record costs the next `e2e`/`gate` one
11807    // clean it might not have strictly needed; trusting a stale match would
11808    // cost it a wrong answer.
11809    if let Some(cache_dir) = cache
11810        && jobs_had_a_writer
11811    {
11812        crate::cache::invalidate_identity(&crate::run::home(), cache_dir);
11813    }
11814    if let Some(guard) = cache_guard {
11815        guard.release();
11816    }
11817    collected.into_iter().flatten().collect()
11818}
11819
11820/// Fold one seat's [`agent::CommandEvidence`] (if its outcome carries any)
11821/// into the run's [`JobRecord`] log — every node, every seat, uniformly:
11822/// this is data collection, not the fix-specific completion contract in
11823/// [`Runner::continue_fix_report`], and applies regardless of which node
11824/// asked.
11825///
11826/// Only `AgentOutcome::Ok`/`Quota`/`Dropped` carry an [`AgentOutput`] to read
11827/// evidence from; `Failed` does not, and correctly contributes nothing — a
11828/// timeout or crash is not itself evidence about a command the seat may have
11829/// started.
11830fn record_jobs(
11831    state: &mut RunState,
11832    node: &str,
11833    round: Option<usize>,
11834    seat: &str,
11835    out: &AgentOutcome,
11836) {
11837    let commands: &[agent::CommandEvidence] = match out {
11838        AgentOutcome::Ok(o) | AgentOutcome::Quota(o) | AgentOutcome::Dropped(o) => &o.commands,
11839        AgentOutcome::Failed(_) | AgentOutcome::ResourceBlocked(_) => &[],
11840    };
11841    let checked_at = Timestamp::now();
11842    for c in commands {
11843        state.jobs.push(JobRecord {
11844            node: node.to_owned(),
11845            round,
11846            seat: seat.to_owned(),
11847            id: c.id.clone(),
11848            description: c.description.clone(),
11849            checked_at,
11850            status: match c.exit_code {
11851                Some(0) => JobStatus::Completed,
11852                Some(_) => JobStatus::Failed,
11853                None => JobStatus::Unknown,
11854            },
11855            exit_code: c.exit_code,
11856            result_summary: c.result_summary.clone(),
11857            source: c.source.clone(),
11858        });
11859    }
11860}
11861
11862/// Is a review round clean, given how many reviewer seats answered against
11863/// how many the round expected?
11864///
11865/// A seat that never answered (timeout, crash, unparsable output) is not a
11866/// seat that read the patch and found nothing — treating it as such is
11867/// exactly the bug this function exists to close. Under the default `block`
11868/// policy a missing seat can never be clean; `warn` still requires the seats
11869/// that *did* answer to have found nothing blocking and verification to be
11870/// green.
11871///
11872/// `quota_missing` narrows that `block` default for exactly one cause of
11873/// absence: a seat lost to its own rate limit this round. Re-reviewing hoping
11874/// a session limit lifts by the very next round buys nothing — the seat is
11875/// asked again with the same quota — so once every missing seat is accounted
11876/// for by a quota loss (and at least one seat *did* answer, so a decision has
11877/// something to rest on) the round is decided on the panel that could answer,
11878/// same as `warn` would. A panel that lost every seat to quota is not
11879/// decided here: `answered == 0` falls through to the existing `block`
11880/// fallback so a fully collapsed panel still waits rather than landing on no
11881/// review at all.
11882fn round_is_clean(
11883    blocking: usize,
11884    e2e_ok: bool,
11885    answered: usize,
11886    expected: usize,
11887    quota_missing: usize,
11888    policy: IncompleteReviewPolicy,
11889) -> bool {
11890    if blocking != 0 || !e2e_ok {
11891        return false;
11892    }
11893    if answered == expected || policy == IncompleteReviewPolicy::Warn {
11894        return true;
11895    }
11896    answered > 0 && expected - answered <= quota_missing
11897}
11898
11899/// The review loop's own conclusion, derived entirely from its persisted
11900/// round records and the round budget that produced them — never from
11901/// `status`, so a reentry (or `gate`/`merge` reading it independently)
11902/// recomputes the identical answer regardless of what an earlier node in the
11903/// same walk, or a previous walk, did to `status`.
11904///
11905/// `None` while more rounds remain to try, including when review never ran
11906/// at all (`review_rounds = 0`, or nothing yet recorded). Once a round has
11907/// gone clean, or the budget is spent, or the tree has stopped moving (see
11908/// [`STAGNANT_LIMIT`]), the answer is one of two things:
11909///
11910/// - An incomplete panel that raised nothing is missing input, not a
11911///   verified tree — never a hand-off candidate, whatever verification said
11912///   (see [`ReviewRound::incomplete`], `IncompleteReviewPolicy`).
11913/// - Otherwise, green e2e on the last round hands off (see
11914///   [`Runner::stop_reviewing`]); red e2e blocks.
11915///
11916/// A last round whose own verification is still `ResourceBlocked` — magi
11917/// itself never got a command to run, not evidence the patch is broken —
11918/// is neither: this returns `None` for it too, the same as "more rounds
11919/// remain", so a reentry retries the check (see `Runner::review_loop`'s own
11920/// handling of that shape) instead of this cheap recomputation guessing a
11921/// verdict a real attempt never produced.
11922pub(crate) fn review_conclusion(reviews: &[ReviewRound], max_rounds: usize) -> Option<RunStatus> {
11923    if max_rounds == 0
11924        || reviews.last().is_some_and(|r| {
11925            r.clean && matches!(r.e2e_status(), E2eStatus::Passed | E2eStatus::NotConfigured)
11926        })
11927    {
11928        return Some(RunStatus::Gating);
11929    }
11930    let last = reviews.last()?;
11931    let stagnant = reviews.iter().rev().take_while(|r| !r.progressed).count() >= STAGNANT_LIMIT;
11932    if reviews.len() < max_rounds && !stagnant {
11933        return None;
11934    }
11935    if last.incomplete() && last.blocking == 0 {
11936        return Some(RunStatus::Blocked);
11937    }
11938    if last.e2e_status() == E2eStatus::ResourceBlocked
11939        || (last.e2e_status() == E2eStatus::Deferred && last.blocking == 0 && last.fix.is_none())
11940    {
11941        return None;
11942    }
11943    Some(if last.e2e.iter().all(CommandOutcome::ok) {
11944        RunStatus::Gating
11945    } else {
11946        RunStatus::Blocked
11947    })
11948}
11949
11950/// How long a re-ask may take, given the budget the first attempt had.
11951///
11952/// A `nudged` retry is a request to restate an answer the seat has already
11953/// worked out: it carries no new work, so it does not deserve the original
11954/// budget. Measured on run 01c2, two judges restated their ranking in 41 and
11955/// 133 seconds while a third sat for over ten minutes on a resumed session
11956/// holding 410 KB of prior output - and because the retry had inherited the
11957/// full 1200s judge timeout, one stuck nudge nearly doubled the wall time of a
11958/// judging round whose other seats were long finished.
11959///
11960/// A quarter of the budget, with a floor so that a deliberately short timeout
11961/// does not collapse to nothing. A retry that re-sends the whole prompt
11962/// (because the seat kept no context) is the original job again, and keeps the
11963/// original budget.
11964pub(crate) fn retry_budget(full: Duration, nudged: bool) -> Duration {
11965    if nudged {
11966        (full / 4).max(Duration::from_secs(120)).min(full)
11967    } else {
11968        full
11969    }
11970}
11971
11972/// Run a wave and parse each reply, re-asking the seats whose reply was
11973/// unusable.
11974///
11975/// The re-ask is a nudge rather than the whole prompt again when the seat still
11976/// holds its conversation, which is the difference between a cheap retry and
11977/// paying for the entire candidate set twice.
11978///
11979/// A seat whose agent *fails* (rate limit, timeout, any other error) and has a
11980/// successor in `roster` is handed to it instead of being re-asked: the
11981/// handover is the retry. A seat with no successor left (a single-agent
11982/// roster, the roster's tail) is nudged as before, up to `retries` times. So
11983/// the asks to one seat in one node number at most
11984/// `roster.len().max(1) * (1 + retries)`; an agent that still has a successor
11985/// is asked once (a dropped stream is nudged first), and only the last agent
11986/// of the chain gets the `retries` same-agent nudges. Each roster agent is
11987/// tried at most once per seat, walking forward from the seat's own position and never wrapping
11988/// ([`next_untried_in_roster`]); a quota or timeout always hands over, any
11989/// other failure stops the chain when the previous agent failed the same way
11990/// ([`should_hand_over`]). The new agent takes a fresh [`SeatState`], so
11991/// [`has_context`] is false and the job's own full prompt and full budget are
11992/// sent. A seat whose chain ends on a quota records one [`QuotaLoss`] (the
11993/// intermediate ones are not losses) and is returned as a failure like any
11994/// other absent seat — the caller decides whether the panel still has a
11995/// quorum. An empty `roster` disables handover: failures are nudged as they
11996/// always were, and a quota is simply lost. A reply that fails to parse or
11997/// validate is the prompt's doing and is only ever nudged, never handed over.
11998///
11999/// The returned [`SeatState`] names the agent that answered (or tried last).
12000#[allow(clippy::too_many_arguments)]
12001async fn ask_json_wave<T>(
12002    jobs: Vec<SeatJob>,
12003    sem: Arc<Semaphore>,
12004    retries: usize,
12005    roster: &[AgentSpec],
12006    ctx: &WaveCtx<'_>,
12007    losses: &mut Vec<QuotaLoss>,
12008    state: &mut RunState,
12009    validate: &(dyn Fn(&T) -> Result<()> + Send + Sync),
12010) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
12011where
12012    T: serde::de::DeserializeOwned + Send + 'static,
12013{
12014    ask_wave_with(
12015        jobs,
12016        sem,
12017        retries,
12018        roster,
12019        ctx,
12020        losses,
12021        state,
12022        &|text: &str| {
12023            let v = verdict::extract_json::<T>(text)?;
12024            validate(&v)?;
12025            Ok(v)
12026        },
12027    )
12028    .await
12029}
12030
12031/// [`ask_json_wave`] with the reading of an answer supplied by the caller, so
12032/// a node whose answer is prose (deliberation) shares the same handover,
12033/// failure classification, quota bookkeeping and bounds instead of a copy.
12034///
12035/// A seat handed to another roster agent is sent the job's `handover` prompt
12036/// (when it has one) rather than `prompt`: the new agent has no session, so a
12037/// resume-style prompt would be incomplete. That holds for the handover ask
12038/// and for every nudge to that agent whose `has_context` is false.
12039#[allow(clippy::too_many_arguments)]
12040async fn ask_wave_with<T>(
12041    jobs: Vec<SeatJob>,
12042    sem: Arc<Semaphore>,
12043    retries: usize,
12044    roster: &[AgentSpec],
12045    ctx: &WaveCtx<'_>,
12046    losses: &mut Vec<QuotaLoss>,
12047    state: &mut RunState,
12048    parse: &(dyn Fn(&str) -> Result<T> + Send + Sync),
12049) -> Vec<(SeatState, Result<(T, AgentOutput)>, usize)>
12050where
12051    T: Send + 'static,
12052{
12053    let n = jobs.len();
12054    let originals: Vec<SeatJob> = jobs;
12055    let mut seats: Vec<SeatState> = originals.iter().map(|j| j.seat.clone()).collect();
12056    let mut done: Vec<Option<Result<(T, AgentOutput)>>> = (0..n).map(|_| None).collect();
12057    // Nudges each seat's *current* agent has taken — 0 for a first-ask
12058    // answer, N once it has gone through N nudges. Read back once this
12059    // returns, so a caller building a history record (`ReviewRecord`) can
12060    // tell "never answered" (`failed: Some(_)`, `attempts == 0`) apart from
12061    // "recovered after a nudge" (`failed: None`, `attempts > 0`) — see that
12062    // field's own doc.
12063    let mut nudges: Vec<usize> = vec![0; n];
12064    // The agent now occupying each seat, the ids it has already been through,
12065    // where in the roster the walk began, the class of the last failure, and
12066    // the stem word of a handover not yet asked (full prompt, full budget).
12067    let mut specs: Vec<AgentSpec> = originals.iter().map(|j| j.spec.clone()).collect();
12068    let mut tried: Vec<BTreeSet<String>> = specs
12069        .iter()
12070        .map(|s| BTreeSet::from([s.id.clone()]))
12071        .collect();
12072    let starts: Vec<usize> = specs
12073        .iter()
12074        .map(|s| roster.iter().position(|r| r.id == s.id).unwrap_or(0))
12075        .collect();
12076    let carry = ctx.carry_seats && !roster.is_empty();
12077    // Carried across rounds: ids that failed the seat earlier, and how the
12078    // last failure went (so a repeat of it is not handed over again).
12079    let carried: Vec<BTreeSet<String>> = originals
12080        .iter()
12081        .map(|j| {
12082            state
12083                .seat_history
12084                .get(&j.seat.key)
12085                .filter(|_| carry)
12086                .map(|h| h.failed.clone())
12087                .unwrap_or_default()
12088        })
12089        .collect();
12090    let mut prev: Vec<Option<FailClass>> = originals
12091        .iter()
12092        .map(|j| {
12093            state
12094                .seat_history
12095                .get(&j.seat.key)
12096                .filter(|_| carry)
12097                .and_then(|h| h.last_fail.clone())
12098        })
12099        .collect();
12100    let next_agent =
12101        |i: usize, tried: &BTreeSet<String>, specs: &[AgentSpec]| -> Option<AgentSpec> {
12102            let others: BTreeSet<String> = specs
12103                .iter()
12104                .enumerate()
12105                .filter(|(j, _)| *j != i)
12106                .map(|(_, s)| s.id.clone())
12107                .collect();
12108            pick_successor(
12109                roster,
12110                starts[i],
12111                tried,
12112                carry.then(|| &carried[i]),
12113                &others,
12114            )
12115            .cloned()
12116        };
12117    let mut fresh: Vec<Option<String>> = vec![None; n];
12118    let mut last_quota: Vec<Option<agent::Quota>> = vec![None; n];
12119    let mut pending: Vec<usize> = (0..n).collect();
12120
12121    // Per seat the work is bounded by `roster.len().max(1) * (1 + retries)`
12122    // asks: an agent with a successor is asked once and handed over, and only
12123    // a seat with no successor spends `retries` nudges on the same agent. This
12124    // only guarantees the loop's own termination whatever those say.
12125    let max_rounds = (retries + 1) * roster.len().max(1) + 1;
12126    for round in 0..max_rounds {
12127        if pending.is_empty() {
12128            break;
12129        }
12130        let mut batch = Vec::with_capacity(pending.len());
12131        let mut renudged: Vec<&str> = Vec::new();
12132        for &i in &pending {
12133            let src = &originals[i];
12134            // A seat now held by another agent than the job named has no
12135            // session of its own: it gets the full-context prompt whenever
12136            // it is asked in full (the handover ask, a nudge it cannot
12137            // resume).
12138            let full: &str = match &src.handover {
12139                Some(h) if specs[i].id != src.spec.id => h,
12140                _ => &src.prompt,
12141            };
12142            // The prompt and the budget are one decision: a nudge restates
12143            // finished work, a re-sent prompt redoes it.
12144            let (prompt, timeout, stem) = if let Some(word) = fresh[i].take() {
12145                (
12146                    full.to_owned(),
12147                    src.timeout,
12148                    format!("{}-{word}-{}", src.stem, specs[i].id),
12149                )
12150            } else if nudges[i] == 0 {
12151                (full.to_owned(), src.timeout, src.stem.clone())
12152            } else {
12153                renudged.push(src.seat.key.as_str());
12154                let why = done[i]
12155                    .as_ref()
12156                    .and_then(|r| r.as_ref().err().map(ToString::to_string))
12157                    .unwrap_or_else(|| "no parsable answer".to_owned());
12158                let nudge = prompt::nudge(&why);
12159                let nudged = has_context(&specs[i], &seats[i], src.sessions);
12160                let prompt = if nudged {
12161                    nudge
12162                } else {
12163                    format!("{full}\n\n---\n\n{nudge}")
12164                };
12165                (
12166                    prompt,
12167                    retry_budget(src.timeout, nudged),
12168                    format!("{}-retry{}", src.stem, nudges[i]),
12169                )
12170            };
12171            batch.push(SeatJob {
12172                spec: specs[i].clone(),
12173                seat: seats[i].clone(),
12174                cwd: src.cwd.clone(),
12175                prompt,
12176                timeout,
12177                allow_write: src.allow_write,
12178                sessions: src.sessions,
12179                artifacts: src.artifacts.clone(),
12180                stem,
12181                handover: None,
12182            });
12183        }
12184
12185        if !renudged.is_empty() {
12186            state.event(
12187                ctx.node,
12188                format!("retry {round}: re-asking {}", renudged.join(", ")),
12189            );
12190        }
12191        let results = wave(batch, Arc::clone(&sem), ctx, state, round).await;
12192        let mut still = Vec::new();
12193        for (&i, (_wi, seat, out)) in pending.iter().zip(results) {
12194            seats[i] = seat;
12195            // No agent was asked: nothing to hand over, nudge, remember or
12196            // charge. The caller sees `resource_block` and stops the node.
12197            if let AgentOutcome::ResourceBlocked(why) = &out {
12198                done[i] = Some(Err(anyhow::anyhow!("{why}")));
12199                continue;
12200            }
12201            let class = FailClass::of(&out);
12202            // A dropped stream is nudged first (the conversation is still
12203            // there to pick up); only a seat whose nudges are spent hands over.
12204            let nudge_first = matches!(out, AgentOutcome::Dropped(_))
12205                && nudges[i] < retries
12206                && !roster.is_empty();
12207            if let Some(cur) = class.clone().filter(|_| !roster.is_empty() && !nudge_first) {
12208                let next = should_hand_over(prev[i].as_ref(), &cur)
12209                    .then(|| next_agent(i, &tried[i], &specs))
12210                    .flatten();
12211                if carry {
12212                    let h = state
12213                        .seat_history
12214                        .entry(originals[i].seat.key.clone())
12215                        .or_default();
12216                    h.failed.insert(specs[i].id.clone());
12217                    h.last_fail = Some(cur.clone());
12218                    if h.last_ok.as_deref() == Some(specs[i].id.as_str()) {
12219                        h.last_ok = None;
12220                    }
12221                    // Saved before the next agent is asked, so a restart in
12222                    // between does not forget who failed.
12223                    if let Err(e) = state.save() {
12224                        tracing::warn!("could not persist a seat's failure history: {e:#}");
12225                    }
12226                }
12227                if let Some(next) = next {
12228                    record_handover(
12229                        state,
12230                        ctx.node,
12231                        &originals[i].seat.key,
12232                        &specs[i].id,
12233                        &next.id,
12234                        &cur,
12235                        &fail_reason(&out),
12236                    );
12237                    tried[i].insert(next.id.clone());
12238                    prev[i] = Some(cur.clone());
12239                    seats[i] =
12240                        handover_seat(&originals[i].seat.key, &next.id, state.next_seat_seed());
12241                    specs[i] = next;
12242                    fresh[i] = Some(cur.stem_word().to_owned());
12243                    nudges[i] = 0;
12244                    done[i] = Some(Err(anyhow::anyhow!(
12245                        "handed over after: {}",
12246                        fail_reason(&out)
12247                    )));
12248                    still.push(i);
12249                    continue;
12250                }
12251            }
12252            if carry
12253                && !nudge_first
12254                && let Some(cur) = class.clone()
12255            {
12256                // The chain ended here (no successor, or a repeated failure).
12257                let h = state
12258                    .seat_history
12259                    .entry(originals[i].seat.key.clone())
12260                    .or_default();
12261                h.failed.insert(specs[i].id.clone());
12262                h.last_fail = Some(cur);
12263            }
12264            let parsed = match out {
12265                AgentOutcome::Ok(o) => parse(&o.text).map(|v| (v, o)),
12266                AgentOutcome::Quota(o) => {
12267                    last_quota[i] = o.quota.clone();
12268                    Err(anyhow::anyhow!("rate limited (quota); not retrying now"))
12269                }
12270                // Not a parseable answer: the nudge loop re-asks it, which is
12271                // exactly what a dropped stream needs. Just don't hand its raw
12272                // error JSON to `extract_json`.
12273                AgentOutcome::Dropped(o) => {
12274                    let why = o
12275                        .dropped
12276                        .as_ref()
12277                        .map(|d| d.why.as_str())
12278                        .unwrap_or("the CLI ended the stream without delivering its answer");
12279                    Err(anyhow::anyhow!("the CLI dropped the stream ({why})"))
12280                }
12281                AgentOutcome::Failed(e) | AgentOutcome::ResourceBlocked(e) => {
12282                    Err(anyhow::anyhow!(e))
12283                }
12284            };
12285            let quota = class == Some(FailClass::Quota);
12286            let failed = parsed.is_err();
12287            if !failed && matches!(ctx.node, "judge" | "vote") {
12288                // A validated answer restores this seat's quorum presence,
12289                // including on the normal path after an all-seat block.
12290                state
12291                    .quota
12292                    .retain(|loss| loss.seat != originals[i].seat.key);
12293            }
12294            done[i] = Some(parsed);
12295            if carry && !failed {
12296                let h = state
12297                    .seat_history
12298                    .entry(originals[i].seat.key.clone())
12299                    .or_default();
12300                h.failed.remove(&specs[i].id);
12301                h.last_ok = Some(specs[i].id.clone());
12302                h.last_fail = None;
12303            }
12304            // Do not re-ask a rate-limited seat (quota) — a retry is known to
12305            // fail the same way; and never re-ask a seat that already parsed.
12306            // A failed agent that still has a successor is not re-asked
12307            // either: the handover was its remedy and has just been refused
12308            // (the chain stops on a repeated failure class). A seat with no
12309            // successor left (a single-agent roster, the roster's tail, or an
12310            // empty roster) keeps the same-agent nudge, bounded by `retries`.
12311            let agent_failure = class.is_some()
12312                && !nudge_first
12313                && !roster.is_empty()
12314                && next_agent(i, &tried[i], &specs).is_some();
12315            if failed && !quota && !agent_failure && nudges[i] < retries {
12316                nudges[i] += 1;
12317                still.push(i);
12318            }
12319        }
12320        pending = still;
12321    }
12322
12323    // One loss per seat whose chain ended on a quota: the intermediate ones
12324    // were absorbed by a handover and are not losses.
12325    for (i, q) in last_quota.into_iter().enumerate() {
12326        if let Some(quota) = q {
12327            losses.push(QuotaLoss::from_report(
12328                originals[i].seat.key.clone(),
12329                ctx.node,
12330                Some(&quota),
12331            ));
12332        }
12333    }
12334
12335    // A stalled quorum already has its own recovery checkpoint. Refresh
12336    // its missing seats before deciding whether it can resume.
12337    if state.status != RunStatus::Stalled
12338        && ctx.node != "deliberate"
12339        && n > 0
12340        && losses.len() == n
12341        && done.iter().all(|r| r.as_ref().is_some_and(Result::is_err))
12342    {
12343        block_machine_outage(state, ctx.node, losses);
12344        state.quota.append(losses);
12345    }
12346
12347    seats
12348        .into_iter()
12349        .zip(done)
12350        .zip(nudges)
12351        .map(|((seat, res), attempts)| {
12352            (
12353                seat,
12354                res.unwrap_or_else(|| Err(anyhow::anyhow!("no attempt was made"))),
12355                attempts,
12356            )
12357        })
12358        .collect()
12359}
12360
12361/// A node with no available agent has no task verdict. Preserve the node
12362/// checkpoint and record why a subsequent explicit resume is needed.
12363pub(crate) fn block_machine_outage(state: &mut RunState, node: &str, losses: &[QuotaLoss]) {
12364    let mut auth: Vec<_> = losses
12365        .iter()
12366        .filter(|loss| loss.cause == agent::QuotaCause::Authentication)
12367        .map(|loss| loss.agent.clone())
12368        .collect();
12369    auth.sort();
12370    auth.dedup();
12371    let (kind, detail) = if auth.is_empty() {
12372        (
12373            "agent usage limit",
12374            "All seats reached their agent usage limits; resume after usage is available"
12375                .to_owned(),
12376        )
12377    } else {
12378        (
12379            "agent authentication",
12380            format!(
12381                "Agents {} cannot authenticate; re-authenticate these agents, then resume the held task",
12382                auth.join(", ")
12383            ),
12384        )
12385    };
12386    state.resource_block = Some(crate::run::ResourceBlock {
12387        node: node.to_owned(),
12388        kind: kind.to_owned(),
12389        cause: crate::run::ResourceBlockCause::Other,
12390        detail: detail.clone(),
12391        at: Timestamp::now(),
12392    });
12393    state.event(node, detail);
12394}
12395
12396/// Did the wave end without asking any agent (see [`block_wave`])?
12397fn wave_blocked(results: &[(usize, SeatState, AgentOutcome)]) -> bool {
12398    results
12399        .iter()
12400        .any(|(_, _, o)| matches!(o, AgentOutcome::ResourceBlocked(_)))
12401}
12402
12403/// Settle a wave that never spawned anything: every job answers
12404/// [`AgentOutcome::ResourceBlocked`], its seat leaves `active`, and nothing
12405/// else about the seat (session, history, quota) is touched.
12406fn block_wave(
12407    jobs: Vec<SeatJob>,
12408    state: &mut RunState,
12409    node: &str,
12410    attempt: usize,
12411    why: &str,
12412) -> Vec<(usize, SeatState, AgentOutcome)> {
12413    state.resource_wait = None;
12414    state
12415        .active
12416        .retain(|_, a| !(a.node == node && a.attempt == attempt));
12417    if let Err(e) = state.save() {
12418        tracing::warn!("could not persist a resource-blocked wave: {e:#}");
12419    }
12420    jobs.into_iter()
12421        .enumerate()
12422        .map(|(i, j)| (i, j.seat, AgentOutcome::ResourceBlocked(why.to_owned())))
12423        .collect()
12424}
12425
12426/// Acquire the shared build cache's lease, waiting out contention within
12427/// `budget` (never past it — see AGENTS.md's build-cache section on why an
12428/// unbounded wait is never acceptable).
12429///
12430/// A first, non-blocking check happens before ever waiting; if it finds the
12431/// lease busy, that fact is logged as a `verify` event *and* flushed with
12432/// [`RunState::save`] immediately — not only once the wait finally succeeds
12433/// or gives up — so a `magi show` run by a different process while this one
12434/// is still waiting reads a `run.json` that says so, rather than whatever it
12435/// looked like before the wait started. The same applies to the terminal
12436/// failure: logged and saved before this returns `Err`, so a caller that
12437/// could not get the lease at all still leaves a legible record of why.
12438async fn acquire_cache_lease(
12439    state: &mut RunState,
12440    cache_dir: &Path,
12441    owner: &crate::cache::Owner,
12442    budget: Duration,
12443    node: &str,
12444    context: &str,
12445    cancel: &(dyn Fn() -> bool + Sync),
12446) -> Result<Option<crate::cache::Guard>> {
12447    let home = crate::run::home();
12448    let kind = if crate::build_target::isolated(&state.config) {
12449        crate::build_target::KIND
12450    } else {
12451        "shared build cache"
12452    };
12453    let started = Instant::now();
12454    let busy = match crate::cache::try_acquire(&home, cache_dir, owner) {
12455        Ok(crate::cache::AcquireOutcome::Acquired(g)) => return Ok(Some(g)),
12456        Ok(crate::cache::AcquireOutcome::Busy(busy)) => busy,
12457        Err(e) => {
12458            state.event(
12459                "verify",
12460                format!(
12461                    "{context}: could not check the {kind} at {}: {e:#}",
12462                    cache_dir.display()
12463                ),
12464            );
12465            if let Err(e2) = state.save() {
12466                tracing::warn!("could not persist a cache-check failure: {e2:#}");
12467            }
12468            return Err(anyhow::Error::new(CacheCheckError(format!("{e:#}"))));
12469        }
12470    };
12471    state.event(
12472        "verify",
12473        format!(
12474            "{context}: waiting for the {kind} at {} ({})",
12475            cache_dir.display(),
12476            busy.describe()
12477        ),
12478    );
12479    // Seats of this node are waiting, not running: say so, so the countdown a
12480    // reader sees only ever measures an agent that has been spawned.
12481    state.resource_wait = Some(crate::run::ResourceWait {
12482        node: context.to_owned(),
12483        kind: kind.to_owned(),
12484        holder: format!("{}: {}", cache_dir.display(), busy.describe()),
12485        since: Timestamp::now(),
12486        limit_secs: budget.as_secs(),
12487    });
12488    if let Err(e) = state.save() {
12489        tracing::warn!("could not persist a cache wait: {e:#}");
12490    }
12491    let remaining = budget.saturating_sub(started.elapsed());
12492    let waited = crate::cache::wait_for_unless(
12493        &home,
12494        cache_dir,
12495        owner,
12496        remaining,
12497        Duration::from_secs(5),
12498        cancel,
12499    )
12500    .await;
12501    state.resource_wait = None;
12502    let cause = match &waited {
12503        Ok(Some(_)) => None,
12504        Ok(None) => Some(crate::run::ResourceBlockCause::Cancelled { park: None }),
12505        Err(error)
12506            if error.is::<crate::cache::WaitTimeout>() && kind == crate::build_target::KIND =>
12507        {
12508            Some(crate::run::ResourceBlockCause::IsolatedCacheTimeout {
12509                target: cache_dir.to_owned(),
12510                waited_secs: started.elapsed().as_secs(),
12511                limit_secs: budget.as_secs(),
12512            })
12513        }
12514        Err(error) if error.is::<crate::cache::WaitTimeout>() => {
12515            Some(crate::run::ResourceBlockCause::Timeout {
12516                waited_secs: started.elapsed().as_secs(),
12517                limit_secs: budget.as_secs(),
12518            })
12519        }
12520        Err(_) => Some(crate::run::ResourceBlockCause::Other),
12521    };
12522    if let Some(cause) = cause {
12523        let detail = match &waited {
12524            Ok(_) => "the wait for the build cache was cancelled".to_owned(),
12525            Err(error) => format!("{error:#}"),
12526        };
12527        state.resource_block = Some(crate::run::ResourceBlock {
12528            cause,
12529            node: node.to_owned(),
12530            kind: kind.into(),
12531            detail: format!("{}: {detail}", cache_dir.display()),
12532            at: Timestamp::now(),
12533        });
12534        state.event(
12535            "resource",
12536            state.resource_block.as_ref().unwrap().description(),
12537        );
12538    }
12539    if let Err(error) = state.save() {
12540        tracing::warn!("could not persist cache acquisition outcome: {error:#}");
12541    }
12542    waited
12543}
12544
12545/// The lease state could not be read at all (unreadable lease file, a
12546/// permission problem). Unlike a busy lease that outlasts its bound, nothing is
12547/// known to be contended, so a wave degrades to running without a shared cache
12548/// instead of stopping on a hold that [`crate::triage`] could never release.
12549#[derive(Debug)]
12550struct CacheCheckError(String);
12551
12552impl std::fmt::Display for CacheCheckError {
12553    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12554        f.write_str(&self.0)
12555    }
12556}
12557
12558impl std::error::Error for CacheCheckError {}
12559
12560/// Keep a specific acquisition outcome when the caller adds command evidence.
12561fn record_cache_error(state: &mut RunState, node: &str, error: &anyhow::Error) {
12562    let kind = if crate::build_target::isolated(&state.config) {
12563        crate::build_target::KIND
12564    } else {
12565        "shared build cache"
12566    };
12567    state
12568        .resource_block
12569        .get_or_insert_with(|| crate::run::ResourceBlock {
12570            cause: crate::run::ResourceBlockCause::Other,
12571            node: node.to_owned(),
12572            kind: kind.into(),
12573            detail: format!("{error:#}"),
12574            at: Timestamp::now(),
12575        });
12576    if let Err(error) = state.save() {
12577        tracing::warn!("could not persist cache resource block: {error:#}");
12578    }
12579}
12580
12581tokio::task_local! {
12582    static VERIFY_TARGET: PathBuf;
12583}
12584
12585/// Run `body` — a verify command batch — while holding the shared build
12586/// cache's lease, so this run's own full verification (`e2e`, `gate`) can
12587/// never interleave with another borrower's build against the same
12588/// `CARGO_TARGET_DIR`: a different run, a lingering reviewer past its
12589/// timeout, or a human's own `magi review`. See the `cache` module doc for
12590/// why this matters more than Cargo's own per-target locking covers — two
12591/// *different* worktrees building the same package name/version into one
12592/// cache directory is a staleness bug, not a lock contention one.
12593///
12594/// Cache acquisition has its own bound, `timeout_resource_wait`, just as
12595/// agent waves do. Repository scheduling also has its own bounded,
12596/// cancellable resource-wait policy. Contention must not consume the
12597/// verification budget: `body` receives the full `budget` after both leases
12598/// are acquired and the cache is fresh. Without a shared cache, only
12599/// repository coordination is acquired before handing over the full budget.
12600///
12601/// A lease that cannot be acquired within the resource wait is reported as a single
12602/// synthetic [`CommandOutcome`] (`code: None`) rather than silently skipping
12603/// verification — the same shape a spawn failure already takes in
12604/// [`run_commands`], so a caller need not special-case it.
12605#[allow(clippy::too_many_arguments)]
12606async fn with_cache_lease<'s, F, Fut>(
12607    state: &'s mut RunState,
12608    cache_dir: Option<&Path>,
12609    node: &str,
12610    seat: &str,
12611    worktree: &Path,
12612    head: &str,
12613    budget: Duration,
12614    context: &str,
12615    wait: &crate::repo_lock::WaitPolicy,
12616    body: F,
12617) -> Result<(Vec<CommandOutcome>, bool)>
12618where
12619    F: FnOnce(&'s mut RunState, Duration) -> Fut,
12620    Fut: std::future::Future<Output = (Vec<CommandOutcome>, bool, Vec<u32>)>,
12621{
12622    // Match editing waves: cache first, repository second. In particular,
12623    // pre_gate must never hold the repository while waiting for a wave's cache.
12624    let started = Instant::now();
12625    let home = crate::run::home();
12626    let isolated = crate::build_target::isolated(&state.config);
12627    let planned_target = if isolated {
12628        let plan = (|| -> Result<PathBuf> {
12629            crate::build_target::supports(&state.config)?;
12630            crate::build_target::resolve(&home, worktree)
12631        })();
12632        match plan {
12633            Ok(path) => Some(path),
12634            Err(error) => {
12635                record_cache_error(state, node, &error);
12636                return Ok((
12637                    vec![CommandOutcome {
12638                        command: "(planning isolated build cache)".into(),
12639                        code: None,
12640                        output_tail: format!("{error:#}"),
12641                        duration_ms: 0,
12642                        resource_blocked: true,
12643                        ..Default::default()
12644                    }],
12645                    false,
12646                ));
12647            }
12648        }
12649    } else {
12650        None
12651    };
12652    let cache_dir = planned_target.as_deref().or(cache_dir);
12653    let resource_limit = Duration::from_secs(state.config.graph.timeout_resource_wait);
12654    let guard = if let Some(cache_dir) = cache_dir {
12655        let owner = crate::cache::Owner::here(&state.id, node, seat, worktree, head);
12656        match acquire_cache_lease(
12657            state,
12658            cache_dir,
12659            &owner,
12660            resource_limit,
12661            node,
12662            context,
12663            &|| wait.cancelled(),
12664        )
12665        .await
12666        .and_then(|g| {
12667            g.ok_or_else(|| anyhow::anyhow!("the wait for the build cache was cancelled"))
12668        }) {
12669            Ok(g) => Some(g),
12670            Err(e) => {
12671                record_cache_error(state, node, &e);
12672                return Ok((
12673                    vec![CommandOutcome {
12674                        command: if isolated {
12675                            "(waiting for the isolated build cache)"
12676                        } else {
12677                            "(waiting for the shared build cache)"
12678                        }
12679                        .into(),
12680                        code: None,
12681                        output_tail: e.to_string(),
12682                        duration_ms: started.elapsed().as_millis() as u64,
12683                        resource_blocked: true,
12684                        ..Default::default()
12685                    }],
12686                    false,
12687                ));
12688            }
12689        }
12690    } else {
12691        None
12692    };
12693    let _coordination = coordinate_operation(state, worktree, wait).await?;
12694    if let Some(path) = &planned_target {
12695        state.event(node, format!("isolated build target: {}", path.display()));
12696    }
12697    if let Some(cache_dir) = cache_dir.filter(|_| !isolated) {
12698        let identity = crate::cache::Identity::new(worktree, head);
12699        let fresh = crate::cache::ensure_fresh(
12700            &home,
12701            cache_dir,
12702            &identity,
12703            &state.config.verify.cargo_manifests(),
12704        );
12705        if let Err(e) = fresh {
12706            record_cache_error(state, node, &e);
12707            state.event(
12708                "verify",
12709                format!(
12710                    "{context}: could not confirm the build cache matches {} at {}: {e:#}",
12711                    worktree.display(),
12712                    short(head)
12713                ),
12714            );
12715            if let Some(guard) = guard {
12716                guard.release();
12717            }
12718            return Ok((
12719                vec![CommandOutcome {
12720                    command: "(confirming the build cache is fresh)".into(),
12721                    code: None,
12722                    output_tail: e.to_string(),
12723                    duration_ms: started.elapsed().as_millis() as u64,
12724                    resource_blocked: true,
12725                    ..Default::default()
12726                }],
12727                false,
12728            ));
12729        }
12730    }
12731    let future = body(state, budget);
12732    let (outcomes, retried, timed_out_pids) = if let Some(target) = planned_target {
12733        VERIFY_TARGET.scope(target, future).await
12734    } else {
12735        future.await
12736    };
12737    if !timed_out_pids.is_empty() {
12738        wait_for_timed_out_children_to_die(&timed_out_pids).await;
12739    }
12740    // Drop repository coordination before releasing the cache, reversing the
12741    // acquisition order. A cancelled/error future also drops both guards.
12742    drop(_coordination);
12743    if let Some(guard) = guard {
12744        guard.release();
12745    }
12746    Ok((outcomes, retried))
12747}
12748
12749/// Poll `pids` — commands [`run_commands`] reports as still running when its
12750/// own timeout elapsed — until every one is confirmed gone, or
12751/// [`LEASE_RELEASE_MAX_WAIT`] passes, whichever comes first.
12752///
12753/// Real confirmation where confirmation is possible, not a substitute for
12754/// full process-tree observation: a grandchild the timed-out process spawned
12755/// and that survives independently of it is invisible to a pid check the
12756/// same way it always was, and continuing to observe and collect *that*
12757/// stays a different piece of work with its own owner. This only narrows a
12758/// fixed blind wait into an actual check of the pids this process does know
12759/// about.
12760async fn wait_for_timed_out_children_to_die(pids: &[u32]) {
12761    wait_for_pids_with(
12762        pids,
12763        crate::proc::pid_alive,
12764        LEASE_RELEASE_POLL,
12765        LEASE_RELEASE_MAX_WAIT,
12766    )
12767    .await;
12768}
12769
12770/// [`wait_for_timed_out_children_to_die`] with its liveness query, poll
12771/// interval and ceiling supplied by the caller, so the polling *logic* -
12772/// returns as soon as every pid reports dead, gives up at the ceiling
12773/// otherwise - is testable on millisecond durations without asking the real
12774/// OS about a pid at all.
12775async fn wait_for_pids_with<F: Fn(u32) -> bool>(
12776    pids: &[u32],
12777    alive: F,
12778    poll: Duration,
12779    max_wait: Duration,
12780) {
12781    let deadline = Instant::now() + max_wait;
12782    loop {
12783        if pids.iter().all(|&pid| !alive(pid)) {
12784            return;
12785        }
12786        if Instant::now() >= deadline {
12787            return;
12788        }
12789        tokio::time::sleep(poll).await;
12790    }
12791}
12792
12793/// Are any of `outcomes` [`CommandOutcome::resource_blocked`] - magi's own
12794/// admission that it could not even get a verify command to run, as opposed
12795/// to evidence the command actually produced? A caller that would otherwise
12796/// read a resource-blocked outcome as a red command must check this first:
12797/// see [`Runner::gate`], which retries rather than records `Blocked` when
12798/// this is true.
12799fn verify_inconclusive(outcomes: &[CommandOutcome]) -> bool {
12800    outcomes.iter().any(|o| o.resource_blocked)
12801}
12802
12803/// What [`Runner::gate_fix_round`] decided.
12804pub(crate) enum GateFix {
12805    /// The tree changed and `verify.e2e` is still green: run the gate again.
12806    Retry,
12807    /// No more rounds, nothing to fix, or the fix did not hold: the gate's
12808    /// last failure stands and the run ends blocked.
12809    Stop,
12810    /// `verify.e2e` could not run after the fix (magi's own contention):
12811    /// decide nothing now, a later reentry retries.
12812    Defer,
12813}
12814
12815/// Is every red command in `outcomes` an ordinary failure the code could
12816/// explain: it ran, exited non-zero, and said something?
12817///
12818/// A timeout, a spawn failure and a killed process all leave `code` `None`;
12819/// 126 / 127 are the POSIX shell's "cannot execute" / "not found". Output-free
12820/// exits carry nothing for a fixer to act on. Language-agnostic on purpose:
12821/// what the command is stays the gate's business.
12822pub(crate) fn gate_fixable(outcomes: &[CommandOutcome]) -> bool {
12823    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
12824    red.peek().is_some()
12825        && red.all(|o| {
12826            !o.resource_blocked
12827                && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
12828                && !o.output_tail.trim().is_empty()
12829        })
12830}
12831
12832/// Describe one verify command's outcome for the event log, distinguishing a
12833/// build/link failure — the toolchain never produced a binary to run — from
12834/// an actual test failure, since only the latter is a verdict on the patch.
12835fn e2e_outcome_label(o: &CommandOutcome) -> String {
12836    if o.ok() {
12837        return "pass".to_owned();
12838    }
12839    let reason = if o.build_failed() {
12840        format!("COULD NOT RUN ({:?}, build/link failure)", o.code)
12841    } else {
12842        format!("FAIL ({:?})", o.code)
12843    };
12844    format!(
12845        "{reason}\n{}",
12846        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
12847    )
12848}
12849
12850/// Does `outcomes` hold a failure worth one more run on the same commit?
12851///
12852/// Only an ordinary test result qualifies: every red command ran, exited
12853/// non-zero and said which way (not a build/link failure, a timeout or kill,
12854/// a spawn failure, the shell's own 126 / 127, or a resource block). Those are
12855/// evidence about the machine or the toolchain, never about a flaky test.
12856fn rerunnable_failure(outcomes: &[CommandOutcome]) -> bool {
12857    let mut red = outcomes.iter().filter(|o| !o.ok()).peekable();
12858    red.peek().is_some()
12859        && !verify_inconclusive(outcomes)
12860        && red.all(|o| {
12861            !o.build_failed() && matches!(o.code, Some(c) if c != 0 && c != 126 && c != 127)
12862        })
12863}
12864
12865/// Run `verify.e2e`, retrying once if the first attempt could not build or
12866/// link — a build/link failure is frequently a race against a shared
12867/// `CARGO_TARGET_DIR` (see AGENTS.md), not a verdict on the patch. Emits one
12868/// `verify` event per command, tagged with `context` (normally `"round N"`)
12869/// so the call sites that need this — the ordinary per-round leg in
12870/// `review_loop`, the deferred catch-up run `stop_reviewing` makes before it
12871/// will ever call a round green, `verify_current_head` and the gate-repair
12872/// check — read identically in the event log.
12873///
12874/// A failure that is a test result (see [`rerunnable_failure`]) is believed
12875/// only after the failed commands have run once more on the same commit, in
12876/// the same worktree and — because the caller holds it around this whole
12877/// function — under the same cache lease, with a full `timeout` of their own
12878/// (`[graph] rerun_failed_e2e`). A command that passes the second time is a
12879/// flake: the head is verified, the first failure is recorded and filed
12880/// (`crate::flake`, `RunState::verify_flakes`). A command that fails again
12881/// stays red and records a structured [`crate::verify_evidence::RerunComparison`]
12882/// preserving bounded evidence and artifact references for both attempts;
12883/// it claims a matching reproduction only when both attempts yield identical
12884/// confirmed terminal test failures. One verification is therefore run at most
12885/// three times: the build/link retry, then this one rerun. `round` is the
12886/// review round the verification belongs to, if any.
12887async fn run_e2e_with_retry(
12888    state: &mut RunState,
12889    shell: &[String],
12890    commands: &[String],
12891    worktree: &Path,
12892    timeout: Duration,
12893    context: &str,
12894    round: Option<usize>,
12895) -> (Vec<CommandOutcome>, bool, Vec<u32>) {
12896    let (mut e2e, mut timed_out_pids) = run_commands(
12897        state, "verify", "e2e", 0, shell, commands, worktree, timeout,
12898    )
12899    .await;
12900    for o in &e2e {
12901        state.event(
12902            "verify",
12903            format!("{context}: `{}` -> {}", o.command, e2e_outcome_label(o)),
12904        );
12905    }
12906    // A build/link failure is not a verdict on the patch — it is frequently a
12907    // race against a shared `CARGO_TARGET_DIR` (see AGENTS.md). Give verify
12908    // one retry before letting a red like that decide the round.
12909    let verify_retried = e2e.iter().any(CommandOutcome::build_failed);
12910    if verify_retried {
12911        state.event(
12912            "verify",
12913            format!(
12914                "{context}: verify could not build/link, not a test result — retrying once \
12915                 before concluding"
12916            ),
12917        );
12918        let retried = run_commands(
12919            state, "verify", "e2e", 1, shell, commands, worktree, timeout,
12920        )
12921        .await;
12922        e2e = retried.0;
12923        // Both attempts' timeouts matter, not just the last one: the first
12924        // attempt's descendants may still be alive alongside the retry's.
12925        timed_out_pids.extend(retried.1);
12926        for o in &e2e {
12927            state.event(
12928                "verify",
12929                format!(
12930                    "{context}: retry `{}` -> {}",
12931                    o.command,
12932                    e2e_outcome_label(o)
12933                ),
12934            );
12935        }
12936    }
12937    if state.config.graph.rerun_failed_e2e && rerunnable_failure(&e2e) {
12938        let failed: Vec<usize> = (0..e2e.len()).filter(|&i| !e2e[i].ok()).collect();
12939        let rerun_commands: Vec<String> = failed.iter().map(|&i| e2e[i].command.clone()).collect();
12940        let head = git::rev_parse(worktree, "HEAD").await.unwrap_or_default();
12941        state.event(
12942            "verify",
12943            format!(
12944                "{context}: {} failed with a test result — running it once more on the same \
12945                 commit {} before deciding",
12946                rerun_commands
12947                    .iter()
12948                    .map(|c| format!("`{c}`"))
12949                    .collect::<Vec<_>>()
12950                    .join(", "),
12951                short(&head)
12952            ),
12953        );
12954        let (second, pids) = run_commands(
12955            state,
12956            "verify",
12957            "e2e",
12958            1 + usize::from(verify_retried),
12959            shell,
12960            &rerun_commands,
12961            worktree,
12962            timeout,
12963        )
12964        .await;
12965        timed_out_pids.extend(pids);
12966        for o in &second {
12967            state.event(
12968                "verify",
12969                format!(
12970                    "{context}: rerun `{}` -> {}",
12971                    o.command,
12972                    e2e_outcome_label(o)
12973                ),
12974            );
12975        }
12976        for (slot, &i) in failed.iter().enumerate() {
12977            let Some(again) = second.get(slot) else {
12978                break;
12979            };
12980            let first = std::mem::replace(&mut e2e[i], again.clone());
12981            if again.ok() {
12982                let signature = crate::flake::signature(&first.output_tail, first.code);
12983                let flake = crate::run::VerifyFlake {
12984                    round,
12985                    context: context.to_owned(),
12986                    head: head.clone(),
12987                    command: first.command.clone(),
12988                    first_failure: summarize_verify(&first.output_tail, EVENT_OUTPUT_TAIL),
12989                    fingerprint: crate::flake::fingerprint(&state.repo, &signature),
12990                    at: Timestamp::now(),
12991                    task: None,
12992                    filed: false,
12993                    filing_error: None,
12994                };
12995                crate::flake::record(state, flake, &signature.label, &crate::queue::Queue::open());
12996            } else if !again.resource_blocked {
12997                let comparison = crate::verify_evidence::compare_attempts(&head, &first, again);
12998                let message = crate::verify_evidence::rerun_event_message(
12999                    context,
13000                    &e2e[i].command,
13001                    &comparison,
13002                );
13003                e2e[i].rerun_comparison = Some(comparison);
13004                state.event("verify", message);
13005            }
13006        }
13007    }
13008    (e2e, verify_retried, timed_out_pids)
13009}
13010
13011/// Run configured shell commands in `cwd`, in order. The second element is
13012/// the pid of every command that hit `timeout` and was still running when
13013/// this stopped waiting on it (best-effort: `None` when the platform did not
13014/// hand one back) — see [`with_cache_lease`]'s use of it for why a caller
13015/// that releases a shared resource afterward needs to know.
13016///
13017/// Records `task` into [`RunState::active`] at every command boundary
13018/// (`RunState::task_command`) and clears it once the whole list has run
13019/// (`RunState::task_finished`) — a `verify.e2e` / `verify.gate` list can run
13020/// for minutes with no seat and no output of its own to show for it (see
13021/// `CommandOutcome`'s doc on why an empty `e2e`/`gate` alone cannot be told
13022/// apart from "not yet run" without this), and this is the only place that
13023/// knows which command is running right now and how many are left. Three
13024/// saves per command — start, not per second — matching the same "only at a
13025/// boundary" rule [`wave`] already follows for seats.
13026#[allow(clippy::too_many_arguments)]
13027async fn run_commands(
13028    state: &mut RunState,
13029    node: &str,
13030    task: &str,
13031    attempt: usize,
13032    shell: &[String],
13033    commands: &[String],
13034    cwd: &Path,
13035    timeout: Duration,
13036) -> (Vec<CommandOutcome>, Vec<u32>) {
13037    let isolated = crate::build_target::isolated(&state.config);
13038    if isolated && let Some(block) = &state.resource_block {
13039        return (
13040            vec![CommandOutcome {
13041                command: "(isolated build admission)".into(),
13042                code: None,
13043                output_tail: block.description(),
13044                duration_ms: 0,
13045                resource_blocked: true,
13046                ..Default::default()
13047            }],
13048            Vec::new(),
13049        );
13050    }
13051    if commands.is_empty() {
13052        // Nothing to mark as running and nothing to clear — an empty list
13053        // means "not configured", and touching `active` (or the disk) over
13054        // that would be a write for every round of a repo with no
13055        // `verify.e2e` / `verify.gate` commands at all.
13056        return (Vec::new(), Vec::new());
13057    }
13058    let mut out = Vec::new();
13059    let mut timed_out_pids = Vec::new();
13060    let total = commands.len();
13061    for (idx, command) in commands.iter().enumerate() {
13062        state.task_command(task, node, attempt, command, idx + 1, total, timeout);
13063        if let Err(e) = state.save() {
13064            tracing::warn!("could not persist an in-progress {task} command: {e:#}");
13065        }
13066        let started = Instant::now();
13067        let mut cmd = tokio::process::Command::new(&shell[0]);
13068        cmd.quiet();
13069        // Verify the checkout as a standalone caller. Worker ownership and
13070        // pinned executable selection belong to this driver, not to tests or
13071        // tools it runs. Preserve home/seat context and Running's containment.
13072        for key in crate::worker::INVOCATION_ENV {
13073            cmd.env_remove(key);
13074        }
13075        cmd.env_remove(crate::build_id::EXPECT_ENV);
13076        cmd.args(&shell[1..])
13077            .current_dir(cwd)
13078            .stdin(std::process::Stdio::null())
13079            .stdout(std::process::Stdio::piped())
13080            .stderr(std::process::Stdio::piped())
13081            .kill_on_drop(true);
13082        let mut outputs = Vec::new();
13083        let mut cache = None;
13084        let home = crate::run::home();
13085        let head = if isolated {
13086            Some(git::rev_parse(cwd, "HEAD").await)
13087        } else {
13088            None
13089        };
13090        let protected = (|| -> Result<()> {
13091            crate::incremental::configure(&mut cmd, cwd)?;
13092            cache = if isolated {
13093                let target = VERIFY_TARGET
13094                    .try_with(Clone::clone)
13095                    .context("isolated verification has no target lease")?;
13096                cmd.arg(crate::build_target::command::normalize(command)?);
13097                crate::build_target::command::configure(&mut cmd, &target)?;
13098                Some(target)
13099            } else {
13100                crate::build_target::command::clear(&mut cmd)?;
13101                cmd.arg(command);
13102                state.config.cache_dir()
13103            };
13104            let mut paths = vec![cwd.to_owned()];
13105            if let Some(cache) = &cache {
13106                paths.push(cache.clone());
13107            }
13108            let admit = if isolated {
13109                crate::retention::OutputLease::admit_isolated
13110            } else {
13111                crate::retention::OutputLease::admit
13112            };
13113            outputs.extend(admit(&home, &paths, state.config.disk.min_free_bytes)?);
13114            if let Some(guard) = crate::retention::OutputLease::borrow(cwd)? {
13115                outputs.push(guard);
13116            }
13117            if let Some(cache) = &cache {
13118                outputs.push(crate::retention::OutputLease::cache(
13119                    &crate::run::home(),
13120                    cache,
13121                    false,
13122                )?);
13123                if let Some(head) = head {
13124                    crate::build_target::ensure_fresh(&home, cache, cwd, &head?, &state.config)?;
13125                    if task == "pre_gate" {
13126                        crate::cache::invalidate_identity(&home, cache);
13127                    }
13128                }
13129            }
13130            Ok(())
13131        })();
13132        if let Err(e) = protected {
13133            let detail = format!("execution admission unavailable: {e:#}");
13134            state.resource_block = Some(crate::run::ResourceBlock {
13135                cause: crate::run::ResourceBlockCause::Other,
13136                node: node.to_owned(),
13137                kind: if detail.contains("disk admission") {
13138                    "disk admission"
13139                } else {
13140                    "output ownership"
13141                }
13142                .to_owned(),
13143                detail: detail.clone(),
13144                at: Timestamp::now(),
13145            });
13146            out.push(CommandOutcome {
13147                command: command.clone(),
13148                code: None,
13149                output_tail: detail,
13150                duration_ms: 0,
13151                resource_blocked: true,
13152                ..Default::default()
13153            });
13154            break;
13155        }
13156        let spawned = if isolated {
13157            crate::seat_process::Running::spawn_build(cmd, None, outputs)
13158        } else {
13159            crate::seat_process::Running::spawn(cmd, None, outputs)
13160        };
13161        let (code, out_text, err_text, body) = match spawned {
13162            Ok(mut running) => {
13163                let pid = running.child().id();
13164                let (stdout, out_reader) = agent::drain(running.child().stdout.take());
13165                let (stderr, err_reader) = agent::drain(running.child().stderr.take());
13166                let mut paths = vec![cwd.to_owned()];
13167                if let Some(cache) = cache {
13168                    paths.push(cache);
13169                }
13170                let mut pressure = None;
13171                let status = tokio::select! {
13172                    status = tokio::time::timeout(timeout, running.child().wait()) => Some(status),
13173                    reason = crate::retention::emergency(paths, state.config.disk.min_free_bytes, isolated) => {
13174                        pressure = Some(reason); None
13175                    }
13176                };
13177                let (code, failure) = match status {
13178                    Some(Ok(Ok(status))) => (
13179                        status.code(),
13180                        status
13181                            .code()
13182                            .is_none()
13183                            .then(|| format!("command terminated: {status}")),
13184                    ),
13185                    Some(Ok(Err(error))) => {
13186                        (None, Some(format!("failed waiting for command: {error}")))
13187                    }
13188                    Some(Err(_)) => {
13189                        // Leased cleanup confirms process-tree death itself.
13190                        // Unleased commands still need the caller's PID check
13191                        // after kill-on-drop, before releasing cache ownership.
13192                        if !running.coordinated()
13193                            && let Some(pid) = pid
13194                        {
13195                            timed_out_pids.push(pid);
13196                        }
13197                        (
13198                            None,
13199                            Some(format!("timed out after {}s", timeout.as_secs())),
13200                        )
13201                    }
13202                    None => (None, None),
13203                };
13204                running.finish().await;
13205                if let Some(reason) = pressure {
13206                    state.resource_block = Some(crate::run::ResourceBlock {
13207                        cause: crate::run::ResourceBlockCause::Other,
13208                        node: node.to_owned(),
13209                        kind: "disk pressure".to_owned(),
13210                        detail: reason.clone(),
13211                        at: Timestamp::now(),
13212                    });
13213                    out.push(CommandOutcome {
13214                        command: command.clone(),
13215                        code: None,
13216                        output_tail: reason,
13217                        duration_ms: started.elapsed().as_millis() as u64,
13218                        resource_blocked: true,
13219                        ..Default::default()
13220                    });
13221                    break;
13222                }
13223                let out_text = agent::collect(&stdout, out_reader, Duration::from_secs(2)).await;
13224                let err_text = agent::collect(&stderr, err_reader, Duration::from_secs(2)).await;
13225                let mut body = out_text.clone();
13226                body.push_str(&err_text);
13227                if let Some(failure) = failure {
13228                    body.push('\n');
13229                    body.push_str(&failure);
13230                }
13231                (code, out_text, err_text, body)
13232            }
13233            Err(e) if isolated => {
13234                let e = anyhow::Error::new(e)
13235                    .context(format!("could not start managed build `{}`", shell[0]));
13236                record_cache_error(state, node, &e);
13237                out.push(CommandOutcome {
13238                    command: command.clone(),
13239                    code: None,
13240                    output_tail: format!("{e:#}"),
13241                    duration_ms: 0,
13242                    resource_blocked: true,
13243                    ..Default::default()
13244                });
13245                break;
13246            }
13247            Err(e) => (
13248                None,
13249                String::new(),
13250                String::new(),
13251                format!("failed to spawn `{}`: {e}", shell[0]),
13252            ),
13253        };
13254        let mut summary = summarize_verify(&body, crate::run::VERIFY_SUMMARY);
13255        let mut artifact = None;
13256        if !body.is_empty() {
13257            // The full text is kept whatever the summary dropped. A fresh
13258            // name per command so a resume or retry never overwrites an
13259            // earlier run's output. A failed write changes no verdict.
13260            match crate::run::write_verification_artifact(state, task, &body) {
13261                Ok(name) => {
13262                    let rel = format!("artifacts/{name}");
13263                    if summary != body {
13264                        summary = format!("[full output: {rel}]\n{summary}");
13265                    }
13266                    artifact = Some(rel);
13267                }
13268                Err(e) => {
13269                    let warning = format!("could not save the full {task} output: {e:#}");
13270                    tracing::warn!("{warning}");
13271                    state.event(node, warning);
13272                    if summary != body {
13273                        summary = format!("[full output could not be saved: {e:#}]\n{summary}");
13274                    }
13275                }
13276            }
13277        }
13278        let resource_blocked = code != Some(0) && body.contains(crate::incremental::BLOCKED);
13279        let mut outcome = CommandOutcome {
13280            command: command.clone(),
13281            code,
13282            output_tail: summary,
13283            duration_ms: started.elapsed().as_millis() as u64,
13284            resource_blocked,
13285            artifact,
13286            failure_evidence: None,
13287            rerun_comparison: None,
13288        };
13289        if !outcome.ok() && !outcome.resource_blocked {
13290            outcome.failure_evidence = Some(crate::verify_evidence::extract_streams(
13291                code,
13292                outcome.build_failed(),
13293                &out_text,
13294                &err_text,
13295            ));
13296        }
13297        out.push(outcome);
13298        if resource_blocked {
13299            state.resource_block = Some(crate::run::ResourceBlock {
13300                cause: crate::run::ResourceBlockCause::Other,
13301                node: node.to_owned(),
13302                kind: "incremental cache admission".into(),
13303                detail: body,
13304                at: Timestamp::now(),
13305            });
13306            break;
13307        }
13308    }
13309    state.task_finished(task);
13310    if let Err(e) = state.save() {
13311        tracing::warn!("could not persist the end of {task}: {e:#}");
13312    }
13313    (out, timed_out_pids)
13314}
13315
13316/// The shell command line `mode = "none"` prints — in `magi show`'s `merge`
13317/// section (`report::run`) and in the `merge` event this node records — for
13318/// the operator to run by hand.
13319///
13320/// Built from [`MergeStyle`] rather than always `git merge --no-ff`: a base
13321/// branch whose ruleset forbids merge commits (GitHub's "must not contain
13322/// merge commits", or "require linear history") rejects the push a `--no-ff`
13323/// merge would produce, which is exactly the guidance this function replaces.
13324/// `message`'s first line becomes the squash commit's subject, matching the
13325/// note `report::run` prints alongside this command — see that function for
13326/// why an explicit subject is not optional there.
13327fn manual_merge_command(style: MergeStyle, repo: &Path, branch: &str, message: &str) -> String {
13328    let repo = repo.display();
13329    match style {
13330        MergeStyle::Merge => format!("git -C {repo} merge --no-ff {branch}"),
13331        MergeStyle::Squash => {
13332            // The subject sits inside double quotes, and a title an agent
13333            // wrote may carry the characters that break out of them.
13334            let subject = message
13335                .lines()
13336                .next()
13337                .unwrap_or(branch)
13338                .replace(['\\', '"', '$', '`'], "");
13339            format!(
13340                "git -C {repo} merge --squash {branch} && git -C {repo} commit -m \"{subject}\""
13341            )
13342        }
13343        MergeStyle::Rebase => format!("git -C {repo} merge --ff-only {branch}"),
13344    }
13345}
13346
13347/// GitHub's `createPullRequest` GraphQL mutation, which `gh pr create` calls
13348/// under the hood, rejects a `title` over 256 characters and the whole
13349/// command fails — no PR at all, for a run whose body was otherwise fine
13350/// (this is what happened to run 2963; see AGENTS.md). 240 leaves room below
13351/// that limit: titles are counted in `chars()` (Unicode scalars), which is not
13352/// always how GitHub counts. [`english_title`] keeps its trailing `...` inside
13353/// this bound. It is a margin, not a guarantee — a title packed
13354/// with multi-unit characters could still in principle land close to the
13355/// edge, but a real task title's occasional emoji or accented letter fits
13356/// comfortably inside it.
13357const PR_TITLE_MAX: usize = 240;
13358
13359/// A pull request title from the opening line of `text`, or `None` when that
13360/// line is not English (GitHub text is) or has no letters.
13361///
13362/// A line within `max` is kept as is. A longer one is cut at the end of its
13363/// first sentence when that falls inside `max`, else at a word boundary with a
13364/// plain `...` (ASCII, unlike the `…` `queue::title_from` appends, which would
13365/// make every merely-truncated title look non-English). The language check
13366/// runs on the kept text before any mark is added, so only what GitHub will
13367/// show is judged: an English opening followed by non-ASCII far past the cut
13368/// still passes.
13369fn english_title(text: &str, max: usize, ascii_only: bool) -> Option<String> {
13370    let line = queue::first_line(text)?;
13371    let chars: Vec<char> = line.chars().collect();
13372    let (kept, mark) = if chars.len() <= max {
13373        (line.to_owned(), "")
13374    } else if let Some(end) = sentence_end(&chars, max) {
13375        (chars[..end].iter().collect::<String>(), "")
13376    } else {
13377        let room = max.saturating_sub(3);
13378        // Cut at the last space inside the room; when the char just past the
13379        // room is a space the room already ends on a word.
13380        let cut = if chars[room].is_whitespace() {
13381            room
13382        } else {
13383            chars[..room]
13384                .iter()
13385                .rposition(|c| c.is_whitespace())
13386                .unwrap_or(room)
13387        };
13388        let head: String = chars[..cut].iter().collect();
13389        let head = head.trim_end_matches(|c: char| c.is_whitespace() || ",;:-".contains(c));
13390        (head.to_owned(), "...")
13391    };
13392    if kept.is_empty() {
13393        return None;
13394    }
13395    if ascii_only && (!kept.is_ascii() || !kept.chars().any(|c| c.is_ascii_alphabetic())) {
13396        return None;
13397    }
13398    if !ascii_only && !kept.chars().any(char::is_alphabetic) {
13399        return None;
13400    }
13401    Some(format!("{kept}{mark}"))
13402}
13403
13404/// The char length of the first sentence of `chars` when it ends within `max`
13405/// (the closing `.`/`!`/`?` dropped), skipping very short stubs and common
13406/// abbreviations so `e.g. foo` does not end a title early.
13407fn sentence_end(chars: &[char], max: usize) -> Option<usize> {
13408    const MIN: usize = 20;
13409    for i in MIN..max.min(chars.len()) {
13410        if !matches!(chars[i], '.' | '!' | '?') {
13411            continue;
13412        }
13413        let Some(&next) = chars.get(i + 1) else {
13414            continue;
13415        };
13416        if !next.is_whitespace() {
13417            continue;
13418        }
13419        let after = chars[i + 1..].iter().find(|c| !c.is_whitespace());
13420        if after.is_some_and(|c| c.is_ascii_lowercase()) {
13421            continue;
13422        }
13423        let word: String = chars[..i]
13424            .iter()
13425            .rev()
13426            .take_while(|c| !c.is_whitespace())
13427            .collect::<Vec<_>>()
13428            .into_iter()
13429            .rev()
13430            .collect();
13431        let word = word.to_ascii_lowercase();
13432        if matches!(word.as_str(), "e.g" | "i.e" | "etc" | "vs" | "cf") {
13433            continue;
13434        }
13435        let end = chars[..i]
13436            .iter()
13437            .rposition(|c| !c.is_whitespace())
13438            .map_or(i, |p| p + 1);
13439        return Some(end);
13440    }
13441    None
13442}
13443
13444/// What `merge = "pr"` (and the merge commit of the other modes) says about a
13445/// change: a title and a body describing what was *implemented*, not the task
13446/// that asked for it. A task reads as a request; a reader of the merged
13447/// history wants the change.
13448struct PrMessage {
13449    title: String,
13450    body: String,
13451}
13452
13453impl PrMessage {
13454    /// Title, blank line, body. The first line is the squash/merge commit
13455    /// subject (`manual_merge_command` takes it via `lines().next()`), so it
13456    /// has to stay one sensible line.
13457    fn commit_message(&self) -> String {
13458        format!("{}\n\n{}", self.title, self.body)
13459    }
13460}
13461
13462/// The text after a leading `TITLE:` (any case) on `line`.
13463fn title_marker(line: &str) -> Option<&str> {
13464    let line = line.trim();
13465    let head = line.get(..6)?;
13466    head.eq_ignore_ascii_case("title:")
13467        .then(|| line[6..].trim())
13468}
13469
13470/// The implementer's own one-line title: the `TITLE:` line the implement
13471/// prompt asks for at the top of its SUMMARY. Candidate commits are all
13472/// `magi: candidate X (uncommitted work)`, so a commit subject is never a
13473/// source, and a title that says as much is refused here too.
13474fn summary_title(summary: &str) -> Option<String> {
13475    let first = summary.lines().find(|l| !l.trim().is_empty())?;
13476    let raw = title_marker(first)?;
13477    if raw.is_empty() {
13478        return None;
13479    }
13480    let title = queue::title_from(raw, PR_TITLE_MAX);
13481    let lower = title.to_ascii_lowercase();
13482    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
13483        return None;
13484    }
13485    Some(title)
13486}
13487
13488/// How `open_review`'s instruction begins; see [`landing_title`].
13489const REVIEW_PROMPT_OPENING: &str = "Review the work already on branch";
13490
13491/// Marker `open_review` gives a candidate that nothing in the roster wrote.
13492pub(crate) const EXISTING_BRANCH: &str = "(existing branch)";
13493
13494/// Does this run review work that already existed, rather than implement a
13495/// task? Runs recorded before `reviewed_commits` existed carry only the
13496/// candidate marker.
13497pub(crate) fn is_review_run(state: &RunState) -> bool {
13498    state.reviewed_commits.is_some() || state.candidates.iter().any(|c| c.agent == EXISTING_BRANCH)
13499}
13500
13501/// The title of a review-only run: the subject of the oldest commit under
13502/// review. Later commits are usually fixups, and `instruction` is the review
13503/// prompt, which says nothing about the change. GitHub text is English, so a
13504/// non-ASCII or blank subject yields `None` and the caller's neutral title.
13505fn review_title(state: &RunState) -> Option<String> {
13506    english_subject(
13507        state.reviewed_commits.as_ref()?.first()?,
13508        state.config.graph.github_english(),
13509    )
13510}
13511
13512/// `raw` as a pull request title, or `None` when it is blank, not English
13513/// (GitHub text is), or one of magi's own candidate commit subjects.
13514fn english_subject(raw: &str, ascii_only: bool) -> Option<String> {
13515    let raw = raw.trim();
13516    if raw.is_empty() {
13517        return None;
13518    }
13519    if ascii_only && (!raw.is_ascii() || !raw.chars().any(|c| c.is_ascii_alphabetic())) {
13520        return None;
13521    }
13522    if !ascii_only && !raw.chars().any(char::is_alphabetic) {
13523        return None;
13524    }
13525    let title = queue::title_from(raw, PR_TITLE_MAX);
13526    let lower = title.to_ascii_lowercase();
13527    if lower.starts_with("magi:") || lower.contains("(uncommitted work)") {
13528        return None;
13529    }
13530    Some(title)
13531}
13532
13533/// What a review-only run's branch says about itself, read at the moment the
13534/// pull request is opened.
13535#[derive(Debug, Clone, PartialEq, Eq)]
13536struct BranchFacts {
13537    /// `(subject, body)` of each commit, oldest first.
13538    commits: Vec<(String, String)>,
13539    /// Trimmed `git diff --stat`.
13540    stat: String,
13541}
13542
13543/// Longest diff stat shown: this many file lines plus the summary line.
13544const STAT_FILE_LINES: usize = 25;
13545/// Cap on the commit list, well inside GitHub's 65536-character body limit.
13546const COMMITS_MAX_CHARS: usize = 20_000;
13547
13548/// Read the commits and diff stat of `base..branch`. `None` when git cannot
13549/// say or finds nothing, so the caller falls back to what the run recorded.
13550async fn branch_facts(repo: &Path, base: &str, branch: &str) -> Option<BranchFacts> {
13551    let commits = git::commit_log(repo, base, branch).await.ok()?;
13552    if commits.is_empty() {
13553        return None;
13554    }
13555    let stat = git::diff_stat(repo, base, branch).await.unwrap_or_default();
13556    let lines: Vec<&str> = stat.lines().collect();
13557    let stat = if lines.len() > STAT_FILE_LINES + 1 {
13558        let omitted = lines.len() - 1 - STAT_FILE_LINES;
13559        let more = format!(" ... {omitted} more file(s)");
13560        let mut kept: Vec<&str> = lines[..STAT_FILE_LINES].to_vec();
13561        kept.push(&more);
13562        kept.push(lines[lines.len() - 1]);
13563        kept.join("\n")
13564    } else {
13565        lines.join("\n")
13566    };
13567    Some(BranchFacts { commits, stat })
13568}
13569
13570/// Defang what would break the surrounding markdown: a closing `</details>`
13571/// and a code fence.
13572fn markdown_safe(text: &str) -> String {
13573    text.replace("</details>", "&lt;/details&gt;")
13574        .replace("\x60\x60\x60", "~~~")
13575}
13576
13577fn neutral_title(state: &RunState, winner: char) -> String {
13578    format!(
13579        "chore: land candidate {} of run {}",
13580        winner.to_ascii_uppercase(),
13581        state.id
13582    )
13583}
13584
13585/// Reuse the graph's bounded fixer without starting another graph or driver.
13586/// Copy the working state back even on errors so spent rounds remain visible.
13587pub(crate) async fn repair_landing_gate(
13588    state: &mut RunState,
13589    winner: &Candidate,
13590    outcomes: &[CommandOutcome],
13591) -> Result<GateFix> {
13592    if state.gate_fixes.len() >= state.config.graph.gate_fix_rounds || !gate_fixable(outcomes) {
13593        return Ok(GateFix::Stop);
13594    }
13595    let mut runner = Runner {
13596        roles: state.config.resolve_roles()?,
13597        sem: Arc::new(Semaphore::new(state.config.graph.max_parallel.max(1))),
13598        state: state.clone(),
13599        pause: Pause::new(),
13600        interrupt: Pause::new(),
13601    };
13602    let result = runner.gate_fix_round(winner, outcomes).await;
13603    *state = runner.state;
13604    result
13605}
13606
13607/// Review judgment survives a clean rebase; command evidence belongs to a SHA.
13608/// A completed failure is terminal on that SHA. Resource waits remain retryable.
13609pub(crate) async fn verify_current_head(
13610    state: &mut RunState,
13611    winner: &Candidate,
13612    wait: &crate::repo_lock::WaitPolicy,
13613) -> Result<bool> {
13614    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13615    // Preserve the previous record before replacing it, including on crash recovery.
13616    if state.head_e2e.as_ref().is_some_and(|e| e.head != head) {
13617        state
13618            .verification_history
13619            .push(crate::run::VerificationEvidence {
13620                superseded_by: Some(head.clone()),
13621                archived_at: Some(Timestamp::now()),
13622                fixes_spent: Some(state.gate_fixes.len()),
13623                gate_head: None,
13624                gate_ran: false,
13625                gate: Vec::new(),
13626                e2e: state.head_e2e.take(),
13627            });
13628    }
13629    if let Some(e) = &state.head_e2e
13630        && e.head == head
13631    {
13632        if e.passed {
13633            return Ok(true);
13634        }
13635        if !e.outcomes.is_empty() && !verify_inconclusive(&e.outcomes) {
13636            state.status = RunStatus::Blocked;
13637            state.save()?;
13638            return Ok(false);
13639        }
13640    } else if state.reviews.last().is_some_and(|r| {
13641        r.verified_head.as_deref() == Some(head.as_str())
13642            && (r.e2e_status() == E2eStatus::Passed
13643                || (r.e2e_status() == E2eStatus::NotConfigured
13644                    && state.config.verify.e2e.is_empty()))
13645    }) || state
13646        .gate_repair_e2e
13647        .as_ref()
13648        .is_some_and(|e| e.head == head && e.passed)
13649    {
13650        return Ok(true);
13651    }
13652    if let Some(e) = &state.gate_repair_e2e
13653        && e.head == head
13654        && !e.passed
13655        && !e.outcomes.is_empty()
13656        && !verify_inconclusive(&e.outcomes)
13657    {
13658        state.status = RunStatus::Blocked;
13659        state.save()?;
13660        return Ok(false);
13661    }
13662    // Bind the result to the base used by the candidate, not a tracking ref
13663    // that the background fetch can advance independently of verification.
13664    let base_commit = state
13665        .base_sync
13666        .as_ref()
13667        .map(|s| s.tip.clone())
13668        .filter(|tip| !tip.is_empty())
13669        .or_else(|| (!state.base_commit.is_empty()).then(|| state.base_commit.clone()));
13670    state.head_e2e = Some(crate::run::GateRepairE2e::new(
13671        head.clone(),
13672        false,
13673        Vec::new(),
13674    ));
13675    state.save()?;
13676    let commands = state.config.verify.e2e.clone();
13677    let shell = state.config.shell();
13678    let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13679    let cache_dir = state.config.cache_dir();
13680    let outcomes = if commands.is_empty() {
13681        Vec::new()
13682    } else {
13683        let (outcomes, _) = with_cache_lease(
13684            state,
13685            cache_dir.as_deref(),
13686            "e2e",
13687            "e2e",
13688            &winner.worktree,
13689            &head,
13690            timeout,
13691            "current head e2e",
13692            wait,
13693            |state, budget| async move {
13694                run_e2e_with_retry(
13695                    state,
13696                    &shell,
13697                    &commands,
13698                    &winner.worktree,
13699                    budget,
13700                    "current head e2e",
13701                    None,
13702                )
13703                .await
13704            },
13705        )
13706        .await?;
13707        outcomes
13708    };
13709    let unresolved = verify_inconclusive(&outcomes);
13710    let passed = !unresolved
13711        && outcomes.iter().all(CommandOutcome::ok)
13712        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
13713    if !outcomes.is_empty() && !unresolved {
13714        state.record_base_progress(&head);
13715    }
13716    let generation = Some(state.verification_history.len());
13717    let pass = state.passes.last().map(|p| p.index);
13718    let recorded_at = Some(Timestamp::now());
13719    let resumption_generation = state.entry_resumption_generation;
13720    let mut record = crate::run::GateRepairE2e::new(head.clone(), passed, outcomes);
13721    record.base_commit = base_commit;
13722    record.generation = generation;
13723    record.pass = pass;
13724    record.recorded_at = recorded_at;
13725    record.resumption_generation = resumption_generation;
13726    if !passed && !unresolved {
13727        let detail = state
13728            .head_e2e
13729            .as_ref()
13730            .and_then(|e| crate::verify_evidence::summarize_failed_outcomes(&e.outcomes))
13731            .map(|d| format!(" ({d})"))
13732            .unwrap_or_default();
13733        state.status = RunStatus::Blocked;
13734        state.event(
13735            "e2e",
13736            format!("verify.e2e failed on head {head}{detail}; nothing published"),
13737        );
13738        record.recorded_events = Some(state.events.len());
13739    }
13740    state.head_e2e = Some(record);
13741    state.save()?;
13742    Ok(passed)
13743}
13744
13745/// Recheck a repair's e2e requirement across failures, resource deferrals and
13746/// process interruptions. A successful result only applies to its exact SHA.
13747pub(crate) async fn check_gate_repair_e2e(
13748    state: &mut RunState,
13749    winner: &Candidate,
13750    wait: &crate::repo_lock::WaitPolicy,
13751) -> Result<GateFix> {
13752    if state.gate_repair_e2e.is_none() && state.gate_fixes.is_empty() {
13753        return Ok(GateFix::Retry);
13754    }
13755    let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13756    if let Some(record) = &state.gate_repair_e2e
13757        && record.head == head
13758    {
13759        if record.passed {
13760            return Ok(GateFix::Retry);
13761        }
13762        if !record.outcomes.is_empty()
13763            && record.outcomes.iter().all(|o| {
13764                !o.resource_blocked && matches!(o.code, Some(code) if code != 126 && code != 127)
13765            })
13766        {
13767            return Ok(GateFix::Stop);
13768        }
13769    }
13770    state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
13771        head.clone(),
13772        false,
13773        Vec::new(),
13774    ));
13775    state.save()?;
13776    let commands = state.config.verify.e2e.clone();
13777    let outcomes = if commands.is_empty() {
13778        Vec::new()
13779    } else {
13780        let shell = state.config.shell();
13781        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13782        let cache_dir = state.config.cache_dir();
13783        let (outcomes, _) = with_cache_lease(
13784            state,
13785            cache_dir.as_deref(),
13786            "e2e",
13787            "e2e",
13788            &winner.worktree,
13789            &head,
13790            timeout,
13791            "gate repair e2e",
13792            wait,
13793            |state, budget| async move {
13794                run_e2e_with_retry(
13795                    state,
13796                    &shell,
13797                    &commands,
13798                    &winner.worktree,
13799                    budget,
13800                    "gate repair e2e",
13801                    None,
13802                )
13803                .await
13804            },
13805        )
13806        .await?;
13807        outcomes
13808    };
13809    let deferred = verify_inconclusive(&outcomes);
13810    let passed = outcomes.iter().all(CommandOutcome::ok)
13811        && git::rev_parse(&winner.worktree, "HEAD").await? == head;
13812    state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(head, passed, outcomes));
13813    state.save()?;
13814    if deferred {
13815        Ok(GateFix::Defer)
13816    } else if !passed {
13817        let detail = state
13818            .gate_repair_e2e
13819            .as_ref()
13820            .and_then(|e| crate::verify_evidence::summarize_failed_outcomes(&e.outcomes))
13821            .map(|d| format!(" ({d})"))
13822            .unwrap_or_default();
13823        state.event(
13824            "gate",
13825            format!("verify.e2e failed after gate repair{detail}; nothing published"),
13826        );
13827        Ok(GateFix::Stop)
13828    } else {
13829        Ok(GateFix::Retry)
13830    }
13831}
13832
13833/// Run the same configured gate for a landing head and a fresh graph.
13834pub(crate) async fn run_landing_gate(
13835    state: &mut RunState,
13836    winner: &Candidate,
13837    wait: &crate::repo_lock::WaitPolicy,
13838) -> Result<Vec<CommandOutcome>> {
13839    let shell = state.config.shell();
13840    let gate_commands = state.config.verify.gate.clone();
13841    let has_pre_gate = !state.config.verify.pre_gate.is_empty();
13842    let outcomes = if gate_commands.is_empty() && !has_pre_gate {
13843        state.gate_head = Some(git::rev_parse(&winner.worktree, "HEAD").await?);
13844        Vec::new()
13845    } else {
13846        let timeout = Duration::from_secs(state.config.graph.verify_timeout());
13847        let cache_dir = state.config.cache_dir();
13848        let head = git::rev_parse(&winner.worktree, "HEAD").await?;
13849        let (outcomes, _) = with_cache_lease(
13850            state,
13851            cache_dir.as_deref(),
13852            "gate",
13853            "gate",
13854            &winner.worktree,
13855            &head,
13856            timeout,
13857            "final gate",
13858            wait,
13859            |state, budget| {
13860                let shell = shell.clone();
13861                let gate_commands = gate_commands.clone();
13862                let winner = winner.clone();
13863                async move {
13864                    Runner::run_pre_gate(state, &winner).await;
13865                    // Bind command evidence after mechanical fixes, before commands start.
13866                    state.gate_head = git::rev_parse(&winner.worktree, "HEAD").await.ok();
13867                    let (outcomes, timed_out_pids) = run_commands(
13868                        state,
13869                        "gate",
13870                        "gate",
13871                        0,
13872                        &shell,
13873                        &gate_commands,
13874                        &winner.worktree,
13875                        budget,
13876                    )
13877                    .await;
13878                    (outcomes, false, timed_out_pids)
13879                }
13880            },
13881        )
13882        .await?;
13883        outcomes
13884    };
13885    let current = git::rev_parse(&winner.worktree, "HEAD").await?;
13886    if !verify_inconclusive(&outcomes) && state.gate_head.as_deref() != Some(current.as_str()) {
13887        let mut outcomes = outcomes;
13888        outcomes.push(CommandOutcome {
13889            command: "gate head stability".into(), code: None,
13890            output_tail: "winner changed during gate, or checked head is unknown; fresh verification required".into(),
13891            duration_ms: 0, resource_blocked: false,
13892            ..Default::default()
13893        });
13894        return Ok(outcomes);
13895    }
13896    if outcomes.is_empty() {
13897        // Nothing configured to check — distinct from every other
13898        // silence in this run's event log, since an empty `gate` alone
13899        // no longer says whether the gate ran at all (see
13900        // `RunState::gate_ran`'s own doc).
13901        state.event("gate", "no gate commands configured; not tested");
13902    }
13903    for o in &outcomes {
13904        state.event(
13905            "gate",
13906            format!(
13907                "`{}` -> {}",
13908                o.command,
13909                if o.ok() {
13910                    "pass".to_owned()
13911                } else {
13912                    format!(
13913                        "FAIL ({:?})\n{}",
13914                        o.code,
13915                        summarize_verify(&o.output_tail, EVENT_OUTPUT_TAIL)
13916                    )
13917                }
13918            ),
13919        );
13920    }
13921    Ok(outcomes)
13922}
13923
13924/// The pull request title to hand to `land::merge_subject`. A review-only run
13925/// opened by an earlier build titled its pull request with the review prompt;
13926/// that title is dropped (empty, so the fallback applies) rather than landed.
13927/// Any other title, including an operator's rename, passes through untouched,
13928/// and so does every title of a run that implements a task.
13929pub fn landing_title<'a>(state: &RunState, pr_title: &'a str) -> &'a str {
13930    if is_review_run(state) && pr_title.trim_start().starts_with(REVIEW_PROMPT_OPENING) {
13931        ""
13932    } else {
13933        pr_title
13934    }
13935}
13936
13937/// What the squash subject falls back to when the pull request title is empty
13938/// or candidate-shaped: for a review-only run the derived title, never the
13939/// review prompt held in `instruction`.
13940pub fn landing_subject_source(state: &RunState) -> String {
13941    if is_review_run(state) {
13942        let winner = state.candidates.first().map_or('A', |c| c.label);
13943        return review_title(state).unwrap_or_else(|| neutral_title(state, winner));
13944    }
13945    state.instruction.clone()
13946}
13947
13948/// `summary` without its `TITLE:` line, which the pull request title already
13949/// carries.
13950fn summary_without_title(summary: &str) -> String {
13951    let mut lines = summary.trim().lines().peekable();
13952    if lines.peek().is_some_and(|l| title_marker(l).is_some()) {
13953        lines.next();
13954    }
13955    lines.collect::<Vec<_>>().join("\n").trim().to_owned()
13956}
13957
13958/// The pull request title and body for the winning candidate.
13959///
13960/// Title: the implementer's `TITLE:` line ([`summary_title`]), falling back to
13961/// the task's own opening line via [`queue::title_from`] when there is none.
13962/// `state.instruction` can open with blank lines (`task_text` only rejects a
13963/// body that is blank *entirely*), which `title_from` skips.
13964///
13965/// Publishing uses an independent description generated from the final diff
13966/// and structured evidence. Internal summaries and reports remain local.
13967/// Non-publishing previews may display the original task and candidate summary.
13968/// The footer retains the run and candidate provenance.
13969#[cfg(test)]
13970fn pr_message(state: &RunState, winner: char) -> PrMessage {
13971    pr_message_with(state, winner, None)
13972}
13973
13974/// [`pr_message`] with what the branch of a review-only run says about itself.
13975/// `facts` is ignored for a run that implements a task.
13976#[cfg(test)]
13977fn pr_message_with(state: &RunState, winner: char, facts: Option<&BranchFacts>) -> PrMessage {
13978    let raw = pr_message_raw(
13979        state,
13980        winner,
13981        facts,
13982        crate::pr_outcome::FinalHead::Unreported,
13983        ChangeNote::NotAsked,
13984    );
13985    let id = crate::scrub::Identity::current();
13986    PrMessage {
13987        title: crate::scrub::scrub(&raw.title, &id),
13988        body: crate::scrub::scrub(&raw.body, &id),
13989    }
13990}
13991
13992/// What the public description may say about the change itself.
13993#[derive(Debug, Clone, Copy)]
13994enum ChangeNote<'a> {
13995    /// A local preview or non-publishing merge mode: no public generation needed.
13996    NotAsked,
13997    /// A summary written from the final diff.
13998    Summary(&'a crate::run::ChangeSummary),
13999    /// A summary was asked for and could not be produced; the text says why.
14000    Unavailable(&'a str),
14001}
14002
14003fn pr_message_raw(
14004    state: &RunState,
14005    winner: char,
14006    facts: Option<&BranchFacts>,
14007    head: crate::pr_outcome::FinalHead<'_>,
14008    change: ChangeNote<'_>,
14009) -> PrMessage {
14010    if !matches!(change, ChangeNote::NotAsked) {
14011        let (title, mut body) = match change {
14012            ChangeNote::Summary(c) => (
14013                c.title.clone(),
14014                format!("## Summary\n\n{}\n\n", c.body.trim()),
14015            ),
14016            ChangeNote::Unavailable(why) => (
14017                neutral_title(state, winner),
14018                format!(
14019                    "## 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"
14020                ),
14021            ),
14022            ChangeNote::NotAsked => unreachable!(),
14023        };
14024        body.push_str(&public_pr_evidence(state, head));
14025        body.push_str(&format!(
14026            "\n---\nmagi:run/{} magi:candidate-{}\n",
14027            state.id,
14028            winner.to_ascii_lowercase()
14029        ));
14030        return PrMessage { title, body };
14031    }
14032    pr_preview(state, winner, facts, head)
14033}
14034
14035/// Append public facts from the run records after every prose generation,
14036/// including posting-gate rewrites. The agent cannot drop this provenance.
14037fn public_pr_evidence(state: &RunState, head: crate::pr_outcome::FinalHead<'_>) -> String {
14038    let mut body = crate::pr_outcome::review_rounds(state);
14039    body.push_str(&crate::pr_outcome::final_verification(state, head));
14040    let open = state.last_round_findings();
14041    if !open.is_empty() {
14042        body.push_str("## Open review findings\n\n");
14043        for f in open {
14044            body.push_str(&format!("- `{}` [{:?}]\n", f.id, f.severity));
14045        }
14046        body.push('\n');
14047    }
14048    if let Some(c) = state.change_summary.as_ref()
14049        && head == crate::pr_outcome::FinalHead::At(&c.head)
14050    {
14051        body.push_str(&format!(
14052            "Evidence: final diff `{}`..`{}`; review and verification records from this run.\n",
14053            c.base, c.head
14054        ));
14055    }
14056    body
14057}
14058
14059/// Local-only preview of the operator's task and candidate summary.
14060fn pr_preview(
14061    state: &RunState,
14062    winner: char,
14063    facts: Option<&BranchFacts>,
14064    head: crate::pr_outcome::FinalHead<'_>,
14065) -> PrMessage {
14066    let summary = state
14067        .candidates
14068        .iter()
14069        .find(|c| c.label == winner)
14070        .map(|c| c.summary.as_str())
14071        .unwrap_or_default();
14072    // The fallback is the operator's own words and may not be English; GitHub
14073    // text always is, so a non-English task gets a neutral title instead.
14074    let review = is_review_run(state);
14075    let title = if review {
14076        facts
14077            .and_then(|f| {
14078                english_subject(&f.commits.first()?.0, state.config.graph.github_english())
14079            })
14080            .or_else(|| review_title(state))
14081            .or_else(|| {
14082                state
14083                    .candidates
14084                    .iter()
14085                    .find(|c| c.label == winner)
14086                    .filter(|c| !c.branch.starts_with("magi/"))
14087                    .and_then(|c| english_subject(&c.branch, state.config.graph.github_english()))
14088            })
14089            .unwrap_or_else(|| neutral_title(state, winner))
14090    } else {
14091        summary_title(summary).unwrap_or_else(|| {
14092            english_title(
14093                &state.instruction,
14094                PR_TITLE_MAX,
14095                state.config.graph.github_english(),
14096            )
14097            .unwrap_or_else(|| neutral_title(state, winner))
14098        })
14099    };
14100
14101    let mut body = String::new();
14102    let what = summary_without_title(summary);
14103    if !what.is_empty() {
14104        body.push_str("## Summary\n\n");
14105        body.push_str(&what);
14106        body.push_str("\n\n");
14107    }
14108
14109    // Review history uses structured facts across all rounds, never reports.
14110    body.push_str(&crate::pr_outcome::review_rounds(state));
14111    body.push_str(&crate::pr_outcome::final_verification(state, head));
14112    let fix = state.reviews.iter().rev().find_map(|r| r.fix.as_ref());
14113
14114    let open = state.open_findings();
14115    if !open.is_empty() {
14116        body.push_str("## Open review findings\n\n");
14117        for f in &open {
14118            body.push_str(&format!(
14119                "- `{}` [{:?}] {}\n",
14120                f.id, f.severity, "Context retained in local review records."
14121            ));
14122        }
14123        body.push('\n');
14124    }
14125
14126    if let Some(fix) = fix
14127        && !fix.rejected.is_empty()
14128    {
14129        body.push_str("## Declined by the fixer\n\n");
14130        for r in &fix.rejected {
14131            body.push_str(&format!(
14132                "- `{}`: {}\n",
14133                r.id, "Reason retained in local review records."
14134            ));
14135        }
14136        body.push('\n');
14137    }
14138
14139    if review {
14140        // The review prompt is not the task; list what the branch carries.
14141        body.push_str("## Commits under review\n\n");
14142        if let Some(facts) = facts {
14143            let mut left = COMMITS_MAX_CHARS;
14144            for (i, (subject, text)) in facts.commits.iter().enumerate() {
14145                let mut entry = format!("- {}\n", markdown_safe(subject));
14146                for l in markdown_safe(text).lines() {
14147                    entry.push_str(format!("  {l}\n").trim_end_matches(' '));
14148                }
14149                if left == 0 {
14150                    body.push_str(&format!(
14151                        "- ... {} more commit(s)\n",
14152                        facts.commits.len() - i
14153                    ));
14154                    break;
14155                }
14156                if entry.len() > left {
14157                    // Even the first commit is cut: one huge body must not
14158                    // push the whole description past GitHub's limit.
14159                    let mut end = left;
14160                    while !entry.is_char_boundary(end) {
14161                        end -= 1;
14162                    }
14163                    entry.truncate(end);
14164                    entry.push_str("\n  ... (truncated)\n");
14165                    left = 0;
14166                } else {
14167                    left -= entry.len();
14168                }
14169                body.push_str(&entry);
14170            }
14171            if !facts.stat.trim().is_empty() {
14172                body.push_str(&format!(
14173                    "\n## Diff stat\n\n```\n{}\n```\n",
14174                    markdown_safe(facts.stat.trim())
14175                ));
14176            }
14177        } else {
14178            match &state.reviewed_commits {
14179                Some(subjects) => {
14180                    for s in subjects {
14181                        body.push_str(&format!("- {}\n", s.trim()));
14182                    }
14183                }
14184                None => {
14185                    // An older run kept only the prompt, with the commit list
14186                    // after its first paragraph.
14187                    let rest = state.instruction.split_once("\n\n").map_or("", |(_, r)| r);
14188                    body.push_str(rest.trim());
14189                    body.push('\n');
14190                }
14191            }
14192        }
14193    } else {
14194        let task = state.instruction.trim();
14195        let task = if task.is_empty() {
14196            "(empty task)"
14197        } else {
14198            task
14199        };
14200        body.push_str(&format!(
14201            "<details>\n<summary>Original task</summary>\n\n{}\n\n</details>\n",
14202            task.replace("</details>", "&lt;/details&gt;")
14203        ));
14204    }
14205
14206    body.push_str(&format!(
14207        "\n---\nmagi:run/{} magi:candidate-{}\n",
14208        state.id,
14209        winner.to_ascii_lowercase()
14210    ));
14211
14212    PrMessage { title, body }
14213}
14214
14215/// Source imports have already been prepared from structured inputs. Legacy
14216/// inferred references must never instruct a seat to reconstruct those imports.
14217fn seeded_instruction(state: &RunState) -> String {
14218    let mut inputs = Vec::new();
14219    if let Some(start) = &state.sources.start_from {
14220        inputs.push(format!(
14221            "Start from `{}` at `{}` (including ancestry).",
14222            start.token, start.sha
14223        ));
14224    }
14225    for pick in &state.sources.pick_commits {
14226        inputs.push(format!(
14227            "Pick `{}` at `{}` (single commit).",
14228            pick.token, pick.sha
14229        ));
14230    }
14231    if inputs.is_empty() {
14232        state.instruction.clone()
14233    } else {
14234        format!(
14235            "{}\n\n# Explicit source inputs already prepared\n\n{}",
14236            state.instruction,
14237            inputs.join("\n")
14238        )
14239    }
14240}
14241
14242/// Does the winner have no commits ahead of the base it would land on?
14243/// Any failure to find out reads as "not empty": the merge then behaves as it
14244/// always did rather than refusing on a guess.
14245async fn merge_is_empty(repo: &Path, state: &RunState, branch: &str, mode: MergeMode) -> bool {
14246    let base = &state.base_branch;
14247    let mut against = base.clone();
14248    if mode == MergeMode::Pr {
14249        // A pull request lands on the remote's base, never the local branch
14250        // of the same name: if that cannot be read, "not empty" is the safe
14251        // answer.
14252        let remote = &state.config.merge.remote;
14253        let tracking = format!("{remote}/{base}");
14254        let fetched = git::fetch(repo, remote, base).await;
14255        if fetched.is_ok_and(|o| o.ok()) && git::rev_exists(repo, &tracking).await {
14256            against = tracking;
14257        } else {
14258            return false;
14259        }
14260    }
14261    matches!(git::commits_ahead(repo, &against, branch).await, Ok(0))
14262}
14263
14264/// Why nothing was opened for an empty winner, with what the task's own
14265/// references resolved to.
14266fn empty_candidate_detail(_state: &RunState, base: &str) -> String {
14267    let mut detail = format!(
14268        "empty candidate: the winning branch has 0 commits ahead of {base}, so there is \
14269         nothing to open a pull request for"
14270    );
14271    detail.push_str(
14272        "\nSource imports require explicit --start-from or --pick-commit options on a new task.",
14273    );
14274    detail
14275}
14276
14277/// What the `Pr` merge does once it knows whether the branch already has an
14278/// open pull request.
14279#[derive(Debug, PartialEq, Eq)]
14280enum PrPlan {
14281    Create,
14282    Adopt { url: String, title: String },
14283    Stop(String),
14284}
14285
14286/// Pure decision behind the `Pr` merge: none -> create, one -> adopt, many or
14287/// a failed lookup -> stop with the real reason. Never guesses.
14288fn pr_merge_plan(found: Result<land::OpenPr>) -> PrPlan {
14289    match found {
14290        Ok(land::OpenPr::None) => PrPlan::Create,
14291        Ok(land::OpenPr::One { url, title }) => PrPlan::Adopt { url, title },
14292        Ok(land::OpenPr::Many(urls)) => PrPlan::Stop(format!(
14293            "several open pull requests exist for this branch, not picking one: {}",
14294            urls.join(" ")
14295        )),
14296        Err(e) => PrPlan::Stop(format!("could not look up open pull requests: {e:#}")),
14297    }
14298}
14299
14300/// `gh pr create`, returning the PR url.
14301pub(crate) async fn gh_pr_create(
14302    cwd: &Path,
14303    base: &str,
14304    head: &str,
14305    title: &str,
14306    body: &str,
14307) -> Result<String> {
14308    let out = tokio::process::Command::new("gh")
14309        .args([
14310            "pr", "create", "--base", base, "--head", head, "--title", title, "--body", body,
14311        ])
14312        .current_dir(cwd)
14313        .quiet()
14314        .stdin(std::process::Stdio::null())
14315        .output()
14316        .await
14317        .context("spawn gh")?;
14318    if out.status.success() {
14319        Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
14320    } else {
14321        bail!("{}", String::from_utf8_lossy(&out.stderr).trim().to_owned())
14322    }
14323}
14324
14325/// Never force deletion of uncommitted work, including unknown legacy trees.
14326async fn remove_preserved_worktree(repo: &Path, path: &Path) -> Result<()> {
14327    match std::fs::symlink_metadata(path) {
14328        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
14329            // A previous cleanup may have removed the tree before a branch
14330            // deletion or state save failed. Unregister it if still present.
14331            git::worktree_remove_clean(repo, path).await?;
14332            return Ok(());
14333        }
14334        Err(e) => return Err(e.into()),
14335        Ok(_) => {}
14336    }
14337    if !git::is_clean(path).await? {
14338        bail!(
14339            "worktree has uncommitted work; refusing removal: {}",
14340            path.display()
14341        );
14342    }
14343    if !git::worktree_remove_clean(repo, path).await? {
14344        bail!("worktree removal refused: {}", path.display());
14345    }
14346    Ok(())
14347}
14348
14349/// Read seats return replies, not working-tree changes. Only registered,
14350/// detached seats directly inside this run's root may discard those changes.
14351async fn remove_read_seat_worktree(state: &mut RunState, path: &Path) -> Result<()> {
14352    if !crate::retention::read_seat(path) || !path.exists() {
14353        return remove_preserved_worktree(&state.repo, path).await;
14354    }
14355    let owned = std::fs::symlink_metadata(path)?.is_dir()
14356        && path.parent().map(Path::canonicalize).transpose()?
14357            == Some(state.worktree_root().canonicalize()?)
14358        && crate::retention::worktrees(state)
14359            .await?
14360            .contains(&path.canonicalize()?);
14361    let common = crate::repo_lock::common_dir(&state.repo).await?;
14362    if !owned
14363        || common.is_none()
14364        || crate::repo_lock::common_dir(path).await? != common
14365        || git::git_raw(path, &["symbolic-ref", "-q", "HEAD"])
14366            .await?
14367            .ok()
14368        || state.candidates.iter().any(|c| c.worktree == path)
14369    {
14370        return remove_preserved_worktree(&state.repo, path).await;
14371    }
14372    let changes = git::status_porcelain(path).await?;
14373    if !git::worktree_remove(&state.repo, path).await? {
14374        bail!(
14375            "read-only seat worktree removal refused: {}",
14376            path.display()
14377        );
14378    }
14379    if !changes.is_empty() {
14380        let paths = changes.lines().take(20).collect::<Vec<_>>().join("; ");
14381        let paths: String = paths.chars().take(1024).collect();
14382        state.event(
14383            "fold",
14384            format!(
14385                "discarded read-only seat {} changes ({} status entries; first 20, at most 1024 chars): {paths}",
14386                path.file_name().unwrap_or_default().to_string_lossy(),
14387                changes.lines().count()
14388            ),
14389        );
14390    }
14391    Ok(())
14392}
14393
14394fn fold_target(
14395    home: &Path,
14396    root: &Path,
14397    path: &Path,
14398    isolated: bool,
14399) -> Option<crate::build_target::FoldTarget> {
14400    if !isolated {
14401        return None;
14402    }
14403    match crate::build_target::FoldTarget::for_checkout(home, path, root) {
14404        Ok(target) => target,
14405        Err(error) => {
14406            tracing::warn!(checkout = %path.display(), %error, "isolated target binding not proved at fold");
14407            None
14408        }
14409    }
14410}
14411
14412fn reclaim_fold_target(home: &Path, target: Option<crate::build_target::FoldTarget>) {
14413    if let Some(target) = target
14414        && let Err(error) = target.reclaim_orphaned_target(home)
14415    {
14416        tracing::warn!(%error, "isolated target retained after fold");
14417    }
14418}
14419
14420/// Tear a run's worktrees and branches down.
14421///
14422/// `home` is where the updated `run.json` is saved (via
14423/// [`RunState::save_under`]), never the process-global [`crate::run::home`]:
14424/// a housekeeping pass already has its own honest `home` handed to it, and
14425/// falling through to the global here would write back through whichever
14426/// directory some other process or test pinned into that `OnceLock` first,
14427/// not the one the caller actually resolved its `runs` and `state` from.
14428pub async fn fold_run(state: &mut RunState, drop_winner: bool, home: &Path) -> Result<Vec<String>> {
14429    fold_run_with_policy(state, drop_winner, home, false).await
14430}
14431
14432/// Explicit CLI-only retention override; automatic callers use [`fold_run`].
14433pub async fn fold_run_overriding_recovery_retention(
14434    state: &mut RunState,
14435    drop_winner: bool,
14436    home: &Path,
14437) -> Result<Vec<String>> {
14438    fold_run_with_policy(state, drop_winner, home, true).await
14439}
14440
14441async fn fold_run_with_policy(
14442    state: &mut RunState,
14443    drop_winner: bool,
14444    home: &Path,
14445    override_recovery_retention: bool,
14446) -> Result<Vec<String>> {
14447    if let Some(reason) = crate::pr_recovery::source_retention_reason(home, state)
14448        && !override_recovery_retention
14449    {
14450        bail!("refusing fold: {reason}");
14451    }
14452    if !state.candidate_preservation.is_empty() || !state.interrupted_implementations.is_empty() {
14453        bail!("candidate preservation incomplete; refusing cleanup");
14454    }
14455    // Serialize ordinary folding with the same starts/resumes as target-only
14456    // eviction. Otherwise a second janitor could remove the whole worktree
14457    // around a live output borrower even though target eviction was fenced.
14458    std::fs::create_dir_all(home.join("runs").join(&state.id))?;
14459    let _owner = crate::pr_head::owner_lock(home, &state.id)?;
14460    // An override must use current durable ownership, not a pre-lock snapshot.
14461    if override_recovery_retention {
14462        *state = RunState::load_under(&state.id, home)?;
14463        anyhow::ensure!(
14464            state.status.done() && !state.status.resumable(),
14465            "recovery retention override requires a finished, non-resumable run"
14466        );
14467        let claimed = crate::daemon::is_working_on_other(home, &state.id, Timestamp::now())?;
14468        anyhow::ensure!(
14469            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
14470            "run is live or its ownership is unknown"
14471        );
14472        anyhow::ensure!(
14473            state.candidate_preservation.is_empty() && state.interrupted_implementations.is_empty(),
14474            "candidate preservation incomplete; refusing cleanup"
14475        );
14476    }
14477    let retention_reason = crate::pr_recovery::source_retention_reason(home, state);
14478    if let Some(reason) = &retention_reason
14479        && !override_recovery_retention
14480    {
14481        bail!("refusing fold: {reason}");
14482    }
14483    let _driver = crate::driver::maintenance(home, &state.id)?;
14484    let mut output_guards = Vec::new();
14485    for entry in std::fs::read_dir(state.worktree_root())
14486        .into_iter()
14487        .flatten()
14488        .flatten()
14489    {
14490        if entry.path().join(".git").is_file() {
14491            output_guards.push(crate::retention::OutputLease::take(&entry.path(), true)?);
14492        }
14493    }
14494    let repo = state.repo.clone();
14495    // CLI, Web and automatic cleanup all enter here, independently of
14496    // Runner::fold_losers. Protect deletion and shared config release too.
14497    let wait = repository_wait(state, None);
14498    let _coordination = match coordinate_operation(state, &repo, &wait).await {
14499        Ok(lease) => lease,
14500        Err(e) => {
14501            state.save_under(home)?;
14502            return Err(e);
14503        }
14504    };
14505    // Confirmed merges dispose of their owned sources after durable evidence
14506    // capture. Preflight every source before removing anything.
14507    let _source_outputs = if retention_reason.is_some()
14508        || (state.status == RunStatus::Merged && state.merge.as_ref().is_some_and(|merge| merge.ok))
14509    {
14510        verify_merged_fold_sources(state, drop_winner, home).await?
14511    } else {
14512        Vec::new()
14513    };
14514    if let Some(reason) = retention_reason {
14515        state.event(
14516            "fold",
14517            format!(
14518                "operator CLI --override-recovery-retention authorized deletion for run {}: bypassed {reason}",
14519                state.id
14520            ),
14521        );
14522        state.save_under(home)?;
14523    }
14524    let root = state.worktree_root();
14525    let winner = state.tally.as_ref().map(|t| t.winner);
14526    let mut removed = Vec::new();
14527    let isolated = crate::build_target::isolated(&state.config);
14528
14529    for i in 0..state.candidates.len() {
14530        let c = state.candidates[i].clone();
14531        let is_winner = Some(c.label) == winner;
14532        if is_winner && !drop_winner {
14533            continue;
14534        }
14535        let existed = c.worktree.exists();
14536        let target = fold_target(home, &root, &c.worktree, isolated);
14537        // A vanished directory can still have a Git registration that keeps
14538        // its branch checked out. Remove that registration before the branch.
14539        remove_preserved_worktree(&repo, &c.worktree).await?;
14540        reclaim_fold_target(home, target);
14541        if existed {
14542            removed.push(c.worktree.to_string_lossy().into_owned());
14543        }
14544        // A branch handed to a later run (and its pull request) is not this
14545        // run's to delete.
14546        let handed_over = state.released_branches.contains(&c.branch);
14547        if !handed_over && git::branch_exists(&repo, &c.branch).await? {
14548            if !git::branch_delete(&repo, &c.branch).await? {
14549                bail!("candidate branch removal refused");
14550            }
14551            removed.push(c.branch.clone());
14552        }
14553        state.candidates[i].folded = true;
14554    }
14555
14556    for name in std::fs::read_dir(&root).into_iter().flatten().flatten() {
14557        let path = name.path();
14558        let keep = !drop_winner
14559            && winner.is_some_and(|w| {
14560                path.file_name()
14561                    .is_some_and(|n| n == format!("cand-{w}").as_str())
14562            });
14563        if keep {
14564            continue;
14565        }
14566        let target = fold_target(home, &root, &path, isolated);
14567        remove_read_seat_worktree(state, &path).await?;
14568        reclaim_fold_target(home, target);
14569        removed.push(path.to_string_lossy().into_owned());
14570    }
14571
14572    // `root` (`wt/<...>/<short>/`) held nothing but this run's candidate and
14573    // judge worktrees, so once the loop above has cleared all of them out,
14574    // the parent is a bare directory nobody else was ever going to remove -
14575    // git only ever managed what was inside it. Left alone, one of these
14576    // accumulates per fully-folded run; the operator's own machine had 74.
14577    // `remove_if_empty` re-checks rather than assuming: a run whose winner
14578    // was kept (`!drop_winner`) leaves its directory behind on purpose, and
14579    // so does anything a run never claimed that happens to share the bay.
14580    remove_if_empty(&root);
14581
14582    if state.enabled_worktree_config && drop_winner {
14583        // A release, not a raw disable: some sibling run in this repository
14584        // may still hold its own reference (see `git::acquire_worktree_config`),
14585        // and only the last release actually turns the setting back off.
14586        git::release_worktree_config(&repo).await.ok();
14587        state.enabled_worktree_config = false;
14588    }
14589    state.save_under(home)?;
14590    Ok(removed)
14591}
14592
14593async fn verify_merged_fold_sources(
14594    state: &RunState,
14595    drop_winner: bool,
14596    home: &Path,
14597) -> Result<Vec<std::fs::File>> {
14598    let winner = state.tally.as_ref().map(|t| t.winner);
14599    let mut heads = BTreeSet::new();
14600    for candidate in &state.candidates {
14601        if Some(candidate.label) == winner && !drop_winner {
14602            continue;
14603        }
14604        anyhow::ensure!(
14605            candidate.worktree.parent() == Some(state.worktree_root().as_path()),
14606            "candidate recovery source is outside the inventoried run root: {}",
14607            candidate.worktree.display()
14608        );
14609        match std::fs::symlink_metadata(&candidate.worktree) {
14610            Ok(_) => {}
14611            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
14612            Err(error) => return Err(error.into()),
14613        }
14614        if !state.released_branches.contains(&candidate.branch)
14615            && git::branch_exists(&state.repo, &candidate.branch).await?
14616        {
14617            heads.insert(git::rev_parse(&state.repo, &candidate.branch).await?);
14618        }
14619    }
14620    let mut cargo_guards = Vec::new();
14621    let entries = match std::fs::read_dir(state.worktree_root()) {
14622        Ok(entries) => Some(entries),
14623        Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
14624        Err(error) => return Err(error.into()),
14625    };
14626    for entry in entries.into_iter().flatten() {
14627        let path = entry?.path();
14628        let metadata = std::fs::symlink_metadata(&path)?;
14629        anyhow::ensure!(
14630            metadata.is_dir() && !metadata.file_type().is_symlink(),
14631            "non-directory or symlink recovery source retained: {}",
14632            path.display()
14633        );
14634        if !drop_winner
14635            && winner.is_some_and(|w| {
14636                path.file_name()
14637                    .is_some_and(|name| name == format!("cand-{w}").as_str())
14638            })
14639        {
14640            continue;
14641        }
14642        anyhow::ensure!(
14643            path.join(".git").is_file(),
14644            "unregistered recovery source retained: {}",
14645            path.display()
14646        );
14647        anyhow::ensure!(
14648            git::git(
14649                &path,
14650                &[
14651                    "status",
14652                    "--porcelain",
14653                    "--untracked-files=all",
14654                    "--ignored",
14655                    "--",
14656                    ".",
14657                    ":(exclude)target"
14658                ]
14659            )
14660            .await?
14661            .is_empty(),
14662            "source changes or ignored recovery files retained: {}",
14663            path.display()
14664        );
14665        match std::fs::symlink_metadata(path.join("target")) {
14666            Ok(_) => {
14667                cargo_guards.extend(crate::retention::verify_residue(home, &state.id, &path).await?)
14668            }
14669            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
14670            Err(error) => return Err(error.into()),
14671        }
14672        for checkpoint in [
14673            "rebase-merge",
14674            "rebase-apply",
14675            "sequencer",
14676            "CHERRY_PICK_HEAD",
14677            "MERGE_HEAD",
14678            "REBASE_HEAD",
14679            "REVERT_HEAD",
14680            "BISECT_LOG",
14681            "AUTO_MERGE",
14682            "MERGE_MSG",
14683        ] {
14684            let location = git::git(
14685                &path,
14686                &[
14687                    "rev-parse",
14688                    "--path-format=absolute",
14689                    "--git-path",
14690                    checkpoint,
14691                ],
14692            )
14693            .await?;
14694            anyhow::ensure!(
14695                matches!(std::fs::symlink_metadata(location.trim()), Err(ref e)
14696                if e.kind() == std::io::ErrorKind::NotFound),
14697                "Git recovery checkpoint retained: {checkpoint}"
14698            );
14699        }
14700        heads.insert(git::rev_parse(&path, "HEAD").await?);
14701    }
14702    crate::fold_evidence::preserve(state, home, &heads).await?;
14703
14704    Ok(cargo_guards)
14705}
14706
14707/// Remove `dir` if it exists and has nothing in it.
14708///
14709/// Best-effort and silent by design: a directory that is not empty (a run
14710/// whose winner is still parked there, a stray file some other process left)
14711/// is exactly the case this must refuse, and a directory that is already gone
14712/// is not a failure worth reporting either. `std::fs::remove_dir` itself
14713/// already refuses a non-empty directory, so the emptiness check below is
14714/// belt, not suspenders - it is what keeps this from ever attempting the
14715/// removal in the case that matters, rather than trusting `remove_dir`'s
14716/// error path to have no side effects if it ever changed.
14717fn remove_if_empty(dir: &Path) {
14718    if dir.is_dir() && std::fs::read_dir(dir).is_ok_and(|mut entries| entries.next().is_none()) {
14719        std::fs::remove_dir(dir).ok();
14720    }
14721}
14722
14723/// Severity of the worst open finding in the last review round, for reporting.
14724pub fn worst_open(state: &RunState) -> Option<Severity> {
14725    state
14726        .reviews
14727        .last()?
14728        .reviews
14729        .iter()
14730        .flat_map(|r| r.findings.iter())
14731        .map(|f| f.severity)
14732        .max()
14733}
14734
14735/// `[worktree] setup` hides its products per worktree, which needs
14736/// `extensions.worktreeConfig`. Taken once per run and released with the run's
14737/// worktrees, like the hook's; every place that runs setup calls this first.
14738async fn ensure_setup_config(state: &mut RunState, repo: &Path) -> Result<()> {
14739    if !state.config.worktree.setup.is_empty() && !state.enabled_worktree_config {
14740        git::acquire_worktree_config(repo).await?;
14741        state.enabled_worktree_config = true;
14742    }
14743    Ok(())
14744}
14745
14746#[cfg(test)]
14747mod tests {
14748    #[tokio::test]
14749    async fn launcher_base_fetch_requires_remote_success() {
14750        let tmp = tempfile::tempdir().unwrap();
14751        let repo = tmp.path().join("repo");
14752        let remote = tmp.path().join("remote");
14753        std::fs::create_dir(&repo).unwrap();
14754        std::fs::create_dir(&remote).unwrap();
14755        git::git(&remote, &["init", "--bare", "-b", "main"])
14756            .await
14757            .unwrap();
14758        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
14759        git::git(
14760            &repo,
14761            &[
14762                "-c",
14763                "user.name=Fixture",
14764                "-c",
14765                "user.email=fixture@example.invalid",
14766                "commit",
14767                "--allow-empty",
14768                "-m",
14769                "fixture",
14770            ],
14771        )
14772        .await
14773        .unwrap();
14774        git::git(
14775            &repo,
14776            &["remote", "add", "origin", remote.to_str().unwrap()],
14777        )
14778        .await
14779        .unwrap();
14780        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
14781        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
14782        assert_eq!(
14783            resolve_base(&repo, "main", "origin", None)
14784                .await
14785                .unwrap()
14786                .commit,
14787            head
14788        );
14789        #[cfg(unix)]
14790        {
14791            let policy: crate::config::Coordination = toml::from_str(
14792                "contract_file='fixture.contract'\ncontract_token='fixture-v1'\nlock_file='fixture.lock'",
14793            ).unwrap();
14794            std::fs::write(repo.join(".git/fixture.contract"), "fixture-v1").unwrap();
14795            std::fs::remove_file(repo.join(".git/FETCH_HEAD")).unwrap();
14796            let held = crate::repo_lock::SeatLease::operation_with(
14797                &repo,
14798                Some(&policy),
14799                &crate::repo_lock::WaitPolicy::default(),
14800            )
14801            .await
14802            .unwrap();
14803            assert!(held.is_some());
14804            let fetch = resolve_base(&repo, "main", "origin", Some(&policy));
14805            tokio::pin!(fetch);
14806            assert!(
14807                tokio::time::timeout(Duration::from_millis(50), &mut fetch)
14808                    .await
14809                    .is_err()
14810            );
14811            assert!(
14812                !repo.join(".git/FETCH_HEAD").exists(),
14813                "no fetch before admission"
14814            );
14815            drop(held);
14816            let fetched = fetch.await.unwrap();
14817            assert_eq!(fetched.commit, head);
14818            assert_eq!(fetched.remote, "origin");
14819            assert_eq!(fetched.branch, "main");
14820        }
14821        // A surviving tracking ref is not successful fetch evidence.
14822        git::git(
14823            &repo,
14824            &[
14825                "remote",
14826                "set-url",
14827                "origin",
14828                tmp.path().join("missing").to_str().unwrap(),
14829            ],
14830        )
14831        .await
14832        .unwrap();
14833        let error = resolve_base(&repo, "main", "origin", None)
14834            .await
14835            .unwrap_err()
14836            .to_string();
14837        assert!(error.contains("cannot read origin/main"));
14838        assert!(error.contains("refusing to branch off"));
14839    }
14840
14841    #[test]
14842    fn should_retitle_only_replaces_magi_shaped_or_leaked_titles() {
14843        let leaked = vec!["chore(deps): update a crate".to_owned()];
14844        let own = "fix(daemon): apply a chosen action";
14845        assert!(should_retitle("", own, &leaked));
14846        assert!(should_retitle(
14847            &format!("{REVIEW_PROMPT_OPENING} `x`"),
14848            own,
14849            &leaked
14850        ));
14851        assert!(should_retitle(
14852            "chore: land candidate A of run 1",
14853            own,
14854            &leaked
14855        ));
14856        assert!(should_retitle(
14857            "magi: candidate A (uncommitted work)",
14858            own,
14859            &leaked
14860        ));
14861        assert!(should_retitle("chore(deps): update a crate", own, &leaked));
14862        assert!(!should_retitle("feat: renamed by hand", own, &leaked));
14863        assert!(!should_retitle("", "chore(deps): update a crate", &leaked));
14864    }
14865
14866    #[test]
14867    fn pr_merge_plan_creates_adopts_or_stops() {
14868        assert_eq!(pr_merge_plan(Ok(land::OpenPr::None)), PrPlan::Create);
14869        assert_eq!(
14870            pr_merge_plan(Ok(land::OpenPr::One {
14871                url: "u".into(),
14872                title: "t".into()
14873            })),
14874            PrPlan::Adopt {
14875                url: "u".into(),
14876                title: "t".into()
14877            }
14878        );
14879        let PrPlan::Stop(many) =
14880            pr_merge_plan(Ok(land::OpenPr::Many(vec!["a".into(), "b".into()])))
14881        else {
14882            panic!("many must stop");
14883        };
14884        assert!(many.contains('a') && many.contains('b'));
14885        let PrPlan::Stop(err) = pr_merge_plan(Err(anyhow::anyhow!("bad token"))) else {
14886            panic!("a failed lookup must stop");
14887        };
14888        assert!(err.contains("bad token"));
14889    }
14890
14891    use super::*;
14892    use crate::run::GateStatus;
14893    use std::collections::BTreeMap;
14894    use std::time::Duration;
14895
14896    fn conductor() -> AgentSpec {
14897        AgentSpec {
14898            id: "conductor".to_owned(),
14899            kind: crate::config::AgentKind::Command,
14900            model: None,
14901            command: vec!["true".to_owned()],
14902            extra_args: Vec::new(),
14903            env: BTreeMap::new(),
14904            prompt_delivery: None,
14905            max_turn_secs: None,
14906        }
14907    }
14908
14909    fn spec(id: &str) -> AgentSpec {
14910        AgentSpec {
14911            id: id.to_owned(),
14912            kind: crate::config::AgentKind::Command,
14913            model: None,
14914            command: vec!["true".to_owned()],
14915            extra_args: Vec::new(),
14916            env: BTreeMap::new(),
14917            prompt_delivery: None,
14918            max_turn_secs: None,
14919        }
14920    }
14921
14922    fn ids(xs: &[&str]) -> BTreeSet<String> {
14923        xs.iter().map(|s| (*s).to_owned()).collect()
14924    }
14925
14926    #[test]
14927    fn pick_successor_skips_an_agent_another_seat_holds() {
14928        // Seats a and b of roster [a, b, c]; a fails, b holds the other seat.
14929        let roster = [spec("a"), spec("b"), spec("c")];
14930        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
14931        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
14932    }
14933
14934    #[test]
14935    fn pick_successor_respects_the_occupant_after_an_earlier_handover() {
14936        // The other seat started on c but was handed to d; c is free again.
14937        let roster = [spec("a"), spec("b"), spec("c"), spec("d")];
14938        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
14939        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
14940        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b", "c"]));
14941        assert_eq!(next.map(|s| s.id.as_str()), Some("d"));
14942    }
14943
14944    #[test]
14945    fn pick_successor_falls_back_to_a_duplicate_when_no_distinct_agent_remains() {
14946        let roster = [spec("a"), spec("b")];
14947        let next = pick_successor(&roster, 0, &ids(&["a"]), None, &ids(&["b"]));
14948        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14949        let carried = ids(&["b"]);
14950        let next = pick_successor(&roster, 0, &ids(&["a"]), Some(&carried), &ids(&["b"]));
14951        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14952    }
14953
14954    #[test]
14955    fn pick_successor_returns_none_without_any_untried_successor() {
14956        let roster = [spec("a"), spec("b")];
14957        assert!(pick_successor(&roster, 1, &ids(&["b"]), None, &ids(&["a"])).is_none());
14958        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), None, &ids(&[])).is_none());
14959        let carried = ids(&["a"]);
14960        assert!(pick_successor(&roster, 0, &ids(&["a", "b"]), Some(&carried), &ids(&[])).is_none());
14961    }
14962
14963    #[test]
14964    fn pick_successor_rescue_avoids_another_seats_occupant() {
14965        // b is a carried failure and free; a is held by the other seat.
14966        let roster = [spec("a"), spec("b"), spec("c")];
14967        let carried = ids(&["b", "c"]);
14968        let next = pick_successor(&roster, 2, &ids(&["c"]), Some(&carried), &ids(&["a"]));
14969        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14970    }
14971
14972    #[test]
14973    fn next_for_seat_prefers_an_agent_that_has_not_failed() {
14974        let roster = [spec("a"), spec("b"), spec("c")];
14975        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["b"]));
14976        assert_eq!(next.map(|s| s.id.as_str()), Some("c"));
14977    }
14978
14979    #[test]
14980    fn next_for_seat_rescues_a_failed_agent_only_when_nothing_else_is_left() {
14981        let roster = [spec("a"), spec("b"), spec("c")];
14982        let failed = ids(&["a", "b", "c"]);
14983        // Rescue looks at the whole roster, once per id, then runs out.
14984        let mut tried = ids(&["b"]);
14985        let first = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
14986        assert_eq!(first.id, "a");
14987        tried.insert(first.id.clone());
14988        let second = next_for_seat(&roster, 1, &tried, &failed).expect("rescue");
14989        assert_eq!(second.id, "c");
14990        tried.insert(second.id.clone());
14991        assert!(next_for_seat(&roster, 1, &tried, &failed).is_none());
14992    }
14993
14994    #[test]
14995    fn next_for_seat_ignores_failed_ids_no_longer_on_the_roster() {
14996        let roster = [spec("a"), spec("b")];
14997        let next = next_for_seat(&roster, 0, &ids(&["a"]), &ids(&["gone"]));
14998        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
14999    }
15000
15001    #[test]
15002    fn pick_start_spec_starts_on_the_last_answerer_when_still_eligible() {
15003        let roster = [spec("a"), spec("b"), spec("c")];
15004        let h = SeatHistory {
15005            failed: ids(&["a"]),
15006            last_ok: Some("b".to_owned()),
15007            last_fail: None,
15008        };
15009        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&h)).id, "b");
15010        // A last answerer that left the roster, or later failed, is ignored.
15011        let gone = SeatHistory {
15012            last_ok: Some("zzz".to_owned()),
15013            ..h.clone()
15014        };
15015        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&gone)).id, "b");
15016        let failed = SeatHistory {
15017            failed: ids(&["a", "b"]),
15018            last_ok: Some("b".to_owned()),
15019            last_fail: None,
15020        };
15021        assert_eq!(pick_start_spec(&roster, spec("a"), Some(&failed)).id, "c");
15022    }
15023
15024    #[test]
15025    fn handover_seat_mints_a_session_id_distinct_from_the_previous_agents() {
15026        let first = SeatState::new("review-1", "alpha", 7);
15027        let next = handover_seat("review-1", "gamma", 7);
15028        assert_ne!(first.claude_session, next.claude_session);
15029    }
15030
15031    #[test]
15032    fn re_handing_a_seat_to_the_same_agent_mints_a_new_session_id() {
15033        let mut state = state_with_summary("x", "y");
15034        let a = handover_seat("review-1", "beta", state.next_seat_seed());
15035        let b = handover_seat("review-1", "beta", state.next_seat_seed());
15036        assert_ne!(a.claude_session, b.claude_session);
15037    }
15038
15039    #[test]
15040    fn pick_start_spec_falls_back_to_the_spec_when_the_whole_roster_failed() {
15041        let roster = [spec("a"), spec("b")];
15042        let h = SeatHistory {
15043            failed: ids(&["a", "b"]),
15044            ..SeatHistory::default()
15045        };
15046        assert_eq!(pick_start_spec(&roster, spec("b"), Some(&h)).id, "b");
15047        assert_eq!(pick_start_spec(&roster, spec("b"), None).id, "b");
15048        assert_eq!(pick_start_spec(&[], spec("b"), Some(&h)).id, "b");
15049    }
15050
15051    // `next_untried_in_roster` is the property `resume_seat_handovers`'s own
15052    // fallback loop depends on to terminate: it must walk forward from the
15053    // seat's own position, never restart at the front of the roster, and it
15054    // must never hand back an id already tried, however many times that id
15055    // happens to appear.
15056
15057    #[test]
15058    fn failure_signature_ignores_numbers_and_paths() {
15059        assert_eq!(
15060            failure_signature("exited with Some(2) and no usable output"),
15061            failure_signature("exited with Some(137) and no usable output")
15062        );
15063        assert_eq!(
15064            failure_signature("process exited with no usable output (exit code 2)"),
15065            failure_signature("process exited with no usable output (exit code 137)")
15066        );
15067        for (old, new) in [
15068            (
15069                "exited with Some(2) and no usable output",
15070                "process exited with no usable output (exit code 2)",
15071            ),
15072            (
15073                "exited with None and no usable output",
15074                "process exited with no usable output (exit code unavailable)",
15075            ),
15076        ] {
15077            let previous = FailClass::Other(failure_signature(old));
15078            let current = FailClass::Other(failure_signature(new));
15079            assert_eq!(previous, current, "resumption retains the failure class");
15080            assert!(!should_hand_over(Some(&previous), &current));
15081        }
15082        assert_eq!(
15083            failure_signature("cannot open /tmp/a/b.txt: denied\nsecond line"),
15084            failure_signature("cannot open /var/x.txt: denied")
15085        );
15086        assert_ne!(failure_signature("boom"), failure_signature("bang"));
15087    }
15088
15089    #[test]
15090    fn quota_and_timeout_always_hand_over_other_failures_stop_on_a_repeat() {
15091        let other = FailClass::Other("x".into());
15092        assert!(should_hand_over(None, &FailClass::Quota));
15093        assert!(should_hand_over(Some(&other), &FailClass::Quota));
15094        assert!(should_hand_over(
15095            Some(&FailClass::Timeout),
15096            &FailClass::Timeout
15097        ));
15098        assert!(should_hand_over(None, &other));
15099        assert!(!should_hand_over(Some(&other), &other));
15100        assert!(should_hand_over(
15101            Some(&other),
15102            &FailClass::Other("y".into())
15103        ));
15104        // A quota or timeout in between ends the run of identical failures.
15105        assert!(should_hand_over(Some(&FailClass::Timeout), &other));
15106        assert!(should_hand_over(Some(&FailClass::Quota), &other));
15107    }
15108
15109    #[test]
15110    fn a_handover_seat_never_reuses_the_previous_agents_session_id() {
15111        let a = SeatState::new("judge-1", "alpha", 7);
15112        let b = handover_seat("judge-1", "beta", 7);
15113        assert_ne!(a.claude_session, b.claude_session);
15114        assert_eq!(b.turns, 0);
15115    }
15116
15117    #[test]
15118    fn a_timeout_is_classified_apart_from_other_failures() {
15119        assert_eq!(
15120            FailClass::of(&AgentOutcome::Failed(TIMED_OUT.to_owned())),
15121            Some(FailClass::Timeout)
15122        );
15123        assert!(matches!(
15124            FailClass::of(&AgentOutcome::Failed("boom".to_owned())),
15125            Some(FailClass::Other(_))
15126        ));
15127    }
15128
15129    #[test]
15130    fn next_untried_in_roster_walks_forward_from_the_seats_own_position() {
15131        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
15132        let tried = BTreeSet::from(["beta".to_owned()]);
15133        // beta sits at index 1; the next candidate is gamma, never alpha —
15134        // which is very likely a different candidate slot's own agent.
15135        let next = next_untried_in_roster(&roster, 1, &tried);
15136        assert_eq!(next.map(|s| s.id.as_str()), Some("gamma"));
15137    }
15138
15139    #[test]
15140    fn next_untried_in_roster_does_not_wrap_back_past_its_own_start() {
15141        let roster = vec![spec("alpha"), spec("beta")];
15142        let tried = BTreeSet::from(["beta".to_owned()]);
15143        // beta is the roster's last entry: nothing follows it, and alpha —
15144        // earlier in the roster, almost certainly a different candidate
15145        // slot's own agent — must not be reached by wrapping back to it.
15146        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
15147    }
15148
15149    #[test]
15150    fn next_untried_in_roster_stops_once_the_tail_is_exhausted_even_if_earlier_ids_are_untried() {
15151        let roster = vec![spec("alpha"), spec("beta"), spec("gamma")];
15152        let tried = BTreeSet::from(["beta".to_owned(), "gamma".to_owned()]);
15153        // beta (index 1) and gamma (index 2, the only entry after it) have
15154        // both been tried; alpha (index 0) never has, but it comes before
15155        // beta's own position, so there is nothing further for this seat.
15156        assert!(next_untried_in_roster(&roster, 1, &tried).is_none());
15157    }
15158
15159    #[test]
15160    fn next_untried_in_roster_skips_ids_already_tried_even_when_duplicated() {
15161        let roster = vec![spec("a"), spec("a"), spec("b")];
15162        let tried = BTreeSet::from(["a".to_owned()]);
15163        let next = next_untried_in_roster(&roster, 0, &tried);
15164        assert_eq!(next.map(|s| s.id.as_str()), Some("b"));
15165    }
15166
15167    #[test]
15168    fn next_untried_in_roster_returns_none_once_every_id_is_tried() {
15169        let roster = vec![spec("a"), spec("b")];
15170        let tried = BTreeSet::from(["a".to_owned(), "b".to_owned()]);
15171        assert!(next_untried_in_roster(&roster, 0, &tried).is_none());
15172    }
15173
15174    #[test]
15175    fn remove_if_empty_only_ever_takes_a_bare_directory() {
15176        let dir = tempfile::tempdir().unwrap();
15177        let bay = dir.path().join("ffff");
15178
15179        // Not there yet: nothing to do, nothing to panic on.
15180        remove_if_empty(&bay);
15181        assert!(!bay.exists());
15182
15183        // Something still inside - the winner's worktree, or a stray file -
15184        // keeps the directory standing.
15185        std::fs::create_dir_all(bay.join("cand-A")).unwrap();
15186        remove_if_empty(&bay);
15187        assert!(bay.exists(), "non-empty directory must survive");
15188
15189        // Once the last entry is gone, so is the directory itself.
15190        std::fs::remove_dir(bay.join("cand-A")).unwrap();
15191        remove_if_empty(&bay);
15192        assert!(!bay.exists(), "an empty bay is a leftover, not a record");
15193    }
15194
15195    // `round_is_clean` is the exact decision this task fixed: a round with a
15196    // seat that never answered must not read the same as a round every seat
15197    // actually reviewed. These are deterministic and process-free by design —
15198    // the equivalent end-to-end check (a real reviewer timing out under a
15199    // live graph run) is a genuine race against wall-clock contention, and a
15200    // spawn slow enough to blow even a generous budget under a loaded test
15201    // run must not turn this specific regression check flaky.
15202
15203    #[test]
15204    fn a_full_panel_that_found_nothing_is_clean() {
15205        assert!(round_is_clean(
15206            0,
15207            true,
15208            2,
15209            2,
15210            0,
15211            IncompleteReviewPolicy::Block
15212        ));
15213    }
15214
15215    #[test]
15216    fn a_missing_seat_is_never_clean_under_the_default_policy() {
15217        assert!(!round_is_clean(
15218            0,
15219            true,
15220            1,
15221            2,
15222            0,
15223            IncompleteReviewPolicy::Block
15224        ));
15225    }
15226
15227    #[test]
15228    fn warn_policy_still_refuses_a_missing_seat_with_open_findings() {
15229        assert!(!round_is_clean(
15230            1,
15231            true,
15232            1,
15233            2,
15234            0,
15235            IncompleteReviewPolicy::Warn
15236        ));
15237    }
15238
15239    #[test]
15240    fn warn_policy_gates_a_missing_seat_once_what_answered_is_clean() {
15241        assert!(round_is_clean(
15242            0,
15243            true,
15244            1,
15245            2,
15246            0,
15247            IncompleteReviewPolicy::Warn
15248        ));
15249    }
15250
15251    #[test]
15252    fn a_full_panel_with_an_open_finding_is_not_clean() {
15253        assert!(!round_is_clean(
15254            1,
15255            true,
15256            2,
15257            2,
15258            0,
15259            IncompleteReviewPolicy::Block
15260        ));
15261    }
15262
15263    #[test]
15264    fn a_full_panel_with_a_red_e2e_is_not_clean() {
15265        assert!(!round_is_clean(
15266            0,
15267            false,
15268            2,
15269            2,
15270            0,
15271            IncompleteReviewPolicy::Block
15272        ));
15273    }
15274
15275    // The stall this task closes: under the default `block` policy, a seat
15276    // missing only because it was rate limited must not force a wait for a
15277    // session limit that will not lift by the next round. `round_is_clean`
15278    // is where that quorum carve-out lives; the review loop around it never
15279    // changes what a reviewer's vote or a finding's severity means.
15280
15281    #[test]
15282    fn a_seat_missing_only_to_its_own_quota_is_clean_under_the_default_policy() {
15283        // 1 of 2 answered, and the one missing was quota'd — the exact
15284        // "review-2 rate limited (quota)" shape from the field report.
15285        assert!(round_is_clean(
15286            0,
15287            true,
15288            1,
15289            2,
15290            1,
15291            IncompleteReviewPolicy::Block
15292        ));
15293    }
15294
15295    #[test]
15296    fn a_seat_missing_for_a_reason_other_than_quota_still_waits() {
15297        // 1 of 2 answered, but the miss was a crash/timeout/parse failure,
15298        // not a quota loss (`quota_missing` stays 0) — worth another try.
15299        assert!(!round_is_clean(
15300            0,
15301            true,
15302            1,
15303            2,
15304            0,
15305            IncompleteReviewPolicy::Block
15306        ));
15307    }
15308
15309    #[test]
15310    fn a_quota_loss_does_not_excuse_an_open_finding_or_a_red_e2e() {
15311        assert!(!round_is_clean(
15312            1,
15313            true,
15314            1,
15315            2,
15316            1,
15317            IncompleteReviewPolicy::Block
15318        ));
15319        assert!(!round_is_clean(
15320            0,
15321            false,
15322            1,
15323            2,
15324            1,
15325            IncompleteReviewPolicy::Block
15326        ));
15327    }
15328
15329    #[test]
15330    fn a_panel_lost_entirely_to_quota_still_waits_rather_than_deciding_on_nobody() {
15331        // Every seat quota'd, nobody answered: there is no panel to decide
15332        // on, so this must fall through to the existing block-and-retry
15333        // fallback rather than call an unreviewed patch clean.
15334        assert!(!round_is_clean(
15335            0,
15336            true,
15337            0,
15338            2,
15339            2,
15340            IncompleteReviewPolicy::Block
15341        ));
15342    }
15343
15344    fn outcome(code: Option<i32>, resource_blocked: bool) -> CommandOutcome {
15345        CommandOutcome {
15346            command: "test".to_owned(),
15347            code,
15348            output_tail: String::new(),
15349            duration_ms: 0,
15350            resource_blocked,
15351            ..Default::default()
15352        }
15353    }
15354
15355    #[cfg(unix)]
15356    #[tokio::test]
15357    async fn incremental_admission_is_a_resource_hold_without_a_build_retry() {
15358        ask_test_home();
15359        let temp = tempfile::tempdir().unwrap();
15360        let mut runner = runner_at(RunStatus::Gating);
15361        let shell = vec!["sh".to_owned(), "-c".to_owned()];
15362        let commands = vec![
15363            "printf '%s\\n' 'incremental cache admission blocked: budget exhausted' 'error: could not compile fixture'; exit 101".to_owned(),
15364            "touch must-not-run".to_owned(),
15365        ];
15366        let (outcomes, retried, pids) = run_e2e_with_retry(
15367            &mut runner.state,
15368            &shell,
15369            &commands,
15370            temp.path(),
15371            Duration::from_secs(5),
15372            "fixture",
15373            None,
15374        )
15375        .await;
15376        assert_eq!(outcomes.len(), 1);
15377        assert!(outcomes[0].resource_blocked);
15378        assert!(!outcomes[0].build_failed());
15379        assert!(!retried);
15380        assert!(pids.is_empty());
15381        assert!(!temp.path().join("must-not-run").exists());
15382        assert_eq!(
15383            runner.state.resource_block.as_ref().unwrap().kind,
15384            "incremental cache admission"
15385        );
15386    }
15387
15388    #[test]
15389    fn verify_is_inconclusive_only_when_a_resource_blocked_outcome_is_present() {
15390        assert!(!verify_inconclusive(&[outcome(Some(0), false)]));
15391        assert!(
15392            !verify_inconclusive(&[outcome(Some(1), false)]),
15393            "an ordinary failure is still evidence about the patch"
15394        );
15395        assert!(verify_inconclusive(&[outcome(None, true)]));
15396        assert!(
15397            verify_inconclusive(&[outcome(Some(0), false), outcome(None, true)]),
15398            "one inconclusive outcome taints the whole batch"
15399        );
15400        assert!(!verify_inconclusive(&[]));
15401    }
15402
15403    #[tokio::test]
15404    async fn timed_out_pid_waiting_returns_as_soon_as_every_pid_is_confirmed_dead() {
15405        // Alive for the first two checks, then dead - confirms the loop
15406        // actually re-polls rather than deciding once and sleeping out the
15407        // ceiling regardless.
15408        let calls = std::sync::atomic::AtomicUsize::new(0);
15409        let started = Instant::now();
15410        wait_for_pids_with(
15411            &[123],
15412            |_| calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 2,
15413            Duration::from_millis(5),
15414            Duration::from_secs(5),
15415        )
15416        .await;
15417        assert!(
15418            calls.load(std::sync::atomic::Ordering::SeqCst) >= 3,
15419            "must keep checking rather than deciding on the first answer"
15420        );
15421        assert!(
15422            started.elapsed() < Duration::from_secs(1),
15423            "must return the moment it is confirmed dead, not wait out the ceiling"
15424        );
15425    }
15426
15427    #[tokio::test]
15428    async fn timed_out_pid_waiting_gives_up_at_its_ceiling_if_never_confirmed_dead() {
15429        let started = Instant::now();
15430        wait_for_pids_with(
15431            &[123],
15432            |_| true, // never reports dead
15433            Duration::from_millis(5),
15434            Duration::from_millis(30),
15435        )
15436        .await;
15437        let elapsed = started.elapsed();
15438        assert!(
15439            elapsed >= Duration::from_millis(30),
15440            "must not give up before its own ceiling: {elapsed:?}"
15441        );
15442        assert!(
15443            elapsed < Duration::from_secs(1),
15444            "must not wait past its own ceiling either: {elapsed:?}"
15445        );
15446    }
15447
15448    #[tokio::test]
15449    async fn timed_out_pid_waiting_is_a_no_op_when_nothing_was_still_running() {
15450        let started = Instant::now();
15451        wait_for_pids_with(
15452            &[],
15453            |_| true,
15454            Duration::from_secs(5),
15455            Duration::from_secs(5),
15456        )
15457        .await;
15458        assert!(
15459            started.elapsed() < Duration::from_millis(200),
15460            "an empty pid list has nothing to confirm"
15461        );
15462    }
15463
15464    // `review_conclusion` is the exact decision the review hand-off task
15465    // fixed: a round budget spent (or a tree that stopped moving) must not
15466    // collapse into `Blocked` regardless of what verification actually
15467    // said. Deterministic and process-free for the same reason the
15468    // `round_is_clean` family above is.
15469    fn review_round(
15470        clean: bool,
15471        blocking: usize,
15472        answered: usize,
15473        expected: usize,
15474        progressed: bool,
15475        e2e_ok: bool,
15476    ) -> ReviewRound {
15477        ReviewRound {
15478            round: 1,
15479            head: "h".to_owned(),
15480            verified_head: None,
15481            verified_at: None,
15482            reviews: Vec::new(),
15483            e2e: vec![CommandOutcome {
15484                command: "test".to_owned(),
15485                code: Some(if e2e_ok { 0 } else { 1 }),
15486                output_tail: String::new(),
15487                duration_ms: 0,
15488                resource_blocked: false,
15489                ..Default::default()
15490            }],
15491            verify_retried: false,
15492            e2e_deferred: false,
15493            e2e_defer_reason: None,
15494            fix: None,
15495            blocking,
15496            answered,
15497            expected,
15498            clean,
15499            progressed,
15500            vote_split: false,
15501            reconsideration: Vec::new(),
15502            verdict: None,
15503        }
15504    }
15505
15506    #[test]
15507    fn review_conclusion_is_none_when_nothing_has_run() {
15508        assert_eq!(review_conclusion(&[], 3), None);
15509    }
15510
15511    #[test]
15512    fn review_conclusion_is_none_while_rounds_remain() {
15513        let rounds = vec![review_round(false, 1, 2, 2, true, true)];
15514        assert_eq!(review_conclusion(&rounds, 3), None);
15515    }
15516
15517    #[test]
15518    fn review_conclusion_is_gating_once_a_round_is_clean() {
15519        let rounds = vec![review_round(true, 0, 2, 2, false, true)];
15520        assert_eq!(review_conclusion(&rounds, 3), Some(RunStatus::Gating));
15521    }
15522
15523    #[test]
15524    fn review_conclusion_hands_off_when_the_budget_is_spent_and_e2e_is_green() {
15525        let rounds = vec![
15526            review_round(false, 1, 2, 2, true, true),
15527            review_round(false, 1, 2, 2, true, true),
15528        ];
15529        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Gating));
15530    }
15531
15532    #[test]
15533    fn review_conclusion_blocks_when_the_budget_is_spent_and_e2e_is_red() {
15534        let rounds = vec![
15535            review_round(false, 1, 2, 2, true, true),
15536            review_round(false, 1, 2, 2, true, false),
15537        ];
15538        assert_eq!(review_conclusion(&rounds, 2), Some(RunStatus::Blocked));
15539    }
15540
15541    #[test]
15542    fn review_conclusion_stays_none_when_the_budget_is_spent_but_the_last_round_could_not_run() {
15543        // Magi never got a command to run against this round's own head — a
15544        // resource-blocked attempt, not a red one — so this must never
15545        // settle on `Blocked` the way a genuine e2e failure would. `None`
15546        // here is what tells `Runner::review_loop` to retry the check
15547        // itself rather than trust this cheap recomputation with a verdict
15548        // it cannot actually produce.
15549        let mut blocked = review_round(false, 1, 2, 2, true, false);
15550        blocked.e2e[0].resource_blocked = true;
15551        let rounds = vec![review_round(false, 1, 2, 2, true, true), blocked];
15552        assert_eq!(review_conclusion(&rounds, 2), None);
15553    }
15554
15555    #[test]
15556    fn review_conclusion_blocks_an_incomplete_panel_that_raised_nothing_even_with_green_e2e() {
15557        // Missing input, not a verified tree — never a hand-off candidate.
15558        let rounds = vec![review_round(false, 0, 1, 2, false, true)];
15559        assert_eq!(review_conclusion(&rounds, 1), Some(RunStatus::Blocked));
15560    }
15561
15562    #[test]
15563    fn review_conclusion_hands_off_when_the_tree_stagnates_before_the_budget_is_spent() {
15564        let rounds = vec![
15565            review_round(false, 1, 2, 2, false, true),
15566            review_round(false, 1, 2, 2, false, true),
15567        ];
15568        assert_eq!(review_conclusion(&rounds, 10), Some(RunStatus::Gating));
15569    }
15570
15571    fn secs(n: u64) -> Duration {
15572        Duration::from_secs(n)
15573    }
15574
15575    /// A throwaway repo with one commit on `main`, for tests that need `merge`
15576    /// to make real (and, if it runs at all, real*ly fail*) git calls.
15577    #[tokio::test]
15578    async fn selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync() {
15579        const CHILD: &str = "MAGI_SELECTED_PUBLIC_ANCESTRY_TEST";
15580        if std::env::var_os(CHILD).is_none() {
15581            // Other tests reconcile every run in the process-global home,
15582            // briefly taking owner locks. This ancestry test expects an idle
15583            // predecessor, so give it its own process and pinned test home.
15584            let output = std::process::Command::new(std::env::current_exe().unwrap())
15585                .args([
15586                    "--exact",
15587                    "graph::tests::selected_public_ancestry_survives_obsolete_candidate_and_current_base_sync",
15588                    "--nocapture",
15589                ])
15590                .env(CHILD, "1")
15591                .env_remove("MAGI_WORKER_HOME")
15592                .env_remove("MAGI_WORKER_ID")
15593                .output()
15594                .unwrap();
15595            assert!(
15596                output.status.success()
15597                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
15598                "{}\n{}",
15599                String::from_utf8_lossy(&output.stdout),
15600                String::from_utf8_lossy(&output.stderr)
15601            );
15602            return;
15603        }
15604        ask_test_home();
15605        let tmp = tempfile::tempdir().unwrap();
15606        let repo = tmp.path().join("repo");
15607        std::fs::create_dir_all(&repo).unwrap();
15608        init_repo(&repo);
15609        let g = |args: &[&str]| {
15610            let out = std::process::Command::new("git")
15611                .args(args)
15612                .current_dir(&repo)
15613                .quiet()
15614                .output()
15615                .unwrap();
15616            assert!(
15617                out.status.success(),
15618                "{}",
15619                String::from_utf8_lossy(&out.stderr)
15620            );
15621        };
15622        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
15623        g(&["checkout", "-b", "historical"]);
15624        std::fs::write(repo.join("implementation"), "incompatible alternative").unwrap();
15625        g(&["add", "."]);
15626        g(&["commit", "-m", "old alternative"]);
15627        let obsolete = git::rev_parse(&repo, "HEAD").await.unwrap();
15628        g(&["checkout", "-b", "magi/task-selected", &base]);
15629        std::fs::write(repo.join("infrastructure"), "prerequisite").unwrap();
15630        g(&["add", "."]);
15631        g(&["commit", "-m", "measurement infrastructure"]);
15632        let prerequisite = git::rev_parse(&repo, "HEAD").await.unwrap();
15633        std::fs::write(repo.join("implementation"), "measured implementation").unwrap();
15634        g(&["add", "."]);
15635        g(&["commit", "-m", "dependent implementation"]);
15636        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
15637        g(&["checkout", "main"]);
15638        std::fs::write(repo.join("unrelated"), "current main change").unwrap();
15639        g(&["add", "."]);
15640        g(&["commit", "-m", "unrelated base change"]);
15641        let current = git::rev_parse(&repo, "HEAD").await.unwrap();
15642        let origin = tmp.path().join("origin.git");
15643        g(&[
15644            "clone",
15645            "--bare",
15646            repo.to_str().unwrap(),
15647            origin.to_str().unwrap(),
15648        ]);
15649        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
15650        g(&["fetch", "origin"]);
15651        let selection = crate::pr_recovery::Selection {
15652            url: "https://example.test/project/pull/1".into(),
15653            branch: "magi/task-selected".into(),
15654            head: head.clone(),
15655            source_head: None,
15656            source_run: None,
15657            source_proof: None,
15658            disposition: Some(crate::pr_recovery::Disposition::Review),
15659            instruction: "preserve measured behavior".into(),
15660            approved_at: jiff::Timestamp::now(),
15661        };
15662        let mut template = runner_at(RunStatus::Reviewing);
15663        template.state.repo = repo.clone();
15664        template.state.base_commit = current.clone();
15665        template.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
15666        template.state.origin = Some(crate::run::Origin::queue("selected"));
15667        template.state.pr_head = Some(selection.branch.clone());
15668        template.state.pr_recovery = Some(selection.clone());
15669        let mut runner =
15670            Runner::open_selected(&repo, template.state, template.roles, 1, current, selection)
15671                .await
15672                .unwrap();
15673        let wt = runner.state.winner().unwrap().worktree.clone();
15674        assert_eq!(git::rev_parse(&wt, "HEAD").await.unwrap(), head);
15675        assert!(git::is_ancestor(&wt, &prerequisite, "HEAD").await);
15676        assert!(!git::is_ancestor(&wt, &obsolete, "HEAD").await);
15677        assert!(runner.state.seeds.is_empty());
15678        assert_eq!(runner.state.instruction, "preserve measured behavior");
15679        runner.sync_to_base().await.unwrap();
15680        assert_eq!(
15681            std::fs::read_to_string(wt.join("infrastructure")).unwrap(),
15682            "prerequisite"
15683        );
15684        assert_eq!(
15685            std::fs::read_to_string(wt.join("implementation")).unwrap(),
15686            "measured implementation"
15687        );
15688        assert_eq!(
15689            std::fs::read_to_string(wt.join("unrelated")).unwrap(),
15690            "current main change"
15691        );
15692        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
15693        assert_eq!(
15694            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
15695            head
15696        );
15697
15698        // A failed selected-source setup stays inspectable, never resumable as a new competition.
15699        let mut partial = runner_at(RunStatus::Reviewing);
15700        partial.state.repo = repo.clone();
15701        partial.state.config.graph.worktree_root = Some(tmp.path().join("failed-worktrees"));
15702        partial.state.config.worktree.setup = vec![crate::config::SetupStep {
15703            run: Some("exit 1".into()),
15704            ..Default::default()
15705        }];
15706        let selection = runner.state.pr_recovery.clone().unwrap();
15707        partial.state.pr_recovery = Some(selection.clone());
15708        partial.state.pr_head = Some(selection.branch.clone());
15709        partial.state.origin = Some(crate::run::Origin::queue("selected"));
15710        let id = partial.state.id.clone();
15711        let error = match Runner::open_selected(
15712            &repo,
15713            partial.state,
15714            partial.roles,
15715            1,
15716            runner.state.base_commit.clone(),
15717            selection,
15718        )
15719        .await
15720        {
15721            Ok(_) => panic!("setup must fail"),
15722            Err(e) => e,
15723        };
15724        assert_eq!(
15725            error
15726                .downcast_ref::<crate::run::StartupFailure>()
15727                .unwrap()
15728                .run,
15729            id
15730        );
15731        let failed = RunState::load(&id).unwrap();
15732        assert_eq!(failed.status, RunStatus::Failed);
15733        assert_eq!(failed.liveness(false), crate::run::Liveness::Dead);
15734        assert!(Runner::resume(&id).is_err());
15735        runner.state.status = RunStatus::Ready;
15736        runner.state.driver_exited = true;
15737        runner.state.save().unwrap();
15738        let mut retry = runner_at(RunStatus::Reviewing);
15739        retry.state.repo = repo.clone();
15740        retry.state.config.graph.worktree_root = Some(tmp.path().join("retry-worktrees"));
15741        let mut reselected = runner.state.pr_recovery.clone().unwrap();
15742        reselected.approved_at = jiff::Timestamp::now();
15743        retry.state.origin = Some(crate::run::Origin::queue("selected"));
15744        retry.state.pr_head = Some(reselected.branch.clone());
15745        retry.state.pr_recovery = Some(reselected.clone());
15746        crate::pr_head::check_predecessors(&retry.state, &reselected.branch)
15747            .await
15748            .unwrap();
15749        let restarted = Runner::open_selected(
15750            &repo,
15751            retry.state,
15752            retry.roles,
15753            1,
15754            runner.state.base_commit.clone(),
15755            reselected,
15756        )
15757        .await
15758        .unwrap();
15759        assert_eq!(
15760            git::rev_parse(&restarted.state.winner().unwrap().worktree, "HEAD")
15761                .await
15762                .unwrap(),
15763            head
15764        );
15765        assert_eq!(git::rev_parse(&repo, "historical").await.unwrap(), obsolete);
15766        assert_eq!(
15767            git::rev_parse(&repo, "magi/task-selected").await.unwrap(),
15768            head
15769        );
15770    }
15771
15772    #[tokio::test]
15773    #[cfg(unix)]
15774    async fn fallback_and_interrupted_restoration_require_coordination() {
15775        use std::os::fd::AsRawFd as _;
15776        ask_test_home();
15777        let tmp = tempfile::tempdir().unwrap();
15778        let mut runner = registered_runner(tmp.path()).await;
15779        runner.state.config.graph.timeout_resource_wait = 1;
15780        let winner = runner.state.candidates[0].clone();
15781        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
15782        let leftover = winner.worktree.join("leftover");
15783        std::fs::write(&leftover, "untrusted edits").unwrap();
15784        let next = tmp.path().join("next-fixer");
15785        let mut failed = spec("first");
15786        failed.command = vec!["sh".into(), "-c".into(), "exit 1".into()];
15787        let mut successor = spec("second");
15788        successor.command = vec![
15789            "sh".into(),
15790            "-c".into(),
15791            format!("touch '{}'; echo done", next.display()),
15792        ];
15793        let attempts = vec![
15794            (failed.clone(), "first".into()),
15795            (successor.clone(), "second".into()),
15796        ];
15797        let lock_path = runner.state.repo.join(".git/updater.lock");
15798        let external = std::fs::File::create(&lock_path).unwrap();
15799        assert_eq!(
15800            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
15801            0
15802        );
15803        let artifacts = tmp.path().join("artifacts");
15804        let build = |spec, seat| SeatJob {
15805            spec,
15806            seat,
15807            cwd: winner.worktree.clone(),
15808            prompt: "fixture".into(),
15809            timeout: Duration::from_secs(10),
15810            allow_write: true,
15811            sessions: false,
15812            artifacts: artifacts.clone(),
15813            stem: "fix".into(),
15814            handover: None,
15815        };
15816        let (_, _, out) = runner
15817            .ask_fixer_among(
15818                attempts.clone(),
15819                "graft",
15820                None,
15821                Some((&winner.worktree, &head)),
15822                build,
15823            )
15824            .await;
15825        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
15826        assert!(leftover.exists(), "contention must prevent clean");
15827        assert!(!next.exists());
15828        assert!(runner.state.handovers.is_empty());
15829        // Early interrupted-repair rollback uses the same protected route.
15830        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
15831            from_run: "earlier".into(),
15832            generation: 1,
15833            mode: crate::recovery::Mode::VerifyRepair,
15834            reasons: Vec::new(),
15835            reviewed_head: None,
15836            rounds: Vec::new(),
15837            open_findings: Vec::new(),
15838            evidence: None,
15839            criteria_inherited: true,
15840            repair: crate::recovery::Repair::Started {
15841                before: head.clone(),
15842            },
15843        });
15844        assert!(
15845            runner
15846                .recovery_repair(&winner)
15847                .await
15848                .unwrap_err()
15849                .is::<crate::repo_lock::ResourceBlocked>()
15850        );
15851        assert!(matches!(
15852            runner.state.recovery.as_ref().unwrap().repair,
15853            crate::recovery::Repair::Started { .. }
15854        ));
15855        assert!(leftover.exists());
15856        drop(external);
15857        runner.recovery_repair(&winner).await.unwrap();
15858        assert!(!leftover.exists());
15859        assert!(matches!(
15860            runner.state.recovery.as_ref().unwrap().repair,
15861            crate::recovery::Repair::Done { .. }
15862        ));
15863        // A hard lock-open failure also leaves HEAD and untracked work intact.
15864        std::fs::remove_file(&lock_path).unwrap();
15865        std::fs::create_dir(&lock_path).unwrap();
15866        std::fs::write(&leftover, "untrusted edits").unwrap();
15867        let (_, _, out) = runner
15868            .ask_fixer_among(
15869                attempts,
15870                "graft",
15871                None,
15872                Some((&winner.worktree, &head)),
15873                build,
15874            )
15875            .await;
15876        assert!(matches!(out, AgentOutcome::Failed(_)));
15877        assert!(leftover.exists());
15878        assert!(!next.exists());
15879        assert_eq!(
15880            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
15881            head
15882        );
15883    }
15884
15885    #[cfg(unix)]
15886    async fn registered_runner(root: &Path) -> Runner {
15887        repository_runner(root, crate::config::test_coordination()).await
15888    }
15889
15890    async fn repository_runner(
15891        root: &Path,
15892        coordination: Option<crate::config::Coordination>,
15893    ) -> Runner {
15894        ask_test_home();
15895        let repo = root.join("repo");
15896        std::fs::create_dir_all(&repo).unwrap();
15897        init_repo(&repo);
15898        if coordination.is_some() {
15899            std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
15900        }
15901        let mut runner = runner_at(RunStatus::Prep);
15902        runner.state.repo = repo.clone();
15903        runner.state.config.coordination = coordination;
15904        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
15905        runner.state.config.graph.worktree_root = Some(root.join("wt"));
15906        runner.state.config.graph.advise = false;
15907        runner.roles.implementers = vec![spec("implement")];
15908        runner.roles.judges = vec![spec("judge")];
15909        runner.prep().await.unwrap();
15910        runner
15911    }
15912
15913    const AUTH_OUTAGE: &str = r#"{"is_error":true,"terminal_reason":"api_error","result":"Failed to authenticate: OAuth session expired and could not be refreshed"}"#;
15914
15915    #[tokio::test]
15916    async fn all_unauthenticated_wave_stops_the_node_without_nudges() {
15917        let tmp = tempfile::tempdir().unwrap();
15918        let mut runner = repository_runner(tmp.path(), None).await;
15919        let prompts = runner.state.config.prompts.clone();
15920        let run = runner.state.id.clone();
15921        let ctx = WaveCtx {
15922            carry_seats: false,
15923            pauses: None,
15924            run: &run,
15925            node: "advise",
15926            prompts: &prompts,
15927            cache: None,
15928            round: None,
15929        };
15930        let jobs: Vec<_> = ["alpha", "beta"]
15931            .into_iter()
15932            .map(|id| SeatJob {
15933                spec: scripted(id, AUTH_OUTAGE),
15934                seat: SeatState::new(id, id, 7),
15935                prompt: "propose".into(),
15936                cwd: runner.state.candidates[0].worktree.clone(),
15937                timeout: Duration::from_secs(10),
15938                allow_write: false,
15939                sessions: false,
15940                artifacts: agent::artifacts_dir(&runner.state.dir()),
15941                stem: id.into(),
15942                handover: None,
15943            })
15944            .collect();
15945        let mut losses = Vec::new();
15946        let results = ask_wave_with(
15947            jobs.clone(),
15948            runner.sem.clone(),
15949            2,
15950            &[],
15951            &ctx,
15952            &mut losses,
15953            &mut runner.state,
15954            &|_: &str| Ok(()),
15955        )
15956        .await;
15957        assert!(
15958            results
15959                .iter()
15960                .all(|(seat, result, nudges)| seat.turns == 1 && result.is_err() && *nudges == 0)
15961        );
15962        assert_eq!(runner.state.quota.len(), 2);
15963        assert!(
15964            runner
15965                .state
15966                .quota
15967                .iter()
15968                .all(|q| q.cause == agent::QuotaCause::Authentication && !q.agent.is_empty())
15969        );
15970        assert!(!runner.state.advise_attempted);
15971        runner.stop_for_resource().unwrap();
15972        assert_eq!(runner.state.status, RunStatus::Blocked);
15973        assert_eq!(runner.state.resource_block.as_ref().unwrap().node, "advise");
15974        assert_eq!(
15975            runner.state.resource_block.as_ref().unwrap().kind,
15976            "agent authentication"
15977        );
15978        // A machine loss followed by an ordinary failure is not evidence
15979        // that the whole node was unavailable, and must not earn a refund.
15980        runner.state.resource_block = None;
15981        runner.state.quota.clear();
15982        let mut mixed = jobs;
15983        mixed[1].spec.command = vec!["false".into()];
15984        let results = ask_wave_with(
15985            mixed,
15986            runner.sem.clone(),
15987            0,
15988            &[],
15989            &ctx,
15990            &mut losses,
15991            &mut runner.state,
15992            &|_: &str| Ok(()),
15993        )
15994        .await;
15995        assert!(results.iter().all(|(_, res, _)| res.is_err()));
15996        assert!(runner.state.resource_block.is_none());
15997        assert_eq!(losses.len(), 1);
15998    }
15999
16000    #[tokio::test]
16001    async fn unauthenticated_implementation_keeps_its_candidate_pending() {
16002        let tmp = tempfile::tempdir().unwrap();
16003        let mut runner = repository_runner(tmp.path(), None).await;
16004        let implementer = scripted("implement", AUTH_OUTAGE);
16005        runner.roles.implementers = vec![implementer.clone()];
16006        runner.state.config.agents = vec![implementer];
16007        runner.implement().await.unwrap();
16008        assert_eq!(runner.state.status, RunStatus::Blocked);
16009        assert_eq!(runner.state.quota.len(), 1);
16010        assert_eq!(
16011            runner.state.quota[0].cause,
16012            agent::QuotaCause::Authentication
16013        );
16014        let candidate = &runner.state.candidates[0];
16015        assert!(candidate.failed.is_none() && !candidate.empty && candidate.commits == 0);
16016        assert_eq!(runner.state.seats["impl-A"].turns, 1);
16017    }
16018
16019    #[tokio::test]
16020    #[cfg(unix)]
16021    async fn parked_implementer_persists_completed_work() {
16022        for registered in [false, true] {
16023            let tmp = tempfile::tempdir().unwrap();
16024            let mut runner = registered_runner(tmp.path()).await;
16025            if !registered {
16026                std::fs::remove_file(runner.state.repo.join(".git/updater.contract")).unwrap();
16027            }
16028            let marker = tmp.path().join("started");
16029            let release = tmp.path().join("release");
16030            let mut implementer = spec("implement");
16031            implementer.command = vec![
16032                "sh".into(),
16033                "-c".into(),
16034                format!(
16035                    "touch '{}'; while [ ! -f '{}' ]; do sleep 0.01; done; echo completed > completed; echo saved-result",
16036                    marker.display(),
16037                    release.display()
16038                ),
16039            ];
16040            runner.roles.implementers = vec![implementer.clone()];
16041            runner.state.config.agents = vec![implementer];
16042            let pause = runner.pause.clone();
16043            let (result, ()) = tokio::join!(runner.implement(), async {
16044                tokio::time::timeout(Duration::from_secs(10), async {
16045                    while !marker.exists() {
16046                        tokio::time::sleep(Duration::from_millis(10)).await;
16047                    }
16048                })
16049                .await
16050                .unwrap();
16051                pause.park();
16052                std::fs::write(&release, "go").unwrap();
16053            });
16054            result.unwrap();
16055            let candidate = &runner.state.candidates[0];
16056            assert!(candidate.commits > 0, "{candidate:?}");
16057            assert!(candidate.summary.contains("saved-result"));
16058            assert_eq!(candidate.files, 1);
16059            let before = candidate.commits;
16060            runner.implement().await.unwrap();
16061            assert_eq!(runner.state.candidates[0].commits, before);
16062        }
16063    }
16064
16065    #[tokio::test]
16066    #[cfg(unix)]
16067    async fn resource_blocked_recovery_retries_the_unstarted_fixer() {
16068        let tmp = tempfile::tempdir().unwrap();
16069        let mut runner = registered_runner(tmp.path()).await;
16070        let winner = runner.state.candidates[0].clone();
16071        let cache = tmp.path().join("cache");
16072        runner.state.config.verify.e2e = vec![format!("CARGO_TARGET_DIR={} true", cache.display())];
16073        runner.state.config.graph.timeout_resource_wait = 0;
16074        let owner = crate::cache::Owner::here("other", "e2e", "e2e", &cache, "abc");
16075        let crate::cache::AcquireOutcome::Acquired(held) =
16076            crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap()
16077        else {
16078            panic!("cache must be free")
16079        };
16080        runner.state.recovery = Some(crate::recovery::RecoveryRecord {
16081            from_run: "earlier".into(),
16082            generation: 1,
16083            mode: crate::recovery::Mode::VerifyRepair,
16084            reasons: Vec::new(),
16085            reviewed_head: None,
16086            rounds: Vec::new(),
16087            open_findings: Vec::new(),
16088            evidence: None,
16089            criteria_inherited: true,
16090            repair: crate::recovery::Repair::NotStarted,
16091        });
16092        runner.recovery_repair(&winner).await.unwrap();
16093        assert!(matches!(
16094            runner.state.recovery.as_ref().unwrap().repair,
16095            crate::recovery::Repair::WaitingForRestore { .. }
16096        ));
16097        drop(held);
16098        runner.state.resource_block = None;
16099        runner.state.config.graph.timeout_resource_wait = 1;
16100        runner.recovery_repair(&winner).await.unwrap();
16101        assert!(matches!(
16102            runner.state.recovery.as_ref().unwrap().repair,
16103            crate::recovery::Repair::Done { .. }
16104        ));
16105        assert!(runner.state.seats.values().any(|seat| seat.turns > 0));
16106    }
16107
16108    #[tokio::test]
16109    #[cfg(unix)]
16110    async fn repository_blocked_graft_and_recovery_retry_after_deferred_restore() {
16111        use std::os::fd::AsRawFd as _;
16112        for graft in [false, true] {
16113            let tmp = tempfile::tempdir().unwrap();
16114            let mut runner = registered_runner(tmp.path()).await;
16115            runner.state.config.graph.timeout_resource_wait = 1;
16116            let winner = runner.state.candidates[0].clone();
16117            let marker = tmp.path().join("fixer-started");
16118            let mut fixer = spec("fixer");
16119            fixer.command = vec![
16120                "sh".into(),
16121                "-c".into(),
16122                format!("echo started >> '{}'; echo done", marker.display()),
16123            ];
16124            runner.roles.fixer = Some(vec![fixer]);
16125            if graft {
16126                let mut loser = winner.clone();
16127                loser.label = 'B';
16128                loser.index = 1;
16129                runner.state.candidates.push(loser);
16130                runner.state.config.graph.graft_runner_up = true;
16131                runner.state.tally = Some(Tally {
16132                    first_choice: BTreeMap::new(),
16133                    borda: BTreeMap::new(),
16134                    winner: winner.label,
16135                    rankings: 1,
16136                    unanimous_initial: true,
16137                    deliberated: false,
16138                    changed_votes: 0,
16139                    unanimous_final: true,
16140                    tie_break: None,
16141                    judges: 1,
16142                    present: 1,
16143                    quorum: 1,
16144                    met_quorum: true,
16145                    uncontested: None,
16146                });
16147                runner.state.judgements.push(crate::run::Judgement {
16148                    judge: 1,
16149                    seat: "judge-1".into(),
16150                    agent: "judge".into(),
16151                    ranking: vec![winner.label, 'B'],
16152                    reasons: BTreeMap::new(),
16153                    confidence: None,
16154                    strengths: BTreeMap::from([("B".into(), vec!["handles empty input".into()])]),
16155                    order: vec![0, 1],
16156                    failed: None,
16157                    duration_ms: 0,
16158                });
16159            } else {
16160                runner.state.recovery = Some(crate::recovery::RecoveryRecord {
16161                    from_run: "earlier".into(),
16162                    generation: 1,
16163                    mode: crate::recovery::Mode::VerifyRepair,
16164                    reasons: Vec::new(),
16165                    reviewed_head: None,
16166                    rounds: Vec::new(),
16167                    open_findings: Vec::new(),
16168                    evidence: None,
16169                    criteria_inherited: true,
16170                    repair: crate::recovery::Repair::NotStarted,
16171                });
16172            }
16173            let reader = crate::repo_lock::SeatLease::for_checkout(
16174                &winner.worktree,
16175                false,
16176                crate::config::test_coordination().as_ref(),
16177            )
16178            .await
16179            .unwrap();
16180            let pause = runner.pause.clone();
16181            let (result, ()) = tokio::join!(
16182                async {
16183                    if graft {
16184                        runner.graft().await
16185                    } else {
16186                        runner.recovery_repair(&winner).await
16187                    }
16188                },
16189                async {
16190                    tokio::time::sleep(Duration::from_millis(100)).await;
16191                    pause.park();
16192                }
16193            );
16194            result.unwrap();
16195            assert!(!marker.exists(), "a blocked seat must not spawn");
16196            // Exercise the persisted state, as a binary replacement/resume does.
16197            runner.state = RunState::load(&runner.state.id).unwrap();
16198            if graft {
16199                assert_eq!(
16200                    runner.state.graft.as_ref().unwrap().outcome,
16201                    GraftOutcome::WaitingForRestore
16202                );
16203            } else {
16204                assert!(matches!(
16205                    runner.state.recovery.as_ref().unwrap().repair,
16206                    crate::recovery::Repair::WaitingForRestore { .. }
16207                ));
16208            }
16209            drop(reader);
16210            runner.pause = Pause::new();
16211            runner.state.resource_block = None;
16212            // Deferred restoration must still respect an external lock owner.
16213            let external =
16214                std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16215            assert_eq!(
16216                unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16217                0
16218            );
16219            let leftover = winner.worktree.join("leftover");
16220            std::fs::write(&leftover, "earlier fallback edits").unwrap();
16221            let result = if graft {
16222                runner.graft().await
16223            } else {
16224                runner.recovery_repair(&winner).await
16225            };
16226            assert!(
16227                result
16228                    .unwrap_err()
16229                    .is::<crate::repo_lock::ResourceBlocked>()
16230            );
16231            assert!(leftover.exists());
16232            assert!(!marker.exists());
16233            drop(external);
16234            runner.state.resource_block = None;
16235            let result = if graft {
16236                runner.graft().await
16237            } else {
16238                runner.recovery_repair(&winner).await
16239            };
16240            result.unwrap();
16241            assert!(!leftover.exists(), "restore must precede retry");
16242            assert_eq!(std::fs::read_to_string(&marker).unwrap(), "started\n");
16243            if graft {
16244                assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
16245            } else {
16246                assert!(matches!(
16247                    runner.state.recovery.as_ref().unwrap().repair,
16248                    crate::recovery::Repair::Done { .. }
16249                ));
16250            }
16251        }
16252    }
16253
16254    #[tokio::test]
16255    #[cfg(unix)]
16256    async fn interrupted_graft_restore_waits_and_preserves_its_record() {
16257        use std::os::fd::AsRawFd as _;
16258        let tmp = tempfile::tempdir().unwrap();
16259        let mut runner = registered_runner(tmp.path()).await;
16260        runner.state.config.graph.timeout_resource_wait = 1;
16261        let winner = runner.state.candidates[0].clone();
16262        let pre = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16263        runner.state.tally = Some(Tally {
16264            first_choice: BTreeMap::new(),
16265            borda: BTreeMap::new(),
16266            winner: winner.label,
16267            rankings: 0,
16268            unanimous_initial: false,
16269            deliberated: false,
16270            changed_votes: 0,
16271            unanimous_final: false,
16272            tie_break: None,
16273            judges: 0,
16274            present: 0,
16275            quorum: 0,
16276            met_quorum: true,
16277            uncontested: Some("fixture".into()),
16278        });
16279        runner.state.graft = Some(GraftRecord {
16280            pre: pre.clone(),
16281            post: None,
16282            lines: None,
16283            limit: None,
16284            agent: None,
16285            outcome: GraftOutcome::Running,
16286            requested: Vec::new(),
16287            adoption: None,
16288            adoption_error: None,
16289        });
16290        std::fs::write(winner.worktree.join("README.md"), "unfinished graft\n").unwrap();
16291        git::commit_all(&winner.worktree, "unfinished graft")
16292            .await
16293            .unwrap();
16294        let unfinished = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16295        let leftover = winner.worktree.join("leftover");
16296        std::fs::write(&leftover, "untrusted edits").unwrap();
16297        let path = runner.state.repo.join(".git/updater.lock");
16298        let external = std::fs::File::create(&path).unwrap();
16299        assert_eq!(
16300            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16301            0
16302        );
16303        assert!(
16304            runner
16305                .graft()
16306                .await
16307                .unwrap_err()
16308                .is::<crate::repo_lock::ResourceBlocked>()
16309        );
16310        assert!(matches!(
16311            runner.state.graft.as_ref().unwrap().outcome,
16312            GraftOutcome::Running
16313        ));
16314        assert_eq!(
16315            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16316            unfinished
16317        );
16318        assert!(leftover.exists());
16319        drop(external);
16320        std::fs::remove_file(&path).unwrap();
16321        std::fs::create_dir(&path).unwrap();
16322        assert!(runner.graft().await.is_err());
16323        assert!(matches!(
16324            runner.state.graft.as_ref().unwrap().outcome,
16325            GraftOutcome::Running
16326        ));
16327        assert_eq!(
16328            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16329            unfinished
16330        );
16331        assert!(leftover.exists());
16332        std::fs::remove_dir(&path).unwrap();
16333        runner.graft().await.unwrap();
16334        assert!(runner.state.graft.as_ref().unwrap().outcome.settled());
16335        assert_eq!(git::rev_parse(&winner.worktree, "HEAD").await.unwrap(), pre);
16336        assert!(!leftover.exists());
16337    }
16338
16339    #[tokio::test]
16340    #[cfg(unix)]
16341    async fn repository_contention_blocks_and_parks_without_poisoning_preparation() {
16342        use std::os::fd::AsRawFd as _;
16343        let tmp = tempfile::tempdir().unwrap();
16344        let mut runner = registered_runner(tmp.path()).await;
16345        runner.state.prep_complete = Some(false);
16346        runner.state.config.graph.timeout_resource_wait = 1;
16347        runner.state.save().unwrap();
16348        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16349        assert_eq!(
16350            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16351            0
16352        );
16353        runner.execute().await.unwrap();
16354        let disk = RunState::load(&runner.state.id).unwrap();
16355        assert!(disk.driver_exited);
16356        assert_eq!(disk.driver_pid, None);
16357        assert_eq!(runner.state.status, RunStatus::Blocked);
16358        assert_eq!(
16359            runner.state.resource_block.as_ref().unwrap().kind,
16360            "repository coordination"
16361        );
16362        assert!(runner.state.prep_failure.is_none());
16363        assert!(runner.state.seats.is_empty());
16364        runner.pause.park();
16365        // Include headroom for Git subprocesses under parallel test load;
16366        // the repository contention deadline itself remains one second.
16367        tokio::time::timeout(Duration::from_secs(10), runner.execute())
16368            .await
16369            .unwrap()
16370            .unwrap();
16371        assert!(runner.state.parked);
16372        assert!(runner.state.prep_failure.is_none());
16373        let disk = RunState::load(&runner.state.id).unwrap();
16374        assert!(disk.driver_exited);
16375        assert_eq!(disk.driver_pid, None);
16376    }
16377
16378    #[tokio::test]
16379    #[cfg(unix)]
16380    async fn dropping_execute_during_a_repository_wait_releases_the_driver() {
16381        use std::os::fd::AsRawFd as _;
16382        let tmp = tempfile::tempdir().unwrap();
16383        let mut runner = registered_runner(tmp.path()).await;
16384        runner.state.prep_complete = Some(false);
16385        runner.state.config.graph.timeout_resource_wait = 30;
16386        runner.state.save().unwrap();
16387        let external = std::fs::File::create(runner.state.repo.join(".git/updater.lock")).unwrap();
16388        assert_eq!(
16389            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16390            0
16391        );
16392        assert!(
16393            tokio::time::timeout(Duration::from_millis(100), runner.execute())
16394                .await
16395                .is_err()
16396        );
16397        let disk = RunState::load(&runner.state.id).unwrap();
16398        assert!(disk.driver_exited);
16399        assert_eq!(disk.driver_pid, None);
16400        assert!(disk.status.resumable());
16401        assert!(runner.state.driver_exited);
16402        assert_eq!(runner.state.driver_pid, None);
16403        runner.state.save().unwrap();
16404        assert_eq!(RunState::load(&runner.state.id).unwrap().driver_pid, None);
16405    }
16406
16407    #[tokio::test]
16408    #[cfg(unix)]
16409    async fn gate_takes_cache_before_repository_so_an_editing_wave_can_finish() {
16410        let tmp = tempfile::tempdir().unwrap();
16411        let mut runner = registered_runner(tmp.path()).await;
16412        let winner = runner.state.candidates[0].clone();
16413        let cache = tmp.path().join("cache");
16414        let started = tmp.path().join("pre-gate-started");
16415        runner.state.config.verify.pre_gate = vec![format!("touch '{}'", started.display())];
16416        runner.state.config.verify.gate =
16417            vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
16418        let home = crate::run::home();
16419        let owner =
16420            crate::cache::Owner::here("editing-wave", "implement", "*", &winner.worktree, "HEAD");
16421        let guard = match crate::cache::try_acquire(&home, &cache, &owner).unwrap() {
16422            crate::cache::AcquireOutcome::Acquired(g) => g,
16423            crate::cache::AcquireOutcome::Busy(busy) => panic!("cache must be free: {busy:?}"),
16424        };
16425        let mut gate = Box::pin(runner.run_gate(&winner));
16426        assert!(
16427            tokio::time::timeout(Duration::from_millis(150), &mut gate)
16428                .await
16429                .is_err()
16430        );
16431        assert!(!started.exists(), "pre-gate must wait for the cache too");
16432        // Simulate the wave that already owns the cache entering invoke.
16433        // It must obtain the editor reservation and finish without waiting
16434        // for the gate that is queued behind its cache.
16435        let wait = crate::repo_lock::WaitPolicy::new(Duration::from_millis(200), || false);
16436        let editor = crate::repo_lock::SeatLease::checkout_with(
16437            &winner.worktree,
16438            true,
16439            crate::config::test_coordination().as_ref(),
16440            &wait,
16441        )
16442        .await
16443        .unwrap();
16444        drop(editor);
16445        guard.release();
16446        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
16447            .await
16448            .unwrap()
16449            .unwrap();
16450        drop(gate);
16451        assert!(outcomes.iter().all(CommandOutcome::ok));
16452        assert!(started.exists());
16453    }
16454
16455    #[tokio::test]
16456    #[cfg(unix)]
16457    async fn post_seat_rescue_and_gate_wait_for_shared_lock() {
16458        use std::os::fd::AsRawFd as _;
16459
16460        ask_test_home();
16461        let tmp = tempfile::tempdir().unwrap();
16462        let repo = tmp.path().join("repo");
16463        std::fs::create_dir_all(&repo).unwrap();
16464        init_repo(&repo);
16465        let common = repo.join(".git");
16466        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
16467        let mut runner = runner_at(RunStatus::Prep);
16468        runner.state.repo = repo.clone();
16469        runner.state.config.coordination = crate::config::test_coordination();
16470        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16471        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16472        runner.state.config.graph.advise = false;
16473        runner.roles.implementers = vec![spec("implement")];
16474        runner.roles.judges = vec![spec("judge")];
16475        runner.prep().await.unwrap();
16476        let winner = runner.state.candidates[0].clone();
16477        // Emulate edits already left by a completed seat. The fixture CLI
16478        // only reports completion; it performs no repository operations.
16479        std::fs::write(winner.worktree.join("leftover"), "seat work\n").unwrap();
16480        let completed = tmp.path().join("seat-completed");
16481        runner.roles.implementers[0].command = vec![
16482            "sh".into(),
16483            "-c".into(),
16484            format!("touch '{}'; echo completed", completed.display()),
16485        ];
16486        let outsider = std::fs::File::create(common.join("updater.lock")).unwrap();
16487        assert_eq!(
16488            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16489            0
16490        );
16491        let before = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16492        let mut implement = Box::pin(runner.implement());
16493        tokio::select! {
16494            result = &mut implement => panic!("rescue must wait: {result:?}"),
16495            result = tokio::time::timeout(Duration::from_secs(10), async {
16496                while !completed.exists() {
16497                    tokio::time::sleep(Duration::from_millis(20)).await;
16498                }
16499            }) => result.unwrap(),
16500        }
16501        assert!(
16502            tokio::time::timeout(Duration::from_millis(200), &mut implement)
16503                .await
16504                .is_err()
16505        );
16506        assert_eq!(
16507            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16508            before
16509        );
16510        assert_eq!(
16511            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
16512            0
16513        );
16514        tokio::time::timeout(Duration::from_secs(10), &mut implement)
16515            .await
16516            .unwrap()
16517            .unwrap();
16518        drop(implement);
16519        assert_ne!(
16520            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16521            before
16522        );
16523        assert!(git::is_clean(&winner.worktree).await.unwrap());
16524
16525        let started = tmp.path().join("pre-gate-started");
16526        let proceed = tmp.path().join("pre-gate-proceed");
16527        let checked = tmp.path().join("gate-ran");
16528        runner.state.config.verify.pre_gate = vec![format!(
16529            "echo mechanical >> README.md; touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
16530            started.display(),
16531            proceed.display()
16532        )];
16533        runner.state.config.verify.gate = vec![format!("touch '{}'", checked.display())];
16534        assert_eq!(
16535            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16536            0
16537        );
16538        let mut gate = Box::pin(runner.run_gate(&winner));
16539        assert!(
16540            tokio::time::timeout(Duration::from_millis(200), &mut gate)
16541                .await
16542                .is_err()
16543        );
16544        assert!(!started.exists());
16545        assert!(!checked.exists());
16546        assert!(git::is_clean(&winner.worktree).await.unwrap());
16547        assert_eq!(
16548            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_UN) },
16549            0
16550        );
16551        tokio::select! {
16552            result = &mut gate => panic!("pre-gate must wait for signal: {result:?}"),
16553            result = tokio::time::timeout(Duration::from_secs(10), async {
16554                while !started.exists() {
16555                    tokio::time::sleep(Duration::from_millis(20)).await;
16556                }
16557            }) => result.unwrap(),
16558        }
16559        assert_eq!(
16560            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16561            -1,
16562            "mechanical edits must hold the real lock"
16563        );
16564        std::fs::write(proceed, "ready").unwrap();
16565        let outcomes = tokio::time::timeout(Duration::from_secs(10), &mut gate)
16566            .await
16567            .unwrap()
16568            .unwrap();
16569        drop(gate);
16570        assert!(outcomes.iter().all(CommandOutcome::ok));
16571        assert!(checked.exists());
16572        assert!(runner.state.pre_gate_commit.is_some());
16573        assert!(git::is_clean(&winner.worktree).await.unwrap());
16574        assert_eq!(
16575            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16576            0,
16577            "gate completion must release coordination"
16578        );
16579        drop(outsider);
16580        std::fs::remove_file(common.join("updater.lock")).unwrap();
16581        std::fs::create_dir(common.join("updater.lock")).unwrap();
16582        std::fs::remove_file(&started).unwrap();
16583        std::fs::remove_file(&checked).unwrap();
16584        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
16585        let error = runner.run_gate(&winner).await.unwrap_err();
16586        assert!(
16587            error
16588                .to_string()
16589                .contains("acquire mandatory repository lock")
16590        );
16591        assert!(
16592            !started.exists(),
16593            "failed acquisition must prevent pre-gate"
16594        );
16595        assert!(!checked.exists(), "failed acquisition must prevent gate");
16596        assert!(git::is_clean(&winner.worktree).await.unwrap());
16597        assert_eq!(
16598            git::rev_parse(&winner.worktree, "HEAD").await.unwrap(),
16599            head
16600        );
16601    }
16602
16603    #[tokio::test]
16604    #[cfg(unix)]
16605    async fn preparation_waits_for_shared_lock_before_checkout_and_holds_it_through_setup() {
16606        use std::os::fd::AsRawFd as _;
16607        use std::time::Duration;
16608
16609        ask_test_home();
16610        let tmp = tempfile::tempdir().unwrap();
16611        let repo = tmp.path().join("repo");
16612        std::fs::create_dir_all(&repo).unwrap();
16613        init_repo(&repo);
16614        let common = repo.join(".git");
16615        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
16616        let lock = std::fs::File::create(common.join("updater.lock")).unwrap();
16617        assert_eq!(
16618            unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16619            0
16620        );
16621        let mut runner = runner_at(RunStatus::Prep);
16622        runner.state.repo = repo.clone();
16623        runner.state.config.coordination = crate::config::test_coordination();
16624        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16625        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16626        runner.state.config.graph.advise = true;
16627        runner.state.config.graph.advisors = 1;
16628        runner.roles.implementers = vec![spec("implement")];
16629        runner.roles.judges = vec![spec("judge")];
16630        let root = runner.state.worktree_root();
16631        let started = tmp.path().join("setup-started");
16632        let proceed = tmp.path().join("setup-proceed");
16633        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
16634            run: Some(format!(
16635                "touch '{}'; while ! test -f '{}'; do sleep 0.02; done",
16636                started.display(),
16637                proceed.display()
16638            )),
16639            ..Default::default()
16640        }];
16641        let branches = git::git(&repo, &["branch", "--list"]).await.unwrap();
16642        let config = git::git(&repo, &["config", "--local", "--list"])
16643            .await
16644            .unwrap();
16645        let mut prep = Box::pin(runner.prep());
16646        assert!(
16647            tokio::time::timeout(Duration::from_millis(200), &mut prep)
16648                .await
16649                .is_err()
16650        );
16651        assert!(
16652            !root.exists(),
16653            "contention must prevent even checkout creation"
16654        );
16655        assert!(!started.exists(), "contention must prevent setup");
16656        assert_eq!(
16657            git::git(&repo, &["branch", "--list"]).await.unwrap(),
16658            branches
16659        );
16660        assert_eq!(
16661            git::git(&repo, &["config", "--local", "--list"])
16662                .await
16663                .unwrap(),
16664            config
16665        );
16666        drop(lock);
16667        tokio::select! {
16668            result = &mut prep => panic!("setup must wait for its signal: {result:?}"),
16669            result = tokio::time::timeout(Duration::from_secs(10), async {
16670                while !started.exists() {
16671                    tokio::time::sleep(Duration::from_millis(20)).await;
16672                }
16673            }) => result.unwrap(),
16674        }
16675        let outsider = std::fs::File::open(common.join("updater.lock")).unwrap();
16676        assert_eq!(
16677            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16678            -1
16679        );
16680        assert!(
16681            tokio::time::timeout(
16682                Duration::from_millis(100),
16683                crate::repo_lock::SeatLease::for_checkout(
16684                    &repo,
16685                    true,
16686                    crate::config::test_coordination().as_ref()
16687                )
16688            )
16689            .await
16690            .is_err(),
16691            "preparation must also exclude local editors"
16692        );
16693        std::fs::write(proceed, "ready").unwrap();
16694        tokio::time::timeout(Duration::from_secs(10), &mut prep)
16695            .await
16696            .unwrap()
16697            .unwrap();
16698        drop(prep);
16699        assert_eq!(runner.state.prep_complete, Some(true));
16700        assert!(root.join("judge-1").exists());
16701        assert!(root.join("advisor-1").exists());
16702        assert_eq!(
16703            unsafe { libc::flock(outsider.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
16704            0
16705        );
16706    }
16707
16708    #[tokio::test]
16709    #[cfg(unix)]
16710    async fn preparation_lock_failure_prevents_repository_changes() {
16711        ask_test_home();
16712        let tmp = tempfile::tempdir().unwrap();
16713        let repo = tmp.path().join("repo");
16714        std::fs::create_dir_all(&repo).unwrap();
16715        init_repo(&repo);
16716        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
16717        // A directory at the required lock path makes opening the real lock
16718        // fail, rather than merely exercising an invalid registration.
16719        std::fs::create_dir(repo.join(".git/updater.lock")).unwrap();
16720        let mut runner = runner_at(RunStatus::Prep);
16721        runner.state.repo = repo.clone();
16722        runner.state.config.coordination = crate::config::test_coordination();
16723        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16724        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16725        runner.roles.implementers = vec![spec("implement")];
16726        let error = runner.prep().await.unwrap_err();
16727        assert!(
16728            error
16729                .to_string()
16730                .contains("acquire mandatory repository lock")
16731        );
16732        assert!(!runner.state.worktree_root().exists());
16733        assert!(runner.state.candidates.is_empty());
16734        assert!(!repo.join(".git/config.worktree").exists());
16735        assert_eq!(
16736            git::git(&repo, &["branch", "--list"]).await.unwrap().trim(),
16737            "* main"
16738        );
16739    }
16740
16741    #[tokio::test]
16742    async fn preparation_records_creation_intent_before_git_can_fail() {
16743        ask_test_home();
16744        let tmp = tempfile::tempdir().unwrap();
16745        let repo = tmp.path().join("repo");
16746        std::fs::create_dir_all(&repo).unwrap();
16747        init_repo(&repo);
16748        let mut runner = runner_at(RunStatus::Prep);
16749        runner.state.repo = repo.clone();
16750        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16751        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16752        runner.state.config.blind.commit_msg_hook = false;
16753        runner.roles.implementers = vec![spec("one")];
16754        let label = blind::assign_labels(1, runner.state.seed)[0];
16755        let branch = runner.state.branch_for(label);
16756        // A conflicting branch makes Git refuse creation before a candidate
16757        // can be registered. The durable intent must still identify it.
16758        git::git(&repo, &["branch", &branch]).await.unwrap();
16759        assert!(runner.prep().await.is_err());
16760        let saved = RunState::load(&runner.state.id).unwrap();
16761        assert!(saved.candidates.is_empty());
16762        let event = saved
16763            .events
16764            .iter()
16765            .find(|e| e.node == "prep-intent")
16766            .unwrap();
16767        let intent: serde_json::Value = serde_json::from_str(&event.message).unwrap();
16768        assert_eq!(intent["branch"], branch);
16769        assert_eq!(intent["start"], runner.state.base_commit);
16770        assert_eq!(
16771            intent["worktree"],
16772            runner
16773                .state
16774                .worktree_root()
16775                .join(format!("cand-{label}"))
16776                .to_string_lossy()
16777                .as_ref()
16778        );
16779        assert_eq!(intent["picks"], serde_json::json!([]));
16780    }
16781
16782    #[tokio::test]
16783    async fn invalid_pinned_sources_create_no_partial_worktrees() {
16784        ask_test_home();
16785        let tmp = tempfile::tempdir().unwrap();
16786        let repo = tmp.path().join("repo");
16787        std::fs::create_dir_all(&repo).unwrap();
16788        init_repo(&repo);
16789        let mut runner = runner_at(RunStatus::Prep);
16790        runner.state.repo = repo.clone();
16791        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16792        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
16793        runner.state.sources.pick_commits.push(refs::Input {
16794            token: "missing".into(),
16795            sha: "0".repeat(40),
16796            provenance: refs::Provenance::ExplicitCli,
16797        });
16798        assert!(runner.prep().await.is_err());
16799        assert!(runner.state.candidates.is_empty());
16800        assert!(!runner.state.worktree_root().exists());
16801    }
16802
16803    #[tokio::test]
16804    async fn prose_and_legacy_inference_never_import_into_candidates() {
16805        ask_test_home();
16806        let tmp = tempfile::tempdir().unwrap();
16807        let repo = tmp.path().join("repo");
16808        std::fs::create_dir_all(&repo).unwrap();
16809        init_repo(&repo);
16810        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
16811        git::git(&repo, &["checkout", "-b", "magi/history/A"])
16812            .await
16813            .unwrap();
16814        std::fs::write(repo.join("unwanted"), "do not import").unwrap();
16815        git::git(&repo, &["add", "."]).await.unwrap();
16816        git::git(&repo, &["commit", "-m", "historical implementation"])
16817            .await
16818            .unwrap();
16819        let source = git::rev_parse(&repo, "HEAD").await.unwrap();
16820        git::git(&repo, &["checkout", "main"]).await.unwrap();
16821        for instruction in [
16822            format!("Example: magi/history/A at {source}"),
16823            format!("Quoted failure: cannot apply referenced commit {source} from magi/history/A"),
16824            format!("Never import magi/history/A or {source}"),
16825            format!("Conversation answer: I mentioned {source} only as background"),
16826        ] {
16827            let mut runner = runner_at(RunStatus::Prep);
16828            runner.state.repo = repo.clone();
16829            runner.state.base_commit = base.clone();
16830            runner.state.instruction = instruction.clone();
16831            runner.state.config.graph.worktree_root = Some(tmp.path().join(&runner.state.id));
16832            runner.state.config.blind.commit_msg_hook = false;
16833            runner.state.seeds = vec![refs::Seed {
16834                token: "magi/history/A".into(),
16835                sha: source.clone(),
16836                kind: refs::SeedKind::Unmerged,
16837                branch: true,
16838                detail: String::new(),
16839            }];
16840            runner.roles.implementers = vec![spec("one")];
16841            assert_eq!(seeded_instruction(&runner.state), instruction);
16842            // Model an old record with inferred seeds but no structured input field.
16843            let mut legacy = serde_json::to_value(&runner.state).unwrap();
16844            legacy.as_object_mut().unwrap().remove("sources");
16845            runner.state = serde_json::from_value(legacy).unwrap();
16846            assert_eq!(runner.state.sources, refs::Sources::default());
16847            runner.state.save().unwrap();
16848            runner.state = RunState::load(&runner.state.id).unwrap();
16849            runner.prep().await.unwrap();
16850            for candidate in &runner.state.candidates {
16851                assert_eq!(
16852                    git::rev_parse(&candidate.worktree, "HEAD").await.unwrap(),
16853                    base
16854                );
16855                assert!(!candidate.worktree.join("unwanted").exists());
16856            }
16857        }
16858    }
16859
16860    #[tokio::test]
16861    async fn preparation_retries_after_explicit_release_and_rebuilds_partial_candidates() {
16862        ask_test_home();
16863        let tmp = tempfile::tempdir().unwrap();
16864        let repo = tmp.path().join("repo");
16865        std::fs::create_dir_all(&repo).unwrap();
16866        init_repo(&repo);
16867        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
16868        git::git(&repo, &["checkout", "-b", "seed"]).await.unwrap();
16869        std::fs::write(repo.join("referenced"), "required commit").unwrap();
16870        git::git(&repo, &["add", "."]).await.unwrap();
16871        git::git(&repo, &["commit", "-m", "required seed"])
16872            .await
16873            .unwrap();
16874        let seed = git::rev_parse(&repo, "HEAD").await.unwrap();
16875        git::git(&repo, &["checkout", "main"]).await.unwrap();
16876        let mut runner = runner_at(RunStatus::Prep);
16877        runner.state.repo = repo.clone();
16878        runner.state.base_commit = base.clone();
16879        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16880        runner.state.config.graph.advise = false;
16881        runner.state.config.blind.commit_msg_hook = false;
16882        runner.state.sources =
16883            refs::Sources::resolve(&repo, "origin", None, std::slice::from_ref(&seed))
16884                .await
16885                .unwrap();
16886        runner.roles.implementers = vec![spec("one"), spec("two")];
16887        runner.roles.judges = vec![spec("judge")];
16888        let label = blind::assign_labels(2, runner.state.seed)[0];
16889        let branch = runner.state.branch_for(label);
16890        let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
16891        git::worktree_add_branch(&repo, &worktree, &branch, &base)
16892            .await
16893            .unwrap();
16894        runner.state.candidates.push(Candidate {
16895            index: 0,
16896            label,
16897            agent: "one".into(),
16898            branch,
16899            worktree,
16900            summary: String::new(),
16901            stat: String::new(),
16902            files: 0,
16903            commits: 0,
16904            empty: false,
16905            failed: None,
16906            verified_noop: None,
16907            duration_ms: 0,
16908            folded: false,
16909        });
16910        runner.state.save().unwrap();
16911        // Reload the checkpoint immediately before its first cherry-pick.
16912        runner.state = RunState::load(&runner.state.id).unwrap();
16913        assert_eq!(runner.state.prep_complete, Some(false));
16914        runner.prep().await.unwrap();
16915        assert_eq!(runner.state.prep_complete, Some(true));
16916        assert_eq!(runner.state.candidates.len(), 2);
16917        for candidate in &runner.state.candidates {
16918            assert_eq!(
16919                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
16920                git::tree_of(&repo, &seed).await.unwrap()
16921            );
16922            assert_eq!(
16923                std::fs::read_to_string(candidate.worktree.join("referenced")).unwrap(),
16924                "required commit"
16925            );
16926        }
16927        assert!(runner.state.worktree_root().join("judge-1").exists());
16928        let heads: Vec<String> = candidate_heads(&runner.state.candidates).await;
16929        runner.prep().await.unwrap();
16930        assert_eq!(candidate_heads(&runner.state.candidates).await, heads);
16931
16932        runner.state.prep_complete = Some(false);
16933        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
16934            run: Some(format!(
16935                "test -f '{}'",
16936                tmp.path().join("dependency-ready").display()
16937            )),
16938            ..Default::default()
16939        }];
16940        assert!(runner.prep().await.is_err());
16941        assert!(runner.state.prep_failure.is_some());
16942        std::fs::write(tmp.path().join("dependency-ready"), "available").unwrap();
16943        runner.state = RunState::load(&runner.state.id).unwrap();
16944        assert!(
16945            runner.prep().await.is_err(),
16946            "correcting the cause alone must not auto-retry"
16947        );
16948        let failed_at = runner.state.events.last().unwrap().at;
16949        assert!(
16950            runner.retry_preparation(failed_at).is_err(),
16951            "old approvals cannot unlock the hold"
16952        );
16953        let mut task = crate::queue::Task::new(
16954            "retry".into(),
16955            "retry setup".into(),
16956            repo.clone(),
16957            crate::queue::Source::Human,
16958        );
16959        task.start(runner.state.id.clone());
16960        task.hold_machine(Some("setup failed".into()));
16961        task.release_operator("cli", None);
16962        runner
16963            .retry_preparation(task.resumption.as_ref().unwrap().at)
16964            .unwrap();
16965        runner.prep().await.unwrap();
16966        assert!(runner.state.prep_failure.is_none());
16967        assert_eq!(runner.state.prep_complete, Some(true));
16968        assert_eq!(runner.state.candidates.len(), 2);
16969        assert!(runner.state.worktree_root().join("judge-1").exists());
16970        for candidate in &runner.state.candidates {
16971            assert_eq!(
16972                git::tree_of(&candidate.worktree, "HEAD").await.unwrap(),
16973                git::tree_of(&repo, &seed).await.unwrap()
16974            );
16975        }
16976    }
16977
16978    async fn candidate_heads(candidates: &[Candidate]) -> Vec<String> {
16979        let mut heads = Vec::new();
16980        for candidate in candidates {
16981            heads.push(git::rev_parse(&candidate.worktree, "HEAD").await.unwrap());
16982        }
16983        heads
16984    }
16985
16986    async fn preservation_resume_fixture() -> (tempfile::TempDir, Runner) {
16987        ask_test_home();
16988        let tmp = tempfile::tempdir().unwrap();
16989        let repo = tmp.path().join("repo");
16990        std::fs::create_dir(&repo).unwrap();
16991        init_repo(&repo);
16992        let mut runner = runner_at(RunStatus::Reviewing);
16993        runner.state.repo = repo.clone();
16994        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
16995        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
16996        for (index, label) in ['A', 'B'].into_iter().enumerate() {
16997            let branch = format!("candidate-{label}");
16998            let worktree = runner.state.worktree_root().join(format!("cand-{label}"));
16999            git::worktree_add_branch(&repo, &worktree, &branch, "main")
17000                .await
17001                .unwrap();
17002            if label == 'B' {
17003                std::fs::write(worktree.join("change"), "winner").unwrap();
17004                git::rescue_commit(&worktree, "candidate change")
17005                    .await
17006                    .unwrap();
17007            }
17008            runner.state.candidates.push(Candidate {
17009                index,
17010                label,
17011                agent: "alpha".into(),
17012                branch,
17013                worktree,
17014                summary: "completed reply".into(),
17015                stat: String::new(),
17016                files: usize::from(label == 'B'),
17017                commits: usize::from(label == 'B'),
17018                empty: label == 'A',
17019                failed: None,
17020                verified_noop: None,
17021                duration_ms: 1,
17022                folded: false,
17023            });
17024        }
17025        runner.state.judge_skipped = true;
17026        runner.state.tally = Some(Tally {
17027            first_choice: BTreeMap::new(),
17028            borda: BTreeMap::new(),
17029            winner: 'B',
17030            rankings: 0,
17031            unanimous_initial: false,
17032            deliberated: false,
17033            changed_votes: 0,
17034            unanimous_final: false,
17035            tie_break: None,
17036            judges: 0,
17037            present: 0,
17038            quorum: 0,
17039            met_quorum: true,
17040            uncontested: Some("only B produced a change".into()),
17041        });
17042        runner.state.save().unwrap();
17043        (tmp, runner)
17044    }
17045
17046    #[tokio::test]
17047    async fn fold_losers_reclaims_isolated_outputs_without_a_pool_limit() {
17048        let (_tmp, mut runner) = preservation_resume_fixture().await;
17049        runner.state.config.verify.build_cache = crate::config::BuildCache::Isolated;
17050        runner.state.config.disk.cache_limit_bytes = 0;
17051        runner.state.config.graph.advise = true;
17052        runner.state.config.graph.advisors = 1;
17053        let advisor = runner.state.worktree_root().join("advisor-1");
17054        git::worktree_add_detached(&runner.state.repo, &advisor, "main")
17055            .await
17056            .unwrap();
17057        let home = crate::run::home();
17058        let loser =
17059            crate::build_target::resolve(&home, &runner.state.candidates[0].worktree).unwrap();
17060        let winner =
17061            crate::build_target::resolve(&home, &runner.state.candidates[1].worktree).unwrap();
17062        let advisor = crate::build_target::resolve(&home, &advisor).unwrap();
17063        for target in [&loser, &winner, &advisor] {
17064            std::fs::write(target.join("build-output"), "compiled").unwrap();
17065        }
17066
17067        runner.fold_losers().await.unwrap();
17068
17069        assert!(!loser.join("build-output").exists());
17070        assert!(!advisor.join("build-output").exists());
17071        assert!(winner.join("build-output").is_file());
17072    }
17073
17074    #[tokio::test]
17075    async fn fold_losers_persists_discard_before_later_teardown_failure() {
17076        let (_tmp, mut runner) = preservation_resume_fixture().await;
17077        runner.state.candidates[0].folded = true;
17078        runner.state.config.graph.advise = true;
17079        runner.state.config.graph.advisors = 2;
17080        let repo = runner.state.repo.clone();
17081        let root = runner.state.worktree_root();
17082        let discarded = root.join("advisor-1");
17083        git::worktree_add_detached(&repo, &discarded, "main")
17084            .await
17085            .unwrap();
17086        std::fs::write(discarded.join("design_proposal.json"), "{}").unwrap();
17087        let protected = root.join("advisor-2");
17088        git::worktree_add_branch(&repo, &protected, "attached-advisor", "main")
17089            .await
17090            .unwrap();
17091        std::fs::write(protected.join("keep"), "uncommitted").unwrap();
17092        runner.state.save().unwrap();
17093
17094        assert!(runner.fold_losers().await.is_err());
17095        assert!(!discarded.exists());
17096        assert!(protected.join("keep").exists());
17097        let saved = RunState::load(&runner.state.id).unwrap();
17098        assert!(saved.events.iter().any(|event| {
17099            event.message.contains("advisor-1") && event.message.contains("design_proposal.json")
17100        }));
17101    }
17102
17103    #[tokio::test]
17104    async fn read_seat_teardown_discards_only_owned_detached_seats() {
17105        let (tmp, mut runner) = preservation_resume_fixture().await;
17106        let repo = runner.state.repo.clone();
17107        let root = runner.state.worktree_root();
17108        for name in ["advisor-3", "judge-1", "review-2"] {
17109            let path = root.join(name);
17110            git::worktree_add_detached(&repo, &path, "main")
17111                .await
17112                .unwrap();
17113            std::fs::write(path.join("README.md"), "uncommitted edit").unwrap();
17114            std::fs::write(path.join("design_proposal.json"), "{}").unwrap();
17115            remove_read_seat_worktree(&mut runner.state, &path)
17116                .await
17117                .unwrap();
17118            assert!(!path.exists());
17119        }
17120        let outside = tmp.path().join("advisor-1");
17121        let unknown = root.join("unknown");
17122        let attached = root.join("advisor-4");
17123        git::worktree_add_detached(&repo, &outside, "main")
17124            .await
17125            .unwrap();
17126        git::worktree_add_detached(&repo, &unknown, "main")
17127            .await
17128            .unwrap();
17129        git::worktree_add_branch(&repo, &attached, "attached-advisor", "main")
17130            .await
17131            .unwrap();
17132        let foreign = tmp.path().join("foreign");
17133        std::fs::create_dir(&foreign).unwrap();
17134        init_repo(&foreign);
17135        let wrong_repo = root.join("judge-2");
17136        git::worktree_add_detached(&foreign, &wrong_repo, "main")
17137            .await
17138            .unwrap();
17139        let candidate = runner.state.candidates[0].worktree.clone();
17140        for path in [outside, unknown, attached, wrong_repo, candidate] {
17141            std::fs::write(path.join("uncommitted"), "keep").unwrap();
17142            assert!(
17143                remove_read_seat_worktree(&mut runner.state, &path)
17144                    .await
17145                    .is_err()
17146            );
17147            assert_eq!(
17148                std::fs::read_to_string(path.join("uncommitted")).unwrap(),
17149                "keep"
17150            );
17151        }
17152    }
17153
17154    #[tokio::test]
17155    #[cfg(unix)]
17156    async fn disk_interrupted_empty_implementation_retries_after_reload_and_failed_checkpoint() {
17157        for (solo, failed_checkpoint) in
17158            [(true, false), (false, false), (true, true), (false, true)]
17159        {
17160            let (_tmp, mut runner) = preservation_resume_fixture().await;
17161            if solo {
17162                runner.state.candidates.retain(|c| c.label == 'A');
17163            }
17164            runner.state.candidates[0].empty = false;
17165            runner.state.candidates[0].summary.clear();
17166            runner.state.tally = None;
17167            runner.state.judge_skipped = false;
17168            runner.state.status = RunStatus::Implementing;
17169            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
17170            let mut implementer = spec("alpha");
17171            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
17172            runner.roles.implementers = vec![implementer];
17173            let patch = runner.state.dir().join("artifacts/cand-A.patch");
17174            if failed_checkpoint {
17175                std::fs::create_dir_all(&patch).unwrap();
17176            }
17177            runner.state.save().unwrap();
17178            assert_eq!(runner.implement().await.is_err(), failed_checkpoint);
17179            drop(pressure);
17180            runner.state = RunState::load(&runner.state.id).unwrap();
17181            assert_eq!(runner.state.status, RunStatus::Blocked);
17182            assert!(runner.state.interrupted_implementations.contains(&'A'));
17183            assert_eq!(runner.state.candidates[0].commits, 0);
17184            assert!(!runner.state.candidates[0].empty);
17185            assert!(runner.state.candidates[0].failed.is_none());
17186            if failed_checkpoint {
17187                assert!(runner.state.candidate_preservation.contains_key(&'A'));
17188                std::fs::remove_dir(patch).unwrap();
17189            }
17190            runner.state.resource_block = None;
17191            runner.state.config.disk.min_free_bytes = 0;
17192            runner.roles.implementers[0].command = vec![
17193                "sh".into(),
17194                "-c".into(),
17195                "printf 'retried empty interrupted seat\\n' > retry-source; echo completed".into(),
17196            ];
17197            runner.implement().await.unwrap();
17198            assert!(runner.state.interrupted_implementations.is_empty());
17199            assert!(runner.state.candidate_preservation.is_empty());
17200            assert_eq!(runner.state.candidates[0].commits, 1);
17201            assert!(!runner.state.candidates[0].empty);
17202            assert!(
17203                std::fs::read_to_string(runner.state.candidates[0].worktree.join("retry-source"))
17204                    .unwrap()
17205                    .contains("retried empty interrupted seat")
17206            );
17207            if !solo {
17208                assert_eq!(runner.state.candidates[1].commits, 1);
17209            }
17210        }
17211    }
17212
17213    #[tokio::test]
17214    #[cfg(unix)]
17215    async fn disk_interrupted_implementation_preserves_edits_and_commits_before_resource_hold() {
17216        for (committed, block_rescue) in [(false, false), (false, true), (true, false)] {
17217            let (_tmp, mut runner) = preservation_resume_fixture().await;
17218            runner.state.candidates.retain(|c| c.label == 'A');
17219            runner.state.candidates[0].empty = false;
17220            runner.state.candidates[0].summary.clear();
17221            runner.state.tally = None;
17222            runner.state.judge_skipped = false;
17223            runner.state.status = RunStatus::Implementing;
17224            // Force only the real post-spawn watchdog, without failing the
17225            // separate admission check. Existing edits predate its measurement.
17226            let pressure = agent::test_watchdog::set(&runner.state.id, u64::MAX);
17227            let wt = runner.state.candidates[0].worktree.clone();
17228            std::fs::write(
17229                wt.join("interrupted-source"),
17230                "retain implementation work\n",
17231            )
17232            .unwrap();
17233            if committed {
17234                git::rescue_commit(&wt, "implementation checkpoint")
17235                    .await
17236                    .unwrap();
17237            }
17238            let lock = git::git(
17239                &wt,
17240                &[
17241                    "rev-parse",
17242                    "--path-format=absolute",
17243                    "--git-path",
17244                    "index.lock",
17245                ],
17246            )
17247            .await
17248            .unwrap();
17249            if block_rescue {
17250                std::fs::write(&lock, "fixture-owned lock").unwrap();
17251            }
17252            let mut implementer = spec("alpha");
17253            implementer.command = vec!["sh".into(), "-c".into(), "exec sleep 30".into()];
17254            runner.roles.implementers = vec![implementer];
17255            runner.state.save().unwrap();
17256            let result = runner.implement().await;
17257            drop(pressure);
17258            assert_eq!(result.is_err(), block_rescue);
17259            assert_eq!(
17260                runner.state.resource_block.as_ref().unwrap().kind,
17261                "disk pressure"
17262            );
17263            assert!(
17264                runner
17265                    .state
17266                    .events
17267                    .iter()
17268                    .any(|e| e.message.contains("agent execution interrupted"))
17269            );
17270            assert!(
17271                runner
17272                    .state
17273                    .dir()
17274                    .join("artifacts/candidate-A-recovery/staged.patch")
17275                    .exists()
17276            );
17277            if block_rescue {
17278                let saved = RunState::load(&runner.state.id).unwrap();
17279                assert!(saved.candidate_preservation.contains_key(&'A'));
17280                assert!(!saved.candidates[0].empty);
17281                assert_eq!(
17282                    std::fs::read_to_string(wt.join("interrupted-source")).unwrap(),
17283                    "retain implementation work\n"
17284                );
17285                std::fs::remove_file(lock).unwrap();
17286                runner.state = saved;
17287            } else {
17288                assert_eq!(runner.state.status, RunStatus::Blocked);
17289                assert_eq!(runner.state.candidates[0].commits, 1);
17290            }
17291            // Recovery must save the candidate before deciding whether another
17292            // implementation is needed. No implementer is available on retry.
17293            runner.roles.implementers.clear();
17294            runner.state.config.disk.min_free_bytes = 0;
17295            runner.state.resource_block = None;
17296            runner.implement().await.unwrap();
17297            assert!(runner.state.candidate_preservation.is_empty());
17298            assert_eq!(runner.state.candidates[0].commits, 1);
17299            assert!(!runner.state.candidates[0].empty);
17300            assert!(git::is_clean(&wt).await.unwrap());
17301            assert!(
17302                crate::run::read_artifact(&runner.state, "cand-A.patch")
17303                    .unwrap()
17304                    .contains("retain implementation work")
17305            );
17306        }
17307    }
17308
17309    #[tokio::test]
17310    async fn candidate_preservation_does_not_reflag_confirmed_or_folded_empty_candidates() {
17311        let (_tmp, mut runner) = preservation_resume_fixture().await;
17312        // Schema 15 already confirmed the unfolded no-change result.
17313        runner.implement().await.unwrap();
17314        assert!(runner.state.candidate_preservation.is_empty());
17315        assert!(
17316            !runner
17317                .state
17318                .dir()
17319                .join("artifacts/candidate-A-recovery")
17320                .exists()
17321        );
17322        runner.fold_losers().await.unwrap();
17323        assert!(!runner.state.candidates[0].worktree.exists());
17324        for schema in [14, crate::run::SCHEMA] {
17325            runner.state.schema = schema;
17326            runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17327            runner.state.save().unwrap();
17328            runner.state = RunState::load(&runner.state.id).unwrap();
17329            runner.implement().await.unwrap();
17330            assert!(runner.state.candidate_preservation.is_empty());
17331            assert!(runner.state.candidates[0].folded);
17332            assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
17333        }
17334    }
17335
17336    #[tokio::test]
17337    async fn infrastructure_failure_report_retains_eligible_candidate_edits() {
17338        let (_tmp, mut runner) = preservation_resume_fixture().await;
17339        runner.state.candidates.retain(|c| c.label == 'A');
17340        runner.state.tally = None;
17341        runner.state.judge_skipped = false;
17342        let candidate = &mut runner.state.candidates[0];
17343        candidate.summary = "Reproduction bind denied with EPERM; source repair complete, deployed browser validation remains parent-owned.".into();
17344        candidate.failed = Some("deployment validation unavailable".into());
17345        std::fs::write(
17346            candidate.worktree.join("repair"),
17347            "future launcher policy\n",
17348        )
17349        .unwrap();
17350        runner
17351            .state
17352            .candidate_preservation
17353            .insert('A', "awaiting persistence".into());
17354        runner.persist_candidates().await.unwrap();
17355        let candidate = &runner.state.candidates[0];
17356        assert!(!candidate.empty);
17357        assert_eq!(candidate.commits, 1);
17358        assert_eq!(candidate.files, 1);
17359        assert!(candidate.failed.is_none());
17360        assert!(candidate.summary.contains("EPERM"));
17361        assert!(
17362            crate::run::read_artifact(&runner.state, "cand-A.patch")
17363                .unwrap()
17364                .contains("future launcher policy")
17365        );
17366        assert!(runner.state.candidate_preservation.is_empty());
17367    }
17368
17369    #[tokio::test]
17370    async fn candidate_preservation_legacy_recovery_blocks_stale_verdict_on_every_resume() {
17371        let (_tmp, mut runner) = preservation_resume_fixture().await;
17372        let wt = runner.state.candidates[0].worktree.clone();
17373        std::fs::write(wt.join("recovered"), "owned edits").unwrap();
17374        runner.state.schema = 14;
17375        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17376        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17377        let tally = serde_json::to_value(&runner.state.tally).unwrap();
17378        for _ in 0..2 {
17379            assert!(runner.implement().await.is_err());
17380            assert_eq!(runner.state.status, RunStatus::Blocked);
17381            assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
17382            assert!(
17383                runner.state.candidates[0].empty,
17384                "old verdict must remain unusable"
17385            );
17386            assert_eq!(serde_json::to_value(&runner.state.tally).unwrap(), tally);
17387            assert!(runner.state.judge_skipped);
17388            assert!(runner.state.judgements.is_empty() && runner.state.votes.is_empty());
17389            assert!(
17390                crate::run::read_artifact(&runner.state, "cand-A.patch")
17391                    .unwrap()
17392                    .contains("owned edits")
17393            );
17394            assert!(wt.exists());
17395            assert_eq!(
17396                git::commits_ahead(&wt, &runner.state.base_commit, "HEAD")
17397                    .await
17398                    .unwrap(),
17399                1
17400            );
17401            runner.state = RunState::load(&runner.state.id).unwrap();
17402        }
17403    }
17404
17405    #[tokio::test]
17406    async fn candidate_preservation_legacy_failed_seat_keeps_edits_before_judging() {
17407        let (_tmp, mut runner) = preservation_resume_fixture().await;
17408        let wt = runner.state.candidates[0].worktree.clone();
17409        runner.state.candidates[0].failed = Some("CLI failed before commit".into());
17410        std::fs::write(wt.join("recovered"), "failed seat edits").unwrap();
17411        let index_lock = PathBuf::from(
17412            git::git(
17413                &wt,
17414                &[
17415                    "rev-parse",
17416                    "--path-format=absolute",
17417                    "--git-path",
17418                    "index.lock",
17419                ],
17420            )
17421            .await
17422            .unwrap(),
17423        );
17424        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
17425        runner.state.schema = 14;
17426        runner.state = crate::run::migrate_schema(runner.state.clone()).unwrap();
17427        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17428        assert!(runner.implement().await.is_err());
17429        assert!(runner.after_implement().is_err());
17430        assert!(runner.fold_losers().await.is_err());
17431        assert_eq!(
17432            std::fs::read_to_string(wt.join("recovered")).unwrap(),
17433            "failed seat edits"
17434        );
17435        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17436        runner.state = RunState::load(&runner.state.id).unwrap();
17437        std::fs::remove_file(index_lock).unwrap();
17438        // Recovery finds changes that the old uncontested result never judged.
17439        assert!(runner.implement().await.is_err());
17440        assert!(runner.state.candidate_preservation[&'A'].contains("supported recovery"));
17441        assert!(runner.state.candidates[0].empty);
17442        assert_eq!(runner.state.tally.as_ref().unwrap().winner, 'B');
17443        assert!(
17444            crate::run::read_artifact(&runner.state, "cand-A.patch")
17445                .unwrap()
17446                .contains("failed seat edits")
17447        );
17448        assert!(wt.exists());
17449    }
17450
17451    #[tokio::test]
17452    async fn candidate_preservation_loser_cleanup_resumes_after_branch_and_judge_failures() {
17453        let (_tmp, mut runner) = preservation_resume_fixture().await;
17454        let repo = runner.state.repo.clone();
17455        let common = git::git(
17456            &repo,
17457            &["rev-parse", "--path-format=absolute", "--git-common-dir"],
17458        )
17459        .await
17460        .unwrap();
17461        let branch_lock = PathBuf::from(common).join("refs/heads/candidate-A.lock");
17462        std::fs::write(&branch_lock, "fixture-owned lock").unwrap();
17463        assert!(runner.fold_losers().await.is_err());
17464        assert!(!runner.state.candidates[0].worktree.exists());
17465        assert!(!runner.state.candidates[0].folded);
17466        assert!(git::branch_exists(&repo, "candidate-A").await.unwrap());
17467        runner.state = RunState::load(&runner.state.id).unwrap();
17468        std::fs::remove_file(branch_lock).unwrap();
17469        let judge = runner.state.worktree_root().join("judge-1");
17470        git::worktree_add_detached(&repo, &judge, "main")
17471            .await
17472            .unwrap();
17473        std::fs::write(judge.join("uncommitted"), "retain").unwrap();
17474        git::git(&repo, &["worktree", "lock", &git::path_arg(&judge)])
17475            .await
17476            .unwrap();
17477        runner.roles.judges = vec![spec("judge")];
17478        assert!(runner.fold_losers().await.is_err());
17479        runner.state = RunState::load(&runner.state.id).unwrap();
17480        assert!(
17481            runner.state.candidates[0].folded,
17482            "candidate progress saved before judge failure"
17483        );
17484        assert!(!git::branch_exists(&repo, "candidate-A").await.unwrap());
17485        assert!(judge.join("uncommitted").exists());
17486        git::git(&repo, &["worktree", "unlock", &git::path_arg(&judge)])
17487            .await
17488            .unwrap();
17489        runner.fold_losers().await.unwrap();
17490        assert!(!judge.exists());
17491        runner.fold_losers().await.unwrap();
17492    }
17493
17494    #[tokio::test]
17495    async fn candidate_preservation_selected_implementer_resumes_through_execute_graph() {
17496        let (_tmp, mut runner) = preservation_resume_fixture().await;
17497        runner.state.candidates.retain(|c| c.label == 'B');
17498        runner.state.tally = None;
17499        runner.state.judge_skipped = false;
17500        runner.state.prep_complete = Some(true);
17501        runner.state.config.graph.advise = false;
17502        runner.state.config.graph.selected_implementer = Some("alpha".into());
17503        let wt = runner.state.candidates[0].worktree.clone();
17504        std::fs::write(wt.join("leftover"), "completed implementation").unwrap();
17505        runner
17506            .state
17507            .candidate_preservation
17508            .insert('B', "awaiting persistence".into());
17509        let index_lock = git::git(
17510            &wt,
17511            &[
17512                "rev-parse",
17513                "--path-format=absolute",
17514                "--git-path",
17515                "index.lock",
17516            ],
17517        )
17518        .await
17519        .unwrap();
17520        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
17521        runner.state.save().unwrap();
17522        assert!(runner.execute_graph().await.is_err());
17523        assert_eq!(runner.state.status, RunStatus::Blocked);
17524        assert!(runner.state.candidate_preservation.contains_key(&'B'));
17525        std::fs::remove_file(index_lock).unwrap();
17526        // Park at the next graph boundary: this tests the real selected-seat
17527        // hold guard without dispatching reviewers or publishing anything.
17528        for _ in 0..2 {
17529            runner.state = RunState::load(&runner.state.id).unwrap();
17530            runner.pause.park();
17531            runner.execute_graph().await.unwrap();
17532            assert_eq!(runner.state.status, RunStatus::Implementing);
17533            assert!(runner.state.candidate_preservation.is_empty());
17534            assert_eq!(runner.state.candidates[0].commits, 2);
17535            assert!(runner.state.tally.is_none());
17536        }
17537        runner.implement().await.unwrap();
17538        assert_eq!(runner.state.status, RunStatus::Judging);
17539        // A genuine selected-implementer hold must still require release.
17540        runner.state.status = RunStatus::Blocked;
17541        runner.state.candidates[0].failed = Some("implementation failed".into());
17542        runner.state.save().unwrap();
17543        let error = runner.execute_graph().await.unwrap_err();
17544        assert!(
17545            error
17546                .to_string()
17547                .contains("selected implementation is held")
17548        );
17549    }
17550
17551    #[tokio::test]
17552    async fn candidate_preservation_cleanup_unregisters_a_vanished_worktree() {
17553        let (_tmp, mut runner) = preservation_resume_fixture().await;
17554        let repo = runner.state.repo.clone();
17555        let candidate = runner.state.candidates[0].clone();
17556        // Remove only the disposable fixture directory, leaving Git's linked
17557        // worktree registration and branch intact, as in a vanished checkout.
17558        let registered = git::worktree_holding(&repo, &candidate.branch)
17559            .await
17560            .unwrap()
17561            .unwrap();
17562        assert_eq!(
17563            registered.canonicalize().unwrap(),
17564            candidate.worktree.canonicalize().unwrap()
17565        );
17566        std::fs::remove_dir_all(&candidate.worktree).unwrap();
17567        assert_eq!(
17568            git::worktree_holding(&repo, &candidate.branch)
17569                .await
17570                .unwrap(),
17571            Some(registered)
17572        );
17573        assert!(
17574            !git::branch_delete(&repo, &candidate.branch).await.unwrap(),
17575            "the stale registration initially keeps the branch checked out"
17576        );
17577        runner.fold_losers().await.unwrap();
17578        assert!(runner.state.candidates[0].folded);
17579        assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
17580        assert_eq!(
17581            git::worktree_holding(&repo, &candidate.branch)
17582                .await
17583                .unwrap(),
17584            None
17585        );
17586        runner.state = RunState::load(&runner.state.id).unwrap();
17587        runner.fold_losers().await.unwrap();
17588    }
17589
17590    #[tokio::test]
17591    async fn fold_run_unregisters_a_vanished_worktree_and_can_retry() {
17592        let (_tmp, mut runner) = preservation_resume_fixture().await;
17593        let repo = runner.state.repo.clone();
17594        let candidate = runner.state.candidates[0].clone();
17595        let winner = runner.state.candidates[1].clone();
17596        let registered = git::worktree_holding(&repo, &candidate.branch)
17597            .await
17598            .unwrap()
17599            .unwrap();
17600        assert_eq!(
17601            registered.canonicalize().unwrap(),
17602            candidate.worktree.canonicalize().unwrap()
17603        );
17604        std::fs::remove_dir_all(&candidate.worktree).unwrap();
17605        assert_eq!(
17606            git::worktree_holding(&repo, &candidate.branch)
17607                .await
17608                .unwrap(),
17609            Some(registered)
17610        );
17611        assert!(!git::branch_delete(&repo, &candidate.branch).await.unwrap());
17612
17613        for _ in 0..2 {
17614            fold_run(&mut runner.state, false, &crate::run::home())
17615                .await
17616                .unwrap();
17617            runner.state = RunState::load(&runner.state.id).unwrap();
17618            assert!(runner.state.candidates[0].folded);
17619            assert!(!git::branch_exists(&repo, &candidate.branch).await.unwrap());
17620            assert_eq!(
17621                git::worktree_holding(&repo, &candidate.branch)
17622                    .await
17623                    .unwrap(),
17624                None
17625            );
17626            assert!(!runner.state.candidates[1].folded);
17627            assert!(winner.worktree.exists());
17628            assert!(git::branch_exists(&repo, &winner.branch).await.unwrap());
17629        }
17630    }
17631    #[tokio::test]
17632    async fn fold_recovery_override_archives_sources_and_keeps_safety_checks() {
17633        for sidecar in [false, true] {
17634            let tmp = tempfile::tempdir().unwrap();
17635            let home = tmp.path().join("home");
17636            let repo = tmp.path().join("repo");
17637            std::fs::create_dir(&repo).unwrap();
17638            init_repo(&repo);
17639            let mut state = runner_at(RunStatus::Superseded).state;
17640            state.repo = repo.clone();
17641            state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17642            state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17643            state.driver_exited = true;
17644            state.reserve_under(&home).unwrap();
17645            git::git(
17646                &repo,
17647                &["update-ref", "refs/remotes/origin/main", &state.base_commit],
17648            )
17649            .await
17650            .unwrap();
17651            let wt = state.worktree_root().join("cand-A");
17652            git::worktree_add_branch(&repo, &wt, "candidate", "main")
17653                .await
17654                .unwrap();
17655            std::fs::write(wt.join("independent"), "retained implementation\n").unwrap();
17656            git::commit_all(&wt, "fixture: independent source")
17657                .await
17658                .unwrap();
17659            let head = git::rev_parse(&wt, "HEAD").await.unwrap();
17660            state.candidates.push(Candidate {
17661                index: 0,
17662                label: 'A',
17663                agent: "fixture".into(),
17664                branch: "candidate".into(),
17665                worktree: wt.clone(),
17666                summary: String::new(),
17667                stat: String::new(),
17668                files: 0,
17669                commits: 0,
17670                empty: false,
17671                failed: None,
17672                verified_noop: None,
17673                duration_ms: 0,
17674                folded: false,
17675            });
17676            let mut task = crate::queue::Task::new(
17677                "task".into(),
17678                "task".into(),
17679                repo.clone(),
17680                crate::queue::Source::Human,
17681            );
17682            task.runs.push(state.id.clone());
17683            crate::queue::Queue::at(home.join("queue"))
17684                .put(&mut task)
17685                .unwrap();
17686            if sidecar {
17687                crate::pr_recovery::retain_sources(&task, &home).unwrap();
17688            }
17689            state.save_under(&home).unwrap();
17690            let reason = crate::pr_recovery::source_retention_reason(&home, &state).unwrap();
17691            assert!(
17692                fold_run(&mut state, true, &home)
17693                    .await
17694                    .unwrap_err()
17695                    .to_string()
17696                    .contains(&reason)
17697            );
17698            let mut disk = state.config.disk.clone();
17699            disk.fold_grace_secs = 0;
17700            assert_eq!(
17701                crate::clean::fold_due(
17702                    &home.join("runs"),
17703                    &home,
17704                    &state.worktree_root(),
17705                    &disk,
17706                    Timestamp::now() + std::time::Duration::from_secs(10),
17707                )
17708                .await
17709                .unwrap(),
17710                (0, 0)
17711            );
17712            assert!(wt.exists());
17713            state.status = RunStatus::Blocked;
17714            state.save_under(&home).unwrap();
17715            assert!(
17716                fold_run_overriding_recovery_retention(&mut state, true, &home)
17717                    .await
17718                    .is_err()
17719            );
17720            state.status = RunStatus::Superseded;
17721            state.driver_exited = false;
17722            state.driver_claimed = None;
17723            state.save_under(&home).unwrap();
17724            assert!(
17725                fold_run_overriding_recovery_retention(&mut state, true, &home)
17726                    .await
17727                    .is_err()
17728            );
17729            state.driver_pid = Some(std::process::id());
17730            state.driver_started_at = crate::proc::process_started_at(std::process::id());
17731            state.save_under(&home).unwrap();
17732            assert!(
17733                fold_run_overriding_recovery_retention(&mut state, true, &home)
17734                    .await
17735                    .is_err()
17736            );
17737            state.driver_exited = true;
17738            state.driver_pid = None;
17739            state.driver_started_at = None;
17740            state.save_under(&home).unwrap();
17741            let lease = crate::driver::maintenance(&home, &state.id).unwrap();
17742            assert!(
17743                fold_run_overriding_recovery_retention(&mut state, true, &home)
17744                    .await
17745                    .is_err()
17746            );
17747            drop(lease);
17748            #[cfg(unix)]
17749            {
17750                let output = crate::retention::OutputLease::take(&wt, false).unwrap();
17751                assert!(
17752                    fold_run_overriding_recovery_retention(&mut state, true, &home)
17753                        .await
17754                        .is_err()
17755                );
17756                drop(output);
17757            }
17758            let owner = crate::pr_head::owner_lock(&home, &state.id).unwrap();
17759            assert!(
17760                fold_run_overriding_recovery_retention(&mut state, true, &home)
17761                    .await
17762                    .is_err()
17763            );
17764            drop(owner);
17765            let checkpoint = git::git(
17766                &wt,
17767                &[
17768                    "rev-parse",
17769                    "--path-format=absolute",
17770                    "--git-path",
17771                    "CHERRY_PICK_HEAD",
17772                ],
17773            )
17774            .await
17775            .unwrap();
17776            std::fs::write(&checkpoint, &head).unwrap();
17777            assert!(
17778                fold_run_overriding_recovery_retention(&mut state, true, &home)
17779                    .await
17780                    .is_err()
17781            );
17782            std::fs::remove_file(checkpoint).unwrap();
17783            std::fs::write(wt.join("dirty"), "keep").unwrap();
17784            assert!(
17785                fold_run_overriding_recovery_retention(&mut state, true, &home)
17786                    .await
17787                    .is_err()
17788            );
17789            assert!(wt.join("dirty").exists());
17790            std::fs::remove_file(wt.join("dirty")).unwrap();
17791            let evidence = home
17792                .join("runs")
17793                .join(&state.id)
17794                .join("artifacts/fold-evidence");
17795            std::fs::create_dir_all(evidence.parent().unwrap()).unwrap();
17796            std::fs::write(&evidence, "blocked archive").unwrap();
17797            assert!(
17798                fold_run_overriding_recovery_retention(&mut state, true, &home)
17799                    .await
17800                    .is_err()
17801            );
17802            assert!(wt.exists());
17803            assert!(
17804                !RunState::load_under(&state.id, &home)
17805                    .unwrap()
17806                    .events
17807                    .iter()
17808                    .any(|event| event.message.contains("--override-recovery-retention"))
17809            );
17810            std::fs::remove_file(&evidence).unwrap();
17811            fold_run_overriding_recovery_retention(&mut state, true, &home)
17812                .await
17813                .unwrap();
17814            assert!(!wt.exists());
17815            assert!(!git::branch_exists(&repo, "candidate").await.unwrap());
17816            assert!(
17817                git::worktree_holding(&repo, "candidate")
17818                    .await
17819                    .unwrap()
17820                    .is_none()
17821            );
17822            assert!(
17823                std::fs::read_to_string(evidence.join(format!("{head}.patch")))
17824                    .unwrap()
17825                    .contains("retained implementation")
17826            );
17827            assert!(evidence.join(format!("{head}.index")).is_file());
17828            let saved = RunState::load_under(&state.id, &home).unwrap();
17829            assert_eq!(saved.status, RunStatus::Superseded);
17830            assert!(saved.candidates[0].folded);
17831            assert!(saved.events.iter().any(|event| {
17832                event.message.contains("--override-recovery-retention")
17833                    && event.message.contains(&state.id)
17834                    && event.message.contains(&reason)
17835            }));
17836            assert_eq!(
17837                crate::pr_recovery::explicit_sources_retained(&home, &state.id),
17838                sidecar
17839            );
17840        }
17841    }
17842
17843    #[tokio::test]
17844    async fn candidate_preservation_retries_after_upgrade_without_rerunning_seats() {
17845        ask_test_home();
17846        let tmp = tempfile::tempdir().unwrap();
17847        let repo = tmp.path().join("repo");
17848        std::fs::create_dir(&repo).unwrap();
17849        init_repo(&repo);
17850        let mut runner = runner_at(RunStatus::Implementing);
17851        runner.state.repo = repo.clone();
17852        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
17853        runner.state.config.graph.worktree_root = Some(tmp.path().join("wt"));
17854        for (index, label) in ['A', 'B'].into_iter().enumerate() {
17855            let branch = format!("candidate-{label}");
17856            let wt = runner.state.worktree_root().join(format!("cand-{label}"));
17857            git::worktree_add_branch(&repo, &wt, &branch, "main")
17858                .await
17859                .unwrap();
17860            std::fs::write(wt.join("README.md"), "tracked edits\n").unwrap();
17861            git::git(&wt, &["add", "README.md"]).await.unwrap();
17862            std::fs::write(wt.join("README.md"), "later tracked edits\n").unwrap();
17863            std::fs::write(wt.join("new-file"), "untracked edits\n").unwrap();
17864            runner.state.candidates.push(Candidate {
17865                index,
17866                label,
17867                agent: "alpha".to_owned(),
17868                branch,
17869                worktree: wt,
17870                summary: "completed implementation".to_owned(),
17871                stat: String::new(),
17872                files: 0,
17873                commits: 0,
17874                empty: false,
17875                failed: None,
17876                verified_noop: None,
17877                duration_ms: 42,
17878                folded: false,
17879            });
17880            runner
17881                .state
17882                .candidate_preservation
17883                .insert(label, "awaiting persistence".to_owned());
17884        }
17885        let wt = runner.state.candidates[0].worktree.clone();
17886        let index_lock = git::git(
17887            &wt,
17888            &[
17889                "rev-parse",
17890                "--path-format=absolute",
17891                "--git-path",
17892                "index.lock",
17893            ],
17894        )
17895        .await
17896        .unwrap();
17897        std::fs::write(&index_lock, "fixture-owned lock").unwrap();
17898        runner.state.save().unwrap();
17899        assert!(runner.persist_candidates().await.is_err());
17900        assert!(runner.state.candidate_preservation.contains_key(&'A'));
17901        assert!(!runner.state.candidate_preservation.contains_key(&'B'));
17902        assert_eq!(
17903            runner.state.candidates[1].commits, 1,
17904            "other results are still collected"
17905        );
17906        assert!(
17907            !runner.state.candidates[0].empty,
17908            "failed rescue is not no change"
17909        );
17910        assert_eq!(
17911            runner.state.candidates[0].summary,
17912            "completed implementation"
17913        );
17914        assert!(runner.after_implement().is_err());
17915        let home = tmp.path().join("fold-home");
17916        assert!(fold_run(&mut runner.state, true, &home).await.is_err());
17917        assert!(wt.join("new-file").exists());
17918        let recovery = runner.state.dir().join("artifacts/candidate-A-recovery");
17919        assert!(recovery.join("staged.patch").exists());
17920        assert!(recovery.join("unstaged.patch").exists());
17921        assert_eq!(
17922            std::fs::read_to_string(recovery.join("untracked/new-file")).unwrap(),
17923            "untracked edits\n"
17924        );
17925        runner.state.begin_pass();
17926        runner.state.end_pass_parked(ParkCause::Upgrade {
17927            from: "1.0".into(),
17928            to: Some("1.1".into()),
17929        });
17930        runner.state.save().unwrap();
17931        runner.state = RunState::load(&runner.state.id).unwrap();
17932        assert!(matches!(
17933            runner.state.passes.last().unwrap().end,
17934            Some(crate::run::PassEnd::Parked {
17935                cause: ParkCause::Upgrade { .. }
17936            })
17937        ));
17938        std::fs::remove_file(index_lock).unwrap();
17939        // No implementer is configured: a persistence retry cannot dispatch a seat.
17940        runner.implement().await.unwrap();
17941        assert!(runner.state.candidate_preservation.is_empty());
17942        assert!(
17943            runner
17944                .state
17945                .candidates
17946                .iter()
17947                .all(|c| c.commits == 1 && !c.empty)
17948        );
17949        assert!(git::is_clean(&wt).await.unwrap());
17950        assert!(
17951            crate::run::read_artifact(&runner.state, "cand-A.patch")
17952                .unwrap()
17953                .contains("later tracked edits")
17954        );
17955    }
17956
17957    #[tokio::test]
17958    async fn candidate_preservation_git_read_and_cleanup_fail_closed() {
17959        ask_test_home();
17960        let tmp = tempfile::tempdir().unwrap();
17961        let repo = tmp.path().join("repo");
17962        std::fs::create_dir(&repo).unwrap();
17963        init_repo(&repo);
17964        let wt = tmp.path().join("candidate");
17965        git::worktree_add_branch(&repo, &wt, "candidate", "main")
17966            .await
17967            .unwrap();
17968        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
17969        assert!(remove_preserved_worktree(&repo, &wt).await.is_err());
17970        assert!(wt.join("uncommitted").exists());
17971        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
17972        std::fs::remove_file(wt.join("uncommitted")).unwrap();
17973        let mut runner = runner_at(RunStatus::Implementing);
17974        runner.state.repo = repo.clone();
17975        runner.state.base_commit = "missing-base".to_owned();
17976        runner.state.candidates.push(Candidate {
17977            index: 0,
17978            label: 'A',
17979            agent: "alpha".into(),
17980            branch: "candidate".into(),
17981            worktree: wt.clone(),
17982            summary: "completed".into(),
17983            stat: String::new(),
17984            files: 0,
17985            commits: 0,
17986            empty: false,
17987            failed: None,
17988            verified_noop: None,
17989            duration_ms: 1,
17990            folded: false,
17991        });
17992        std::fs::write(wt.join("uncommitted"), "keep").unwrap();
17993        assert!(
17994            fold_run(&mut runner.state, true, &tmp.path().join("home"))
17995                .await
17996                .is_err()
17997        );
17998        assert!(!runner.state.candidates[0].folded);
17999        assert!(git::branch_exists(&repo, "candidate").await.unwrap());
18000        std::fs::remove_file(wt.join("uncommitted")).unwrap();
18001        runner
18002            .state
18003            .candidate_preservation
18004            .insert('A', "pending".into());
18005        assert!(runner.persist_candidates().await.is_err());
18006        assert!(!runner.state.candidates[0].empty);
18007        assert!(!runner.state.candidates[0].folded);
18008        assert!(wt.exists());
18009        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
18010        let patch_path = runner.state.dir().join("artifacts/cand-A.patch");
18011        std::fs::create_dir_all(&patch_path).unwrap();
18012        assert!(
18013            runner.persist_candidates().await.is_err(),
18014            "artifact failure stays pending"
18015        );
18016        assert!(runner.state.candidate_preservation.contains_key(&'A'));
18017        assert!(!runner.state.candidates[0].empty);
18018        std::fs::remove_dir(patch_path).unwrap();
18019        runner.persist_candidates().await.unwrap();
18020        assert!(
18021            runner.state.candidates[0].empty,
18022            "only successful inspection confirms no change"
18023        );
18024    }
18025
18026    fn init_repo(dir: &Path) {
18027        let run = |args: &[&str]| {
18028            let out = std::process::Command::new("git")
18029                .args(args)
18030                .current_dir(dir)
18031                .quiet()
18032                .output()
18033                .expect("spawn git");
18034            assert!(
18035                out.status.success(),
18036                "git {args:?} failed: {}",
18037                String::from_utf8_lossy(&out.stderr)
18038            );
18039        };
18040        run(&["init", "-b", "main"]);
18041        run(&["config", "user.name", "magi test"]);
18042        run(&["config", "user.email", "magi@example.com"]);
18043        std::fs::write(dir.join("README.md"), "# fixture\n").unwrap();
18044        run(&["add", "-A"]);
18045        run(&["commit", "-m", "init"]);
18046    }
18047
18048    // `settle_questions` is what closes the ghost the phone showed: a run's
18049    // seat asked something, the run then ended, and nothing was left to
18050    // abandon the question it left `open`. `HOME` is a process-wide
18051    // `OnceLock` (see `run::set_home`'s doc), so this only wins the race the
18052    // first time it runs in the binary — every test below still reaches the
18053    // same directory whichever call won, and each gets its own run id from
18054    // `RunState::new`, so they never collide there.
18055    fn ask_test_home() {
18056        crate::run::pin_test_home();
18057    }
18058
18059    #[test]
18060    fn startup_terminal_save_failure_preserves_original_error_and_reservation() {
18061        ask_test_home();
18062        let mut runner = runner_at(RunStatus::Prep);
18063        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
18064        // A blocked temporary output path makes the terminal save fail while
18065        // preserving the already published reservation.
18066        std::fs::create_dir(runner.state.dir().join("run.json.tmp")).unwrap();
18067        let error = guard
18068            .finish(
18069                &mut runner.state,
18070                Err(
18071                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "original refusal")
18072                        .into(),
18073                ),
18074            )
18075            .unwrap_err();
18076        assert_eq!(
18077            error.downcast_ref::<std::io::Error>().unwrap().kind(),
18078            std::io::ErrorKind::PermissionDenied
18079        );
18080        assert!(error.downcast_ref::<crate::run::StartupFailure>().is_some());
18081        let message = format!("{error:#}");
18082        assert!(message.contains("original refusal"));
18083        assert!(!message.contains("could not save terminal"));
18084        assert_eq!(
18085            error.chain().count(),
18086            2,
18087            "only startup attribution wraps the original error"
18088        );
18089        let saved = RunState::load(&runner.state.id).unwrap();
18090        assert_eq!(saved.status, RunStatus::Blocked);
18091        assert!(!saved.startup.unwrap().complete);
18092    }
18093
18094    #[test]
18095    fn reserved_startup_interruption_is_blocked_and_not_resumable() {
18096        ask_test_home();
18097        let mut runner = runner_at(RunStatus::Prep);
18098        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
18099        let id = runner.state.id.clone();
18100        drop(guard);
18101        let saved = RunState::load(&id).unwrap();
18102        assert_eq!(saved.status, RunStatus::Blocked);
18103        assert!(!saved.startup.as_ref().unwrap().complete);
18104        assert!(
18105            saved
18106                .startup
18107                .unwrap()
18108                .failure
18109                .unwrap()
18110                .contains("interrupted")
18111        );
18112        assert!(Runner::resume(&id).is_err());
18113    }
18114
18115    #[test]
18116    fn startup_failure_keeps_typed_cause_and_separate_task_history() {
18117        ask_test_home();
18118        let mut runner = runner_at(RunStatus::Prep);
18119        let guard = StartupGuard::reserve(&mut runner.state, "review", Some("feature")).unwrap();
18120        let error = guard
18121            .finish(
18122                &mut runner.state,
18123                Err(
18124                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, "refused startup")
18125                        .into(),
18126                ),
18127            )
18128            .unwrap_err();
18129        assert_eq!(
18130            error.downcast_ref::<std::io::Error>().unwrap().kind(),
18131            std::io::ErrorKind::PermissionDenied
18132        );
18133        let failure = error.downcast_ref::<crate::run::StartupFailure>().unwrap();
18134        let mut task = crate::queue::Task::new(
18135            "review".into(),
18136            "criteria".into(),
18137            runner.state.repo.clone(),
18138            crate::queue::Source::Human,
18139        );
18140        task.record_startup_failure(failure.clone());
18141        task.record_startup_failure(failure.clone());
18142        assert_eq!(task.startup_failures.len(), 1);
18143        assert!(task.runs.is_empty());
18144        assert_eq!(task.attempts, 0);
18145    }
18146
18147    async fn exhausted_base_fixture() -> (tempfile::TempDir, Runner, String, String) {
18148        ask_test_home();
18149        let tmp = tempfile::tempdir().unwrap();
18150        let repo = tmp.path().join("repo");
18151        std::fs::create_dir(&repo).unwrap();
18152        init_repo(&repo);
18153        let base = git::rev_parse(&repo, "HEAD").await.unwrap();
18154        let origin = tmp.path().join("origin.git");
18155        git::git(&repo, &["init", "--bare", origin.to_str().unwrap()])
18156            .await
18157            .unwrap();
18158        git::git(
18159            &repo,
18160            &["remote", "add", "origin", origin.to_str().unwrap()],
18161        )
18162        .await
18163        .unwrap();
18164        git::git(&repo, &["checkout", "-b", "fix/retained"])
18165            .await
18166            .unwrap();
18167        std::fs::write(repo.join("retained"), "retained change").unwrap();
18168        git::git(&repo, &["add", "."]).await.unwrap();
18169        git::git(&repo, &["commit", "-m", "retained implementation"])
18170            .await
18171            .unwrap();
18172        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
18173        git::git(&repo, &["checkout", "main"]).await.unwrap();
18174        std::fs::write(repo.join("base-change"), "new base").unwrap();
18175        git::git(&repo, &["add", "."]).await.unwrap();
18176        git::git(&repo, &["commit", "-m", "base moved"])
18177            .await
18178            .unwrap();
18179        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
18180        git::git(&repo, &["checkout", "fix/retained"])
18181            .await
18182            .unwrap();
18183        let mut runner = runner_at(RunStatus::Voting);
18184        runner.state.repo = repo.clone();
18185        runner.state.base_commit = base;
18186        runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
18187        runner.state.config.disk.min_free_bytes = 0;
18188        runner.state.config.graph.review_rounds = 1;
18189        runner.state.config.verify.e2e = vec!["true".into()];
18190        runner.state.config.verify.gate = vec!["true".into()];
18191        runner.state.candidates = vec![Candidate {
18192            index: 0,
18193            label: 'A',
18194            agent: "fixture".into(),
18195            branch: "fix/retained".into(),
18196            worktree: repo.clone(),
18197            summary: String::new(),
18198            stat: String::new(),
18199            files: 1,
18200            commits: 1,
18201            empty: false,
18202            failed: None,
18203            verified_noop: None,
18204            duration_ms: 0,
18205            folded: false,
18206        }];
18207        runner.state.tally = Some(Tally {
18208            first_choice: BTreeMap::new(),
18209            borda: BTreeMap::new(),
18210            winner: 'A',
18211            rankings: 0,
18212            unanimous_initial: true,
18213            deliberated: false,
18214            changed_votes: 0,
18215            unanimous_final: true,
18216            tie_break: None,
18217            judges: 0,
18218            present: 0,
18219            quorum: 0,
18220            met_quorum: true,
18221            uncontested: Some("review-only".into()),
18222        });
18223        let mut task = crate::queue::Task::new(
18224            "fixture".into(),
18225            "fixture".into(),
18226            repo,
18227            crate::queue::Source::Human,
18228        );
18229        task.link_run(&runner.state.id);
18230        crate::queue::Queue::open().put(&mut task).unwrap();
18231        runner.state.origin = Some(crate::run::Origin::queue(&task.id));
18232        runner.state.base_sync = Some(BaseSync {
18233            tip: String::new(),
18234            behind: 1,
18235            attempts: BASE_SYNC_ROUNDS,
18236            conflict: None,
18237            already_in: None,
18238        });
18239        runner.sync_to_base().await.unwrap();
18240        assert_eq!(runner.state.status, RunStatus::Blocked);
18241        (tmp, runner, head, task.id)
18242    }
18243
18244    #[tokio::test]
18245    async fn rebase_preparation_failure_preserves_base_sync_budget_and_resumes() {
18246        let (_tmp, mut runner, head, _task) = exhausted_base_fixture().await;
18247        runner.state.status = RunStatus::Voting;
18248        runner.state.base_sync = None;
18249        runner.state.base_sync_recovery = Default::default();
18250        let scratch = runner.state.dir().join("base-sync");
18251        std::fs::create_dir_all(&scratch).unwrap();
18252        std::fs::write(scratch.join("obstruction"), "keep").unwrap();
18253        runner.sync_to_base().await.unwrap();
18254        assert!(runner.state.resource_block.is_some());
18255        assert!(!runner.state.base_sync_blocked());
18256        assert!(runner.state.base_sync.is_none());
18257        assert_eq!(
18258            std::fs::read_to_string(scratch.join("obstruction")).unwrap(),
18259            "keep"
18260        );
18261        assert_eq!(runner.state.base_episode_used(), 0);
18262        assert!(runner.state.base_sync_recovery.operations.is_empty());
18263        assert!(runner.state.rebase_fixes.is_empty());
18264        assert_eq!(
18265            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18266            head
18267        );
18268        std::fs::remove_dir_all(&scratch).unwrap();
18269        runner.state.resource_block = None;
18270        runner.sync_to_base().await.unwrap();
18271        assert!(!runner.state.base_sync_blocked());
18272        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18273        assert_eq!(runner.state.base_episode_used(), 1);
18274        assert!(runner.state.base_sync_recovery.operations[0].finished);
18275        assert!(runner.state.rebase_fixes.is_empty());
18276        assert!(git::is_ancestor(&runner.state.repo, "origin/main", "HEAD").await);
18277        assert!(git::is_clean(&runner.state.repo).await.unwrap());
18278    }
18279
18280    #[tokio::test]
18281    async fn rebase_legacy_sequencer_stop_reuses_the_original_reservation() {
18282        let (tmp, mut runner, head, owner) = exhausted_base_fixture().await;
18283        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18284        runner.state.base_sync_recovery = Default::default();
18285        runner.state.task_instruction = Some("fixture".into());
18286        runner.state.config.agents = vec![spec("fixture")];
18287        runner.state.config.graph.review_rounds = 0;
18288        runner.state.config.merge.mode = MergeMode::None;
18289        runner.state.driver_exited = true;
18290        let sync = runner.state.base_sync.as_mut().unwrap();
18291        sync.conflict = None;
18292        sync.attempts = 0;
18293        runner.state.reserve_base_operation(&head, &tip);
18294        runner.state.finish_base_operation(None);
18295        let detail = format!(
18296            "fix/retained conflicts with origin/main and did not rebase: \
18297             conflict not resolved after 28 of 3 fixer round(s) (not on the new base); \
18298             remaining conflicted path(s): none recorded; git said: \
18299             warning: execution failed: {}",
18300            git::REBASE_EXEC
18301        );
18302        runner.state.base_sync.as_mut().unwrap().conflict = Some(detail.clone());
18303        runner.state.record_base_sync_stop(&head);
18304        runner.state.rebase_fixes.push(crate::run::RebaseFixRecord {
18305            unstarted: false,
18306            agent: "fixture".into(),
18307            paths: Vec::new(),
18308            from: Some(head.clone()),
18309            finished: true,
18310            error: None,
18311            stop: None,
18312            onto: None,
18313            index_outside: None,
18314            launcher: None,
18315            infra: None,
18316            outage: None,
18317        });
18318        runner.state.save().unwrap();
18319        assert_eq!(
18320            crate::resume::validate(&crate::run::home(), &runner.state.id)
18321                .unwrap()
18322                .id,
18323            runner.state.id
18324        );
18325
18326        let dirty = runner.state.repo.join("owner-work");
18327        std::fs::write(&dirty, "keep").unwrap();
18328        runner.sync_to_base().await.unwrap();
18329        assert_eq!(std::fs::read_to_string(&dirty).unwrap(), "keep");
18330        assert!(runner.state.base_sync_recovery.operations[0].finished);
18331        assert!(runner.state.base_sync_blocked());
18332        std::fs::remove_file(dirty).unwrap();
18333
18334        let queue = crate::queue::Queue::open();
18335        let id = runner.state.id.clone();
18336        assert!(crate::resume::pin_queued(&queue, &id, None, None).unwrap());
18337        let _claim = queue.claim(&owner).unwrap();
18338        let mut task = queue.get(&owner).unwrap();
18339        let config = tmp.path().join("test-config.toml");
18340        std::fs::write(&config, "[disk]\nmin_free_bytes = 0\n").unwrap();
18341        let opts = crate::daemon::Opts {
18342            repo: task.repo.clone(),
18343            config: Some(config),
18344            ..Default::default()
18345        };
18346        crate::daemon::run_claimed(&opts, &queue, &mut task).await;
18347        let task = queue.get(&owner).unwrap();
18348        assert_eq!(
18349            task.runs.as_slice(),
18350            std::slice::from_ref(&id),
18351            "{:?}",
18352            task.hold_reason
18353        );
18354        runner.state = RunState::load(&id).unwrap();
18355        assert!(!runner.state.base_sync_blocked());
18356        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
18357        assert_eq!(runner.state.base_sync_recovery.operations.len(), 1);
18358        assert!(runner.state.base_sync_recovery.operations[0].finished);
18359        assert_eq!(
18360            runner.state.base_sync_recovery.stops.last().unwrap().detail,
18361            detail
18362        );
18363        assert_eq!(runner.state.rebase_fixes.len(), 1);
18364        assert!(git::is_ancestor(&runner.state.repo, &tip, "HEAD").await);
18365    }
18366
18367    #[cfg(unix)]
18368    #[tokio::test]
18369    async fn base_recovery_control_rechecks_owner_decision_and_routing_at_consumption() {
18370        for routed in [false, true] {
18371            let (_tmp, mut runner, head, owner) = exhausted_base_fixture().await;
18372            let home = crate::run::home();
18373            let queue = crate::queue::Queue::open();
18374            let task = queue.get(&owner).unwrap();
18375            runner.state.task_instruction = Some(task.instruction.clone());
18376            runner.state.driver_exited = true;
18377            runner.state.save().unwrap();
18378            let questions = crate::ask::Questions::at(home.join("questions"));
18379            let mut q = crate::ask::Question::new(
18380                runner.state.id.clone(),
18381                "base-recovery".into(),
18382                "owner".into(),
18383                "Recover bounded base movement?".into(),
18384                String::new(),
18385                vec!["recover".into()],
18386            );
18387            q.actions.insert(
18388                "recover".into(),
18389                crate::ask::ChoiceAction::RecoverBase {
18390                    run: runner.state.id.clone(),
18391                    stop: runner.state.base_sync_recovery.stop.clone().unwrap(),
18392                    episode: runner.state.base_sync_recovery.episodes.last().unwrap().id,
18393                },
18394            );
18395            q.routed_task = Some(owner.clone());
18396            q.answer(crate::ask::Answer::Choice("recover".into()))
18397                .unwrap();
18398            questions.put(&mut q).unwrap();
18399            crate::base_recovery_control::recover(
18400                &queue,
18401                &home,
18402                crate::base_recovery_control::Request {
18403                    run: runner.state.id.clone(),
18404                    head: head.clone(),
18405                    actor: "decisions".into(),
18406                    request: q.id.clone(),
18407                    decision: Some((owner.clone(), q.answered_at.unwrap())),
18408                    expected_stop: Some((
18409                        runner.state.base_sync_recovery.stop.clone().unwrap(),
18410                        runner.state.base_sync_recovery.episodes.last().unwrap().id,
18411                    )),
18412                    evidence_digest: None,
18413                },
18414            )
18415            .await
18416            .unwrap();
18417            if routed {
18418                questions
18419                    .update(&q.id, |q| {
18420                        q.routed_task = Some("another-owner".into());
18421                        Ok(())
18422                    })
18423                    .unwrap();
18424            } else {
18425                let mut task = queue.get(&owner).unwrap();
18426                task.hold_manual(Some("new owner decision".into()));
18427                // Keep the generation to exercise the separate owner-decision binding.
18428                task.status = crate::queue::TaskStatus::Queued;
18429                queue.put(&mut task).unwrap();
18430            }
18431            runner.state = RunState::load(&runner.state.id).unwrap();
18432            runner.sync_to_base().await.unwrap();
18433            let approval = runner
18434                .state
18435                .base_sync_recovery
18436                .authorizations
18437                .last()
18438                .unwrap();
18439            assert!(approval.consumed);
18440            assert!(approval.invalidated.as_ref().unwrap().contains(if routed {
18441                "routing"
18442            } else {
18443                "owner decision"
18444            }));
18445            assert_eq!(
18446                runner.state.base_sync.as_ref().unwrap().attempts,
18447                BASE_SYNC_ROUNDS
18448            );
18449            assert_eq!(
18450                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18451                head
18452            );
18453        }
18454    }
18455
18456    #[cfg(unix)]
18457    #[tokio::test]
18458    async fn base_recovery_authorizes_its_worker_but_rejects_other_workers() {
18459        const CHILD: &str = "MAGI_BASE_RECOVERY_WORKER_TEST";
18460        if std::env::var_os(CHILD).is_none() {
18461            let home = tempfile::tempdir().unwrap();
18462            let output = std::process::Command::new(std::env::current_exe().unwrap())
18463                .args([
18464                    "--exact",
18465                    "graph::tests::base_recovery_authorizes_its_worker_but_rejects_other_workers",
18466                    "--nocapture",
18467                ])
18468                .env(CHILD, "1")
18469                .env("MAGI_HOME", home.path())
18470                .env("MAGI_WORKER_HOME", home.path())
18471                .env("MAGI_WORKER_ID", "abcdef")
18472                .output()
18473                .unwrap();
18474            assert!(
18475                output.status.success()
18476                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
18477                "{}\n{}",
18478                String::from_utf8_lossy(&output.stdout),
18479                String::from_utf8_lossy(&output.stderr)
18480            );
18481            return;
18482        }
18483        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
18484        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
18485        let home = crate::run::home();
18486        let queue = crate::queue::Queue::open();
18487        let mut owner = queue.get(&task).unwrap();
18488        owner.release_operator("test-release", None);
18489        owner.start(runner.state.id.clone());
18490        queue.put(&mut owner).unwrap();
18491        runner.state.driver_exited = true;
18492        runner.state.task_instruction = Some(owner.instruction.clone());
18493        runner.state.save().unwrap();
18494        let _claim = queue.claim(&task).unwrap();
18495        let reserve = |id: &str| {
18496            let directory = home.join("workers/jobs").join(id);
18497            std::fs::create_dir_all(&directory).unwrap();
18498            let job = crate::worker::Job {
18499                id: id.into(),
18500                sequence: 1,
18501                kind: "task".into(),
18502                key: format!("task:{task}"),
18503                payload: serde_json::json!({"opts": crate::daemon::Opts::default(), "queue": queue.root(), "task": task}),
18504                generation: "fixture-generation".into(),
18505                version: None,
18506                status: crate::worker::Status::Running,
18507                result: None,
18508                pid: Some(std::process::id()),
18509                created_at: 0,
18510                finished_at: None,
18511            };
18512            std::fs::write(
18513                directory.join("job.json"),
18514                serde_json::to_vec(&job).unwrap(),
18515            )
18516            .unwrap();
18517            crate::worker::execution_lease_for_test(&directory.join("live.lock"))
18518        };
18519        let _own = reserve("abcdef");
18520        let other = reserve("fedcba");
18521        assert!(
18522            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
18523                .await
18524                .is_err()
18525        );
18526        assert!(
18527            RunState::load(&runner.state.id)
18528                .unwrap()
18529                .base_sync_recovery
18530                .authorizations
18531                .is_empty()
18532        );
18533        drop(other);
18534        assert!(crate::daemon::is_working_on(
18535            &home,
18536            &runner.state.id,
18537            Timestamp::now()
18538        ));
18539        assert!(
18540            !crate::daemon::is_working_on_other(&home, &runner.state.id, Timestamp::now()).unwrap()
18541        );
18542        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
18543            .await
18544            .unwrap();
18545        assert!(
18546            RunState::load(&runner.state.id)
18547                .unwrap()
18548                .base_recovery_pending()
18549        );
18550    }
18551
18552    #[cfg(unix)]
18553    #[tokio::test]
18554    async fn base_recovery_authorizes_a_crashed_driver_with_a_free_matching_lease() {
18555        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
18556        let home = crate::run::home();
18557        runner.state.driver_pid = Some(std::process::id());
18558        runner.state.driver_started_at = crate::proc::process_started_at(std::process::id());
18559        runner.state.driver_exited = false;
18560        runner.state.begin_pass();
18561        runner.state.save().unwrap();
18562        let mut driver = crate::driver::DriverGuard::acquire(&home, &runner.state).unwrap();
18563        driver.record(&runner.state).unwrap();
18564        let saved = std::fs::read(runner.state.dir().join("run.json")).unwrap();
18565        // Preserve the durable claim as if the process died before Drop saved.
18566        drop(driver);
18567        std::fs::write(runner.state.dir().join("run.json"), saved).unwrap();
18568        assert_eq!(
18569            runner.state.liveness_under(&home, false),
18570            crate::run::Liveness::Dead
18571        );
18572        let queue = crate::queue::Queue::open();
18573        let _claim = queue.claim(&task).unwrap();
18574        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18575            .await
18576            .unwrap();
18577        let disk = RunState::load(&runner.state.id).unwrap();
18578        assert!(!disk.driver_exited);
18579        assert!(disk.base_recovery_pending());
18580    }
18581
18582    #[cfg(unix)]
18583    #[tokio::test]
18584    async fn base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase() {
18585        const CHILD: &str = "MAGI_BASE_RECOVERY_CLOSURE_TEST";
18586        if std::env::var_os(CHILD).is_none() {
18587            use std::os::unix::fs::PermissionsExt;
18588            let tmp = tempfile::tempdir().unwrap();
18589            let gh = tmp.path().join("gh");
18590            std::fs::write(&gh, r#"#!/bin/sh
18591case "$1 $2" in
18592  'pr view') printf '{"headRefName":"fix/retained","headRefOid":"%s","baseRefName":"main","state":"OPEN","isCrossRepository":false}' "$(git rev-parse fix/retained)" ;;
18593  'pr close') if [ ! -f "$MAGI_BASE_CLOSURE_MARKER" ]; then touch "$MAGI_BASE_CLOSURE_MARKER"; echo 'transient closure failure' >&2; exit 1; fi ;;
18594  *) exit 2 ;;
18595esac
18596"#).unwrap();
18597            std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
18598            let mut paths = vec![tmp.path().to_path_buf()];
18599            paths.extend(std::env::split_paths(&std::env::var_os("PATH").unwrap()));
18600            let output = std::process::Command::new(std::env::current_exe().unwrap())
18601                .args(["--exact", "graph::tests::base_recovery_retries_integrated_pr_closure_without_authorizing_a_rebase", "--nocapture"])
18602                .env(CHILD, "1")
18603                .env("MAGI_BASE_CLOSURE_MARKER", tmp.path().join("closure-attempted"))
18604                .env("PATH", std::env::join_paths(paths).unwrap())
18605                .env_remove("MAGI_WORKER_HOME").env_remove("MAGI_WORKER_ID")
18606                .output().unwrap();
18607            assert!(
18608                output.status.success()
18609                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
18610                "{}\n{}",
18611                String::from_utf8_lossy(&output.stdout),
18612                String::from_utf8_lossy(&output.stderr)
18613            );
18614            return;
18615        }
18616        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18617        let repo = runner.state.repo.clone();
18618        git::git(&repo, &["checkout", "main"]).await.unwrap();
18619        git::git(&repo, &["cherry-pick", &head]).await.unwrap();
18620        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
18621        git::git(&repo, &["checkout", "fix/retained"])
18622            .await
18623            .unwrap();
18624        runner.state.pr = Some(crate::run::PrRecord {
18625            url: "https://example.test/project/pull/1".into(),
18626            number: 1,
18627            state: "open".into(),
18628            checks: "unknown".into(),
18629            round: 0,
18630            rounds: 1,
18631            red_at_merge: Vec::new(),
18632        });
18633        runner.sync_to_base().await.unwrap();
18634        assert_eq!(runner.state.status, RunStatus::Blocked);
18635        assert_eq!(
18636            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
18637            crate::base_sync_recovery::StopKind::ClosingIntegratedPr
18638        );
18639        assert!(runner.state.base_sync_closure_pending());
18640        assert!(crate::handover::can_resume(&runner.state));
18641        let queue = crate::queue::Queue::open();
18642        assert!(!crate::base_sync_recovery::held_task(
18643            &queue,
18644            &queue.get(&task).unwrap()
18645        ));
18646        assert!(runner.state.authorize_base_sync(&task).is_err());
18647        // Legacy closure stops have no typed stop but must retain the checkpoint.
18648        runner.state.base_sync_recovery.stop = None;
18649        runner.state.status = RunStatus::Voting;
18650        runner.state.gate_ran = true;
18651        runner.state.config.graph.review_rounds = 0;
18652        runner.state.save().unwrap();
18653        assert!(crate::handover::can_resume(&runner.state));
18654        runner.state = RunState::load(&runner.state.id).unwrap();
18655        runner.execute_graph().await.unwrap();
18656        assert_eq!(runner.state.status, RunStatus::AlreadyInBase);
18657        assert_eq!(runner.state.pr.as_ref().unwrap().state, "closed");
18658        assert_eq!(
18659            runner.state.base_sync.as_ref().unwrap().attempts,
18660            BASE_SYNC_ROUNDS
18661        );
18662        assert!(runner.state.base_sync_recovery.authorizations.is_empty());
18663        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), head);
18664        assert!(runner.state.reviews.is_empty());
18665        assert!(runner.state.gate.is_empty());
18666    }
18667
18668    #[cfg(unix)]
18669    #[tokio::test]
18670    async fn base_recovery_authorization_requires_current_owner_free_lease_and_clean_tree() {
18671        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
18672        runner.state.driver_exited = true;
18673        runner.state.save().unwrap();
18674        let home = crate::run::home();
18675        let queue = crate::queue::Queue::open();
18676        let _claim = queue.claim(&task).unwrap();
18677        let lease = crate::driver::maintenance(&home, &runner.state.id).unwrap();
18678        assert!(
18679            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18680                .await
18681                .is_err()
18682        );
18683        drop(lease);
18684        std::fs::write(runner.state.repo.join("dirty"), "retained uncommitted work").unwrap();
18685        assert!(
18686            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18687                .await
18688                .is_err()
18689        );
18690        std::fs::remove_file(runner.state.repo.join("dirty")).unwrap();
18691        Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18692            .await
18693            .unwrap();
18694        let disk = RunState::load(&runner.state.id).unwrap();
18695        assert!(disk.base_recovery_pending());
18696        assert_eq!(disk.base_sync_recovery.authorizations.len(), 1);
18697        assert!(
18698            Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18699                .await
18700                .is_err()
18701        );
18702        assert_eq!(
18703            RunState::load(&runner.state.id)
18704                .unwrap()
18705                .base_sync_recovery
18706                .authorizations
18707                .len(),
18708            1
18709        );
18710        let mut owner = queue.get(&task).unwrap();
18711        owner.runs.push("20260101-000000-ffff".into());
18712        queue.put(&mut owner).unwrap();
18713        let error = Runner::authorize_base_recovery(&home, &runner.state.id, &task)
18714            .await
18715            .unwrap_err();
18716        assert!(error.to_string().contains("run task ownership changed"));
18717    }
18718
18719    #[cfg(unix)]
18720    #[tokio::test]
18721    async fn base_recovery_legacy_voting_and_repeated_resume_stay_blocked() {
18722        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
18723        let mut legacy = serde_json::to_value(&runner.state).unwrap();
18724        legacy.as_object_mut().unwrap().remove("base_sync_recovery");
18725        legacy["status"] = serde_json::json!("voting");
18726        runner.state = serde_json::from_value(legacy).unwrap();
18727        runner.state.save().unwrap();
18728        for _ in 0..3 {
18729            runner.execute_graph().await.unwrap();
18730            assert_eq!(runner.state.status, RunStatus::Blocked);
18731            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
18732            assert!(!crate::handover::can_resume(&runner.state));
18733            assert_eq!(
18734                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18735                head
18736            );
18737            assert!(runner.state.reviews.is_empty());
18738            assert!(!runner.state.gate_ran);
18739        }
18740        let notice = crate::notices::run_ended(&runner.state).unwrap();
18741        let stop = runner.state.base_sync_recovery.stop.clone().unwrap();
18742        runner.state.begin_pass();
18743        runner.state.status = RunStatus::Voting;
18744        runner.deliberate().await.unwrap();
18745        runner.vote().await.unwrap();
18746        runner.finish_after_tally().await.unwrap();
18747        assert_eq!(runner.state.status, RunStatus::Blocked);
18748        assert_eq!(runner.state.base_sync_recovery.stop.as_ref(), Some(&stop));
18749        assert_eq!(
18750            crate::notices::run_ended(&runner.state).unwrap().since,
18751            notice.since
18752        );
18753    }
18754
18755    #[cfg(unix)]
18756    #[tokio::test]
18757    async fn base_recovery_never_authorizes_conflicts_publication_or_unknown_stops() {
18758        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18759        for detail in [
18760            "fix/retained conflicts with origin/main and did not rebase: conflict",
18761            "rebased fix/retained locally but origin refused the push",
18762            "unknown failure",
18763        ] {
18764            runner.state.base_sync.as_mut().unwrap().conflict = Some(detail.into());
18765            runner.state.record_base_sync_stop(&head);
18766            assert!(runner.state.authorize_base_sync(&task).is_err());
18767            runner.state.status = RunStatus::Voting;
18768            runner.execute_graph().await.unwrap();
18769            assert_eq!(runner.state.status, RunStatus::Blocked);
18770            assert!(!crate::handover::can_resume(&runner.state));
18771            assert_eq!(
18772                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
18773                head
18774            );
18775        }
18776    }
18777
18778    #[tokio::test]
18779    async fn base_recovery_preparation_stop_keeps_remaining_budget() {
18780        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18781        let state = &mut runner.state;
18782        let tip = state.base_sync.as_ref().unwrap().tip.clone();
18783        let branch = state.winner().unwrap().branch.clone();
18784        state.base_sync_recovery = Default::default();
18785        state.base_sync.as_mut().unwrap().attempts = 0;
18786        state.reserve_base_operation(&head, &tip);
18787        state.finish_base_operation(None);
18788        let detail = format!(
18789            "could not rebase {branch} onto origin/main: spawn git rev-parse --git-path magi-rebase-heads: Invalid directory (os error 267)"
18790        );
18791        state.base_sync.as_mut().unwrap().conflict = Some(detail.clone());
18792        state.event("land", detail);
18793        state.record_base_sync_stop_as(&head, Some(crate::base_sync_recovery::StopKind::Unknown));
18794        assert!(state.unknown_preparation_stop(&head));
18795        let digest = state.preparation_digest(&head).unwrap();
18796        state
18797            .base_sync_recovery
18798            .operations
18799            .last_mut()
18800            .unwrap()
18801            .validated_head = Some(head.clone());
18802        assert!(!state.unknown_preparation_stop(&head));
18803        state
18804            .base_sync_recovery
18805            .operations
18806            .last_mut()
18807            .unwrap()
18808            .validated_head = None;
18809        state.task_instruction = Some(crate::queue::Queue::open().get(&task).unwrap().instruction);
18810        state.driver_exited = true;
18811        state.save().unwrap();
18812        let home = crate::run::home();
18813        let queue = crate::queue::Queue::open();
18814        let inspection = crate::repair_budget::legacy::inspect(&queue, &home, &task, &state.id)
18815            .await
18816            .unwrap();
18817        assert_eq!(inspection["classification"], "recoverable-unknown-stop");
18818        assert_eq!(inspection["evidence_digest"], digest);
18819        let request = crate::base_recovery_control::Request {
18820            run: state.id.clone(),
18821            head: head.clone(),
18822            actor: "test".into(),
18823            request: "preparation".into(),
18824            decision: None,
18825            expected_stop: None,
18826            evidence_digest: Some(digest),
18827        };
18828        let mut stale = request.clone();
18829        stale.evidence_digest = Some("stale".into());
18830        assert!(
18831            crate::base_recovery_control::recover(&queue, &home, stale)
18832                .await
18833                .is_err()
18834        );
18835        let scratch = state.dir().join("base-sync");
18836        std::fs::create_dir(&scratch).unwrap();
18837        assert!(
18838            crate::base_recovery_control::recover(&queue, &home, request.clone())
18839                .await
18840                .is_err()
18841        );
18842        std::fs::remove_dir(&scratch).unwrap();
18843        git::git(&state.repo, &["checkout", "main"]).await.unwrap();
18844        git::git(
18845            &state.repo,
18846            &[
18847                "commit",
18848                "--allow-empty",
18849                "-m",
18850                "base advanced after inspection",
18851            ],
18852        )
18853        .await
18854        .unwrap();
18855        git::git(&state.repo, &["push", "origin", "main"])
18856            .await
18857            .unwrap();
18858        git::git(&state.repo, &["checkout", "fix/retained"])
18859            .await
18860            .unwrap();
18861        let outcome = crate::base_recovery_control::recover(&queue, &home, request.clone())
18862            .await
18863            .unwrap();
18864        assert!(!outcome.repeated);
18865        assert!(
18866            crate::base_recovery_control::recover(&queue, &home, request)
18867                .await
18868                .unwrap()
18869                .repeated
18870        );
18871        runner.state = RunState::load(&runner.state.id).unwrap();
18872        assert!(runner.state.base_recovery_pending());
18873        runner.sync_to_base().await.unwrap();
18874        assert!(!runner.state.base_sync_blocked());
18875        assert!(!runner.state.consume_base_recovery(&head));
18876        assert_eq!(runner.state.base_episode_used(), 2);
18877        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
18878        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 1);
18879        assert_eq!(runner.state.base_sync_recovery.stops.len(), 1);
18880    }
18881
18882    #[cfg(unix)]
18883    #[tokio::test]
18884    async fn base_recovery_consumption_survives_crash_without_another_attempt() {
18885        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18886        runner.state.authorize_base_sync(&task).unwrap();
18887        assert!(runner.state.consume_base_recovery(&head));
18888        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
18889        runner.state.reserve_base_operation(&head, &tip);
18890        runner.state.save().unwrap();
18891        runner.state = RunState::load(&runner.state.id).unwrap();
18892        assert!(!runner.state.consume_base_recovery(&head));
18893        runner.sync_to_base().await.unwrap();
18894        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18895        assert_eq!(runner.state.base_episode_used(), 1);
18896        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
18897        assert!(
18898            runner
18899                .state
18900                .base_sync_recovery
18901                .operations
18902                .last()
18903                .unwrap()
18904                .finished
18905        );
18906        assert!(!runner.state.base_sync_blocked());
18907        runner.sync_to_base().await.unwrap();
18908        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18909    }
18910
18911    #[cfg(unix)]
18912    #[tokio::test]
18913    async fn base_recovery_legacy_authorization_and_unrecorded_wait_grant_no_interval() {
18914        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
18915        // Both historical diagnostic spellings retain an exhaustion identity.
18916        let original = runner
18917            .state
18918            .base_sync
18919            .as_ref()
18920            .unwrap()
18921            .conflict
18922            .clone()
18923            .unwrap();
18924        runner.state.base_sync.as_mut().unwrap().conflict = Some(
18925            original
18926                .replace("synchronization(s)", "rebase(s)")
18927                .replace("synchronizing", "rebasing"),
18928        );
18929        runner.state.base_sync_recovery = Default::default();
18930        runner.state.record_base_sync_stop(&head);
18931        assert_eq!(
18932            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
18933            crate::base_sync_recovery::StopKind::Exhausted
18934        );
18935        runner.state.authorize_base_sync(&task).unwrap();
18936        let mut legacy = serde_json::to_value(&runner.state).unwrap();
18937        let auth = legacy["base_sync_recovery"]["authorizations"][0]
18938            .as_object_mut()
18939            .unwrap();
18940        auth.remove("interval");
18941        auth.remove("scope");
18942        runner.state = serde_json::from_value(legacy).unwrap();
18943        assert!(runner.state.consume_base_recovery(&head));
18944        assert_eq!(runner.state.base_episode_used(), 3);
18945        runner.sync_to_base().await.unwrap();
18946        assert_eq!(runner.state.base_episode_used(), 4);
18947        runner.state.resource_block = Some(crate::run::ResourceBlock {
18948            node: "gate".into(),
18949            kind: "cache".into(),
18950            detail: "legacy wait".into(),
18951            at: Timestamp::now(),
18952            cause: crate::run::ResourceBlockCause::Unrecorded,
18953        });
18954        runner.state.save().unwrap();
18955        assert!(
18956            runner
18957                .state
18958                .base_sync_recovery
18959                .episodes
18960                .last()
18961                .unwrap()
18962                .boundary
18963                .is_none()
18964        );
18965        runner.state.resource_block = None;
18966        advance_base_fixture(&runner).await;
18967        runner.sync_to_base().await.unwrap();
18968        assert!(runner.state.base_sync_blocked());
18969        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
18970    }
18971
18972    #[cfg(unix)]
18973    async fn advance_base_fixture(runner: &Runner) {
18974        let repo = &runner.state.repo;
18975        for args in [
18976            vec!["checkout", "main"],
18977            vec!["commit", "--allow-empty", "-m", "base advanced"],
18978            vec!["push", "origin", "main"],
18979            vec!["checkout", "fix/retained"],
18980        ] {
18981            git::git(repo, &args).await.unwrap();
18982        }
18983    }
18984
18985    #[cfg(unix)]
18986    fn fresh_base_interval_fixture(runner: &mut Runner) {
18987        runner.state.base_sync.as_mut().unwrap().attempts = 0;
18988        runner.state.base_sync.as_mut().unwrap().conflict = None;
18989        runner.state.base_sync_recovery = Default::default();
18990        runner.state.status = RunStatus::Voting;
18991    }
18992
18993    #[cfg(unix)]
18994    #[tokio::test]
18995    async fn base_recovery_resource_boundary_requires_new_owner_and_is_single_use() {
18996        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
18997        fresh_base_interval_fixture(&mut runner);
18998        runner.state.begin_pass();
18999        runner.sync_to_base().await.unwrap();
19000        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19001        runner.state.resource_block = Some(crate::run::ResourceBlock {
19002            node: "gate".into(),
19003            kind: "build cache".into(),
19004            detail: "busy".into(),
19005            at: Timestamp::now(),
19006            cause: crate::run::ResourceBlockCause::Timeout {
19007                waited_secs: 1,
19008                limit_secs: 1,
19009            },
19010        });
19011        runner.state.save().unwrap();
19012        let queue = crate::queue::Queue::open();
19013        let mut owner = queue.get(&task).unwrap();
19014        runner.state.task_instruction = Some(owner.instruction.clone());
19015        owner.release_operator("fixture-owner", None);
19016        queue.put(&mut owner).unwrap();
19017        let approval = owner.resumption.clone().unwrap();
19018        runner.state.resource_block = None;
19019        runner.state.save().unwrap();
19020        runner.state = RunState::load(&runner.state.id).unwrap();
19021        advance_base_fixture(&runner).await;
19022        runner.sync_to_base().await.unwrap();
19023        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
19024        assert_eq!(runner.state.base_episode_used(), 1);
19025        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
19026        assert!(
19027            runner.state.base_sync_recovery.episodes[0]
19028                .boundary
19029                .as_ref()
19030                .unwrap()
19031                .consumed
19032        );
19033        assert!(
19034            !runner
19035                .state
19036                .renew_base_episode(&task, &approval, &head, "base")
19037        );
19038        for _ in 0..3 {
19039            owner.release_operator("fixture-owner", None);
19040            queue.put(&mut owner).unwrap();
19041            runner.state = RunState::load(&runner.state.id).unwrap();
19042            runner.state.begin_pass();
19043            runner.sync_to_base().await.unwrap();
19044            assert_eq!(runner.state.base_sync_recovery.episodes.len(), 2);
19045            assert_eq!(runner.state.base_episode_used(), 1);
19046        }
19047        runner.state.resource_block = Some(crate::run::ResourceBlock {
19048            node: "gate".into(),
19049            kind: "disk pressure".into(),
19050            detail: "free space required".into(),
19051            at: Timestamp::now(),
19052            cause: crate::run::ResourceBlockCause::Other,
19053        });
19054        runner.state.end_pass_parked(ParkCause::Interrupt {
19055            reason: "disk pressure".into(),
19056        });
19057        runner.state.save().unwrap();
19058        owner.release_operator("fixture-owner-after-disk", None);
19059        queue.put(&mut owner).unwrap();
19060        runner.state.resource_block = None;
19061        advance_base_fixture(&runner).await;
19062        runner.sync_to_base().await.unwrap();
19063        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 3);
19064        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 3);
19065        assert_eq!(runner.state.base_episode_used(), 1);
19066        assert_eq!(runner.state.base_sync_recovery.renewals.len(), 2);
19067    }
19068
19069    #[cfg(unix)]
19070    #[tokio::test]
19071    async fn base_recovery_continuous_advancement_stops_at_four() {
19072        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
19073        fresh_base_interval_fixture(&mut runner);
19074        for spent in 1..=BASE_SYNC_ROUNDS {
19075            runner.sync_to_base().await.unwrap();
19076            assert!(!runner.state.base_sync_blocked());
19077            assert_eq!(runner.state.base_episode_used(), spent);
19078            advance_base_fixture(&runner).await;
19079        }
19080        runner.sync_to_base().await.unwrap();
19081        assert_eq!(
19082            runner.state.base_sync_recovery.stop.as_ref().unwrap().kind,
19083            crate::base_sync_recovery::StopKind::Exhausted
19084        );
19085        let stop = runner.state.base_sync_recovery.stop.as_ref().unwrap();
19086        assert!(stop.unverified_sync);
19087        let action = runner.state.base_sync_next_action();
19088        assert!(action.contains("never reached its gate"));
19089        assert!(action.contains("4/4 in episode 0, 4 lifetime"));
19090        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19091        runner.state = RunState::load(&runner.state.id).unwrap();
19092        runner.sync_to_base().await.unwrap();
19093        assert_eq!(runner.state.base_episode_used(), 4);
19094        assert_eq!(runner.state.base_sync_recovery.episodes.len(), 1);
19095    }
19096
19097    #[cfg(unix)]
19098    #[tokio::test]
19099    async fn base_recovery_stop_diagnostic_requires_synced_head_without_current_gate() {
19100        let (_tmp, mut runner, head, _) = exhausted_base_fixture().await;
19101        runner.state.ensure_base_episode();
19102        // Verification progress alone is not evidence of a successful sync.
19103        runner.state.record_base_progress(&head);
19104        runner.state.base_sync_recovery.stop = None;
19105        runner.state.record_base_sync_stop(&head);
19106        assert!(
19107            !runner
19108                .state
19109                .base_sync_recovery
19110                .stop
19111                .as_ref()
19112                .unwrap()
19113                .unverified_sync
19114        );
19115
19116        runner.state.finish_base_operation(Some(&head));
19117        // A gate for another head cannot verify this synchronization.
19118        runner.state.gate_ran = true;
19119        runner.state.gate_head = Some("older-head".into());
19120        runner.state.base_sync_recovery.stop = None;
19121        runner.state.record_base_sync_stop(&head);
19122        runner.state.save().unwrap();
19123        runner.state = RunState::load(&runner.state.id).unwrap();
19124        assert!(
19125            runner
19126                .state
19127                .base_sync_recovery
19128                .stop
19129                .as_ref()
19130                .unwrap()
19131                .unverified_sync
19132        );
19133
19134        runner.state.gate_head = Some(head.clone());
19135        runner.state.base_sync_recovery.stop = None;
19136        runner.state.record_base_sync_stop(&head);
19137        assert!(
19138            !runner
19139                .state
19140                .base_sync_recovery
19141                .stop
19142                .as_ref()
19143                .unwrap()
19144                .unverified_sync
19145        );
19146        assert!(
19147            !runner
19148                .state
19149                .base_sync_next_action()
19150                .contains("never reached its gate")
19151        );
19152
19153        // Historical records cannot establish the missing synchronization evidence.
19154        let mut legacy = serde_json::to_value(&runner.state).unwrap();
19155        legacy["base_sync_recovery"]["stop"]
19156            .as_object_mut()
19157            .unwrap()
19158            .remove("unverified_sync");
19159        legacy["base_sync_recovery"]["episodes"][0]
19160            .as_object_mut()
19161            .unwrap()
19162            .remove("last_sync_head");
19163        runner.state = serde_json::from_value(legacy).unwrap();
19164        assert!(
19165            !runner
19166                .state
19167                .base_sync_recovery
19168                .stop
19169                .as_ref()
19170                .unwrap()
19171                .unverified_sync
19172        );
19173        assert!(
19174            runner.state.base_sync_recovery.episodes[0]
19175                .last_sync_head
19176                .is_none()
19177        );
19178    }
19179
19180    #[cfg(unix)]
19181    #[tokio::test]
19182    async fn base_recovery_next_action_reports_new_episode_and_pending_approval() {
19183        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19184        runner.state.authorize_base_sync(&task).unwrap();
19185        assert!(
19186            runner
19187                .state
19188                .base_sync_next_action()
19189                .contains("Approval recorded")
19190        );
19191        assert!(
19192            runner
19193                .state
19194                .base_sync_next_action()
19195                .contains("4/4 in episode 0, 4 lifetime")
19196        );
19197        assert!(runner.state.consume_base_recovery(&head));
19198        assert!(
19199            runner
19200                .state
19201                .base_sync_next_action()
19202                .contains("0/4 in episode 1, 4 lifetime")
19203        );
19204    }
19205
19206    #[cfg(unix)]
19207    #[tokio::test]
19208    async fn base_recovery_changed_head_invalidates_without_spending() {
19209        let (_tmp, mut runner, _, task) = exhausted_base_fixture().await;
19210        runner.state.authorize_base_sync(&task).unwrap();
19211        git::git(
19212            &runner.state.repo,
19213            &["commit", "--allow-empty", "-m", "external head change"],
19214        )
19215        .await
19216        .unwrap();
19217        runner.sync_to_base().await.unwrap();
19218        let a = runner
19219            .state
19220            .base_sync_recovery
19221            .authorizations
19222            .last()
19223            .unwrap();
19224        assert!(a.consumed);
19225        assert!(a.invalidated.as_deref().unwrap().contains("HEAD changed"));
19226        runner.state = RunState::load(&runner.state.id).unwrap();
19227        assert!(
19228            runner
19229                .state
19230                .base_sync_next_action()
19231                .contains("Approval invalidated")
19232        );
19233        assert!(!runner.state.base_recovery_pending());
19234        assert!(runner.state.base_sync_blocked());
19235        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19236    }
19237
19238    #[cfg(unix)]
19239    #[tokio::test]
19240    async fn base_recovery_stale_fetched_base_invalidates_approval() {
19241        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19242        runner.state.driver_exited = true;
19243        runner.state.save().unwrap();
19244        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
19245            .await
19246            .unwrap();
19247        runner.state = RunState::load(&runner.state.id).unwrap();
19248        advance_base_fixture(&runner).await;
19249        runner.sync_to_base().await.unwrap();
19250        let a = runner
19251            .state
19252            .base_sync_recovery
19253            .authorizations
19254            .last()
19255            .unwrap();
19256        assert!(
19257            a.consumed
19258                && a.invalidated
19259                    .as_deref()
19260                    .unwrap()
19261                    .contains("fetched base changed")
19262        );
19263        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 4);
19264        assert_eq!(
19265            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19266            head
19267        );
19268        Runner::authorize_base_recovery(&crate::run::home(), &runner.state.id, &task)
19269            .await
19270            .unwrap();
19271        runner.state = RunState::load(&runner.state.id).unwrap();
19272        runner.sync_to_base().await.unwrap();
19273        assert!(!runner.state.base_sync_blocked());
19274        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19275    }
19276
19277    #[cfg(unix)]
19278    #[tokio::test]
19279    async fn base_recovery_crash_after_git_finishes_reserved_operation_once() {
19280        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19281        runner.state.authorize_base_sync(&task).unwrap();
19282        assert!(runner.state.consume_base_recovery(&head));
19283        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19284        runner.state.reserve_base_operation(&head, &tip);
19285        runner.state.save().unwrap();
19286        let scratch = runner.state.dir().join("base-sync");
19287        assert_eq!(
19288            crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
19289                .await
19290                .unwrap(),
19291            crate::rebase::Rebased::Applied
19292        );
19293        runner.state = RunState::load(&runner.state.id).unwrap();
19294        runner.sync_to_base().await.unwrap();
19295        assert!(
19296            runner
19297                .state
19298                .base_sync_recovery
19299                .operations
19300                .last()
19301                .unwrap()
19302                .finished
19303        );
19304        assert_eq!(runner.state.base_episode_used(), 1);
19305        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19306        assert!(!runner.state.base_sync_blocked());
19307    }
19308
19309    #[cfg(unix)]
19310    #[tokio::test]
19311    async fn base_recovery_crash_preserves_untracked_files() {
19312        for ignored in [false, true] {
19313            let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19314            runner.state.authorize_base_sync(&task).unwrap();
19315            assert!(runner.state.consume_base_recovery(&head));
19316            let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19317            runner.state.reserve_base_operation(&head, &tip);
19318            runner.state.save().unwrap();
19319            let scratch = runner.state.dir().join("base-sync");
19320            assert_eq!(
19321                crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
19322                    .await
19323                    .unwrap(),
19324                crate::rebase::Rebased::Applied
19325            );
19326            let repo = &runner.state.repo;
19327            let result = git::rev_parse(repo, "HEAD").await.unwrap();
19328            assert_ne!(result, head);
19329            if ignored {
19330                let exclude = git::git(repo, &["rev-parse", "--git-path", "info/exclude"])
19331                    .await
19332                    .unwrap();
19333                std::fs::write(repo.join(exclude), "local-notes\n").unwrap();
19334            }
19335            std::fs::write(repo.join("local-notes"), "retained work\n").unwrap();
19336            assert!(
19337                git::git_raw(repo, &["diff", "--quiet", &head])
19338                    .await
19339                    .unwrap()
19340                    .ok()
19341            );
19342            // Resume after the branch moved, before its checkout was reset.
19343            runner.state = RunState::load(&runner.state.id).unwrap();
19344            runner.sync_to_base().await.unwrap();
19345            assert!(runner.state.base_sync_blocked());
19346            assert!(!runner.state.base_sync_recovery.operations[0].finished);
19347            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19348            assert_eq!(
19349                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19350                result
19351            );
19352            assert_eq!(
19353                std::fs::read_to_string(runner.state.repo.join("local-notes")).unwrap(),
19354                "retained work\n"
19355            );
19356            assert!(
19357                git::git_raw(&runner.state.repo, &["diff", "--quiet", &head])
19358                    .await
19359                    .unwrap()
19360                    .ok()
19361            );
19362        }
19363    }
19364
19365    #[cfg(unix)]
19366    #[tokio::test]
19367    async fn base_recovery_crash_does_not_adopt_foreign_commits() {
19368        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
19369        runner.state.authorize_base_sync(&task).unwrap();
19370        assert!(runner.state.consume_base_recovery(&head));
19371        let tip = runner.state.base_sync.as_ref().unwrap().tip.clone();
19372        runner.state.reserve_base_operation(&head, &tip);
19373        runner.state.save().unwrap();
19374        let scratch = runner.state.dir().join("base-sync");
19375        crate::rebase::rebase_with_fixer(&mut runner.state, &scratch, "fix/retained", &tip)
19376            .await
19377            .unwrap();
19378        git::sync_to_head(&runner.state.repo).await.unwrap();
19379        std::fs::write(runner.state.repo.join("foreign"), "foreign work").unwrap();
19380        git::git(&runner.state.repo, &["add", "foreign"])
19381            .await
19382            .unwrap();
19383        git::git(&runner.state.repo, &["commit", "-m", "foreign work"])
19384            .await
19385            .unwrap();
19386        let foreign_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19387        runner.state = RunState::load(&runner.state.id).unwrap();
19388        runner.sync_to_base().await.unwrap();
19389        assert!(runner.state.base_sync_blocked());
19390        assert!(
19391            !runner
19392                .state
19393                .base_sync_recovery
19394                .operations
19395                .last()
19396                .unwrap()
19397                .finished
19398        );
19399        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
19400        assert_eq!(
19401            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19402            foreign_head
19403        );
19404    }
19405
19406    #[cfg(unix)]
19407    async fn paused_base_conflict_fixture() -> (tempfile::TempDir, Runner, String, String, PathBuf)
19408    {
19409        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
19410        fresh_base_interval_fixture(&mut runner);
19411        let repo = &runner.state.repo;
19412        git::git(repo, &["checkout", "main"]).await.unwrap();
19413        std::fs::write(repo.join("retained"), "upstream change\n").unwrap();
19414        git::git(repo, &["add", "retained"]).await.unwrap();
19415        git::git(repo, &["commit", "-m", "upstream retained change"])
19416            .await
19417            .unwrap();
19418        git::git(repo, &["push", "origin", "main"]).await.unwrap();
19419        let tip = git::rev_parse(repo, "HEAD").await.unwrap();
19420        git::git(repo, &["checkout", "fix/retained"]).await.unwrap();
19421        let scratch = runner.state.dir().join("base-sync");
19422        assert!(matches!(
19423            git::rebase_start(repo, &scratch, "fix/retained", &tip)
19424                .await
19425                .unwrap(),
19426            git::RebaseStart::Conflicted(_)
19427        ));
19428        runner.state.rebase_fixes.push(crate::run::RebaseFixRecord {
19429            unstarted: false,
19430            agent: "fixture".into(),
19431            paths: vec!["retained".into()],
19432            from: Some(head.clone()),
19433            onto: None,
19434            stop: Some(git::rev_parse(&scratch, "REBASE_HEAD").await.unwrap()),
19435            index_outside: None,
19436            finished: false,
19437            error: None,
19438            launcher: None,
19439            infra: None,
19440            outage: None,
19441        });
19442        (tmp, runner, head, tip, scratch)
19443    }
19444
19445    #[cfg(unix)]
19446    #[tokio::test]
19447    async fn base_recovery_imports_legacy_rebase_before_following_new_main() {
19448        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
19449        // A resource stop from before reservations existed, with resolved
19450        // contents left for the launcher's ordinary staging continuation.
19451        std::fs::write(
19452            scratch.join("retained"),
19453            "upstream and retained resolution\n",
19454        )
19455        .unwrap();
19456        runner.state.resource_block = Some(crate::run::ResourceBlock {
19457            node: "rebase".into(),
19458            kind: "repository coordination".into(),
19459            detail: "busy".into(),
19460            at: Timestamp::now(),
19461            cause: crate::run::ResourceBlockCause::Other,
19462        });
19463        runner.state.save().unwrap();
19464        // Advance the remote without moving either checkout participating
19465        // in the standing rebase.
19466        let newer = git::git(
19467            &runner.state.repo,
19468            &[
19469                "commit-tree",
19470                "main^{tree}",
19471                "-p",
19472                "main",
19473                "-m",
19474                "base advanced during wait",
19475            ],
19476        )
19477        .await
19478        .unwrap();
19479        git::git(
19480            &runner.state.repo,
19481            &[
19482                "push",
19483                "origin",
19484                &format!("{}:refs/heads/main", newer.trim()),
19485            ],
19486        )
19487        .await
19488        .unwrap();
19489        runner.state = RunState::load(&runner.state.id).unwrap();
19490        runner.state.resource_block = None;
19491        runner.sync_to_base().await.unwrap();
19492        assert!(!runner.state.base_sync_blocked());
19493        let op = &runner.state.base_sync_recovery.operations[0];
19494        assert_eq!(op.head, head);
19495        assert_eq!(op.tip, tip);
19496        assert!(op.finished);
19497        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
19498        assert_eq!(runner.state.rebase_fixes.len(), 1);
19499        let latest = git::rev_parse(&runner.state.repo, "origin/main")
19500            .await
19501            .unwrap();
19502        assert_ne!(latest, tip);
19503        runner.state = RunState::load(&runner.state.id).unwrap();
19504        runner.sync_to_base().await.unwrap();
19505        assert!(!runner.state.base_sync_blocked());
19506        assert_eq!(runner.state.base_sync_recovery.operations.len(), 2);
19507        assert_eq!(runner.state.base_sync_recovery.operations[1].tip, latest);
19508        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 2);
19509    }
19510
19511    #[cfg(unix)]
19512    #[tokio::test]
19513    async fn base_recovery_resumes_exact_validated_conflict_result_after_crash() {
19514        let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
19515        runner.state.reserve_base_operation(&head, &tip);
19516        runner.state.save().unwrap();
19517        std::fs::write(
19518            scratch.join("retained"),
19519            "upstream and retained resolution\n",
19520        )
19521        .unwrap();
19522        git::git(&scratch, &["add", "retained"]).await.unwrap();
19523        git::git(
19524            &scratch,
19525            &["-c", "core.editor=true", "rebase", "--continue"],
19526        )
19527        .await
19528        .unwrap();
19529        let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
19530        assert!(
19531            !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
19532                .await
19533                .unwrap()
19534                .is_empty()
19535        );
19536        assert_eq!(
19537            crate::rebase::finish(
19538                &mut runner.state,
19539                &scratch,
19540                "fix/retained",
19541                &head,
19542                &tip,
19543                &["retained".into()],
19544                ""
19545            )
19546            .await
19547            .unwrap(),
19548            crate::rebase::Rebased::Applied
19549        );
19550        assert!(!scratch.exists());
19551        // Simulate losing the caller before finish_base_operation/save.
19552        runner.state = RunState::load(&runner.state.id).unwrap();
19553        let op = &runner.state.base_sync_recovery.operations[0];
19554        assert!(!op.finished);
19555        assert_eq!(op.validated_head.as_deref(), Some(result.as_str()));
19556        runner.sync_to_base().await.unwrap();
19557        assert!(!runner.state.base_sync_blocked());
19558        assert!(runner.state.base_sync_recovery.operations[0].finished);
19559        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
19560        assert_eq!(runner.state.rebase_fixes.len(), 1);
19561        let winner = runner.state.winner().unwrap().clone();
19562        let wait = runner.repository_wait();
19563        assert!(
19564            verify_current_head(&mut runner.state, &winner, &wait)
19565                .await
19566                .unwrap()
19567        );
19568        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
19569    }
19570
19571    #[cfg(unix)]
19572    #[tokio::test]
19573    async fn base_recovery_revalidates_completed_scratch_before_validation_save() {
19574        for damage in [None, Some("record"), Some("foreign"), Some("dirty")] {
19575            let (_tmp, mut runner, head, tip, scratch) = paused_base_conflict_fixture().await;
19576            runner.state.reserve_base_operation(&head, &tip);
19577            runner.state.save().unwrap();
19578            std::fs::write(
19579                scratch.join("retained"),
19580                "upstream and retained resolution\n",
19581            )
19582            .unwrap();
19583            git::git(&scratch, &["add", "retained"]).await.unwrap();
19584            git::git(
19585                &scratch,
19586                &["-c", "core.editor=true", "rebase", "--continue"],
19587            )
19588            .await
19589            .unwrap();
19590            let result = git::rev_parse(&scratch, "HEAD").await.unwrap();
19591            assert!(!git::rebase_in_progress(&scratch).await);
19592            assert!(
19593                !crate::reconcile::origin_missing(&runner.state.repo, &result, &head)
19594                    .await
19595                    .unwrap()
19596                    .is_empty()
19597            );
19598            match damage {
19599                Some("record") => {
19600                    let path =
19601                        git::git(&scratch, &["rev-parse", "--git-path", "magi-rebase-heads"])
19602                            .await
19603                            .unwrap();
19604                    std::fs::write(scratch.join(path), "").unwrap();
19605                }
19606                Some("foreign") => {
19607                    std::fs::write(scratch.join("foreign"), "foreign work").unwrap();
19608                    git::git(&scratch, &["add", "foreign"]).await.unwrap();
19609                    git::git(&scratch, &["commit", "-m", "foreign work"])
19610                        .await
19611                        .unwrap();
19612                }
19613                Some("dirty") => {
19614                    std::fs::write(scratch.join("retained"), "uncommitted work").unwrap();
19615                }
19616                _ => {}
19617            }
19618            let retained_head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19619            // Crash immediately after Git continuation, before finish runs.
19620            runner.state = RunState::load(&runner.state.id).unwrap();
19621            assert!(
19622                runner.state.base_sync_recovery.operations[0]
19623                    .validated_head
19624                    .is_none()
19625            );
19626            runner.sync_to_base().await.unwrap();
19627            assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
19628            assert_eq!(runner.state.base_episode_used(), 1);
19629            assert_eq!(runner.state.rebase_fixes.len(), 1);
19630            assert_eq!(
19631                git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
19632                retained_head
19633            );
19634            if damage.is_some() {
19635                assert!(runner.state.base_sync_blocked());
19636                assert!(scratch.exists());
19637                assert!(!runner.state.base_sync_recovery.operations[0].finished);
19638                assert!(
19639                    runner.state.base_sync_recovery.operations[0]
19640                        .validated_head
19641                        .is_none()
19642                );
19643            } else {
19644                assert!(!runner.state.base_sync_blocked());
19645                assert!(!scratch.exists());
19646                assert!(runner.state.base_sync_recovery.operations[0].finished);
19647                assert_eq!(
19648                    runner.state.base_sync_recovery.operations[0]
19649                        .validated_head
19650                        .as_deref(),
19651                    Some(result.as_str())
19652                );
19653                let winner = runner.state.winner().unwrap().clone();
19654                let wait = runner.repository_wait();
19655                assert!(
19656                    verify_current_head(&mut runner.state, &winner, &wait)
19657                        .await
19658                        .unwrap()
19659                );
19660                assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, result);
19661                runner.state = RunState::load(&runner.state.id).unwrap();
19662                runner.sync_to_base().await.unwrap();
19663                assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 1);
19664            }
19665        }
19666    }
19667
19668    #[cfg(unix)]
19669    async fn resumed_gate_fixture() -> (tempfile::TempDir, Runner, String) {
19670        let (tmp, mut runner, head, _) = exhausted_base_fixture().await;
19671        // This is an ordinary gate stop, not an authorized base-budget recovery.
19672        runner.state.prep_complete = Some(true);
19673        runner.state.base_sync = None;
19674        runner.state.base_sync_recovery = Default::default();
19675        runner.state.config.graph.gate_fix_rounds = 1;
19676        let mut review = review_round(true, 0, 1, 1, false, true);
19677        review.head = head.clone();
19678        review.verified_head = Some(head.clone());
19679        runner.state.reviews = vec![review];
19680        runner.state.gate = vec![CommandOutcome {
19681            command: "old gate".into(),
19682            code: Some(1),
19683            output_tail: "old failure".into(),
19684            duration_ms: 0,
19685            resource_blocked: false,
19686            ..Default::default()
19687        }];
19688        runner.state.gate_head = Some(head.clone());
19689        runner.state.gate_ran = true;
19690        runner.state.gate_fixes = vec![crate::run::GateFixRecord {
19691            agent: "fixture".into(),
19692            failed: runner.state.gate.clone(),
19693            notes: "spent".into(),
19694            committed: false,
19695            error: None,
19696        }];
19697        runner.state.land_approval = Some(crate::run::LandApproval {
19698            question: "old approval".into(),
19699            head: head.clone(),
19700        });
19701        runner.state.status = RunStatus::Blocked;
19702        (tmp, runner, head)
19703    }
19704
19705    #[cfg(unix)]
19706    #[tokio::test]
19707    async fn current_head_e2e_keeps_synchronized_base_when_tracking_ref_moves() {
19708        let (_tmp, mut runner, _) = resumed_gate_fixture().await;
19709        runner.sync_to_base().await.unwrap();
19710        let winner = runner.state.winner().unwrap().clone();
19711        let head = git::rev_parse(&winner.worktree, "HEAD").await.unwrap();
19712        let base = runner.state.base_sync.as_ref().unwrap().tip.clone();
19713        assert_ne!(head, base);
19714        runner.state.config.verify.e2e = vec![format!(
19715            "git update-ref refs/remotes/origin/main {head} && false"
19716        )];
19717        let wait = repository_wait(&runner.state, None);
19718        assert!(
19719            !verify_current_head(&mut runner.state, &winner, &wait)
19720                .await
19721                .unwrap()
19722        );
19723        assert_eq!(
19724            git::rev_parse(&runner.state.repo, "refs/remotes/origin/main")
19725                .await
19726                .unwrap(),
19727            head
19728        );
19729        assert_eq!(
19730            runner
19731                .state
19732                .head_e2e
19733                .as_ref()
19734                .unwrap()
19735                .base_commit
19736                .as_deref(),
19737            Some(base.as_str())
19738        );
19739    }
19740
19741    #[cfg(unix)]
19742    #[tokio::test]
19743    async fn resumed_gate_rebase_verifies_new_head_without_refilling_repairs() {
19744        for (e2e_ok, gate_ok) in [(true, true), (true, false), (false, true)] {
19745            let (tmp, mut runner, old) = resumed_gate_fixture().await;
19746            let phases = tmp.path().join("phases");
19747            runner.state.config.verify.e2e = vec![format!(
19748                "echo e2e >> '{}'; {}",
19749                phases.display(),
19750                if e2e_ok {
19751                    "true"
19752                } else {
19753                    "echo new-e2e-failure; false"
19754                }
19755            )];
19756            runner.state.config.verify.gate = vec![format!(
19757                "echo gate >> '{}'; {}",
19758                phases.display(),
19759                if gate_ok {
19760                    "true"
19761                } else {
19762                    "echo new-gate-failure; false"
19763                }
19764            )];
19765            runner.state.save().unwrap();
19766            runner.state = RunState::load(&runner.state.id).unwrap();
19767            runner.sync_to_base().await.unwrap();
19768            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19769            assert_ne!(head, old);
19770            // Reentry after Git updated but before verification was invalidated.
19771            runner.state = RunState::load(&runner.state.id).unwrap();
19772            runner.execute_graph().await.unwrap();
19773            assert_eq!(runner.state.gate_fixes.len(), 1);
19774            assert_eq!(runner.state.reviews.len(), 1);
19775            assert_eq!(runner.state.reviews[0].head, old);
19776            assert_eq!(runner.state.land_approval.as_ref().unwrap().head, old);
19777            assert_eq!(runner.state.verification_history.len(), 1);
19778            let history = &runner.state.verification_history[0];
19779            assert_eq!(history.gate_head.as_deref(), Some(old.as_str()));
19780            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
19781            assert!(history.archived_at.is_some());
19782            assert_eq!(history.fixes_spent, Some(1));
19783            assert_eq!(history.gate[0].output_tail, "old failure");
19784            let archive_events: Vec<_> = runner
19785                .state
19786                .events
19787                .iter()
19788                .filter(|e| e.node == "gate" && e.message.starts_with("archived gate on "))
19789                .collect();
19790            assert_eq!(archive_events.len(), 1);
19791            assert!(archive_events[0].message.contains(&short(&old)));
19792            assert!(archive_events[0].message.contains(&short(&head)));
19793            assert!(
19794                archive_events[0]
19795                    .message
19796                    .contains("1 gate-fix round(s) already spent stay spent")
19797            );
19798            assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, head);
19799            assert_eq!(runner.state.head_e2e.as_ref().unwrap().passed, e2e_ok);
19800            if e2e_ok {
19801                assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
19802                assert_eq!(runner.state.gate_allows_progress(), gate_ok);
19803            } else {
19804                assert!(!runner.state.gate_ran);
19805            }
19806            assert_eq!(
19807                runner.state.status,
19808                if e2e_ok && gate_ok {
19809                    RunStatus::Ready
19810                } else {
19811                    RunStatus::Blocked
19812                }
19813            );
19814            if !e2e_ok || !gate_ok {
19815                let cause = runner.state.verification_blocking_cause().unwrap();
19816                assert!(cause.contains(&head));
19817                assert!(cause.contains(if e2e_ok { "gate failed" } else { "e2e failed" }));
19818                // A later successful progress event must not become the cause.
19819                runner.state.event("land", "rebased successfully");
19820                let notice = crate::notices::run_ended(&runner.state).unwrap();
19821                assert!(!format!("{notice:?}").contains("rebased successfully"));
19822                assert!(runner.state.merge.is_none());
19823            }
19824            let before = std::fs::read_to_string(&phases).unwrap();
19825            runner.state.save().unwrap();
19826            runner.state = RunState::load(&runner.state.id).unwrap();
19827            runner.review_loop().await.unwrap();
19828            runner.gate().await.unwrap();
19829            assert_eq!(std::fs::read_to_string(&phases).unwrap(), before);
19830            assert_eq!(runner.state.verification_history.len(), 1);
19831            let history = &runner.state.verification_history[0];
19832            assert_eq!(history.superseded_by.as_deref(), Some(head.as_str()));
19833            assert!(history.archived_at.is_some());
19834            assert_eq!(history.fixes_spent, Some(1));
19835        }
19836    }
19837
19838    #[cfg(unix)]
19839    #[tokio::test]
19840    async fn resumed_gate_unchanged_head_keeps_failure_and_unknown_head_rechecks() {
19841        let (tmp, mut runner, head) = resumed_gate_fixture().await;
19842        let marker = tmp.path().join("gate-ran");
19843        runner.state.config.verify.gate = vec![format!("touch '{}'", marker.display())];
19844        runner.review_loop().await.unwrap();
19845        runner.gate().await.unwrap();
19846        assert_eq!(runner.state.status, RunStatus::Blocked);
19847        assert!(!marker.exists());
19848        assert!(runner.state.verification_history.is_empty());
19849        runner.state.gate_head = None;
19850        runner.gate().await.unwrap();
19851        assert!(marker.exists());
19852        assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
19853        assert_eq!(runner.state.verification_history.len(), 1);
19854        assert_eq!(runner.state.gate_fixes.len(), 1);
19855    }
19856
19857    #[cfg(unix)]
19858    #[tokio::test]
19859    async fn resumed_gate_pending_e2e_retries_without_spending_or_landing() {
19860        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
19861        runner.sync_to_base().await.unwrap();
19862        let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19863        runner.state.reconcile_verification_head(&head);
19864        // Both crash-before-command and resource wait are unresolved evidence.
19865        for outcomes in [
19866            Vec::new(),
19867            vec![CommandOutcome {
19868                command: "true".into(),
19869                code: None,
19870                output_tail: "cache unavailable".into(),
19871                duration_ms: 0,
19872                resource_blocked: true,
19873                ..Default::default()
19874            }],
19875        ] {
19876            runner.state.head_e2e = Some(crate::run::GateRepairE2e::new(
19877                head.clone(),
19878                false,
19879                outcomes,
19880            ));
19881            runner.state.gate_ran = false;
19882            runner.state.gate.clear();
19883            runner.state.save().unwrap();
19884            runner.state = RunState::load(&runner.state.id).unwrap();
19885            runner.merge().await.unwrap();
19886            assert!(runner.state.merge.is_none());
19887            runner.review_loop().await.unwrap();
19888            runner.gate().await.unwrap();
19889            assert!(runner.state.head_e2e.as_ref().unwrap().passed);
19890            assert!(runner.state.gate_allows_progress());
19891            assert_eq!(runner.state.gate_fixes.len(), 1);
19892            assert!(runner.state.merge.is_none());
19893        }
19894        // Moving the winner after a successful gate cannot publish an unchecked SHA.
19895        git::git(
19896            &runner.state.repo,
19897            &["commit", "--allow-empty", "-m", "external update"],
19898        )
19899        .await
19900        .unwrap();
19901        runner.merge().await.unwrap();
19902        assert!(runner.state.merge.is_none());
19903        assert_eq!(runner.state.status, RunStatus::Blocked);
19904    }
19905
19906    #[cfg(unix)]
19907    #[tokio::test]
19908    async fn resumed_gate_resource_waits_preserve_budget_and_retry_on_reentry() {
19909        for waiting_on_gate in [false, true] {
19910            let (tmp, mut runner, _old) = resumed_gate_fixture().await;
19911            runner.sync_to_base().await.unwrap();
19912            let head = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19913            runner.state.reconcile_verification_head(&head);
19914            if waiting_on_gate {
19915                runner.state.head_e2e = Some(crate::run::GateRepairE2e::new(
19916                    head.clone(),
19917                    true,
19918                    Vec::new(),
19919                ));
19920            }
19921            let cache = tmp.path().join("cache");
19922            runner.state.config.verify.e2e =
19923                vec![format!("CARGO_TARGET_DIR='{}' true", cache.display())];
19924            runner.state.config.verify.gate = vec!["true".into()];
19925            runner.state.config.graph.timeout_resource_wait = 1;
19926            let owner =
19927                crate::cache::Owner::here("other", "e2e", "e2e", &runner.state.repo, "other-head");
19928            let guard =
19929                match crate::cache::try_acquire(&crate::run::home(), &cache, &owner).unwrap() {
19930                    crate::cache::AcquireOutcome::Acquired(g) => g,
19931                    crate::cache::AcquireOutcome::Busy(b) => panic!("unexpected busy cache: {b:?}"),
19932                };
19933            runner.review_loop().await.unwrap();
19934            runner.gate().await.unwrap();
19935            assert!(!runner.state.gate_ran);
19936            assert_eq!(runner.state.gate_fixes.len(), 1);
19937            assert!(runner.state.resource_block.is_some());
19938            runner.merge().await.unwrap();
19939            assert!(runner.state.merge.is_none());
19940            drop(guard);
19941            runner.state = RunState::load(&runner.state.id).unwrap();
19942            // The driver clears the previous pass's resource stop on resume.
19943            runner.state.resource_block = None;
19944            runner.review_loop().await.unwrap();
19945            runner.gate().await.unwrap();
19946            assert!(runner.state.gate_allows_progress());
19947            assert_eq!(runner.state.gate_head.as_deref(), Some(head.as_str()));
19948            assert_eq!(runner.state.gate_fixes.len(), 1);
19949        }
19950    }
19951
19952    #[cfg(unix)]
19953    #[tokio::test]
19954    async fn resumed_gate_pre_gate_head_change_and_review_holds() {
19955        let (_tmp, mut runner, _old) = resumed_gate_fixture().await;
19956        runner.sync_to_base().await.unwrap();
19957        let before = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19958        runner.state.config.verify.pre_gate = vec!["echo mechanical > mechanical".into()];
19959        // Verification passes before pre_gate and fails on the mechanically changed head.
19960        runner.state.config.verify.e2e = vec!["test ! -f mechanical".into()];
19961        runner.review_loop().await.unwrap();
19962        runner.gate().await.unwrap();
19963        let after = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
19964        assert_ne!(before, after);
19965        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, after);
19966        assert!(!runner.state.head_e2e.as_ref().unwrap().passed);
19967        assert!(!runner.state.gate_allows_progress());
19968        runner.merge().await.unwrap();
19969        assert!(runner.state.merge.is_none());
19970        assert!(
19971            runner
19972                .state
19973                .verification_history
19974                .iter()
19975                .any(|h| h.e2e.as_ref().is_some_and(|e| e.head == before && e.passed))
19976        );
19977
19978        // An incomplete review is still an independent hold on a changed head.
19979        runner.state.reviews[0].clean = false;
19980        runner.state.reviews[0].answered = 0;
19981        runner.state.config.verify.e2e = vec!["true".into()];
19982        runner.review_loop().await.unwrap();
19983        runner.gate().await.unwrap();
19984        runner.merge().await.unwrap();
19985        assert_eq!(runner.state.status, RunStatus::Blocked);
19986        assert!(runner.state.merge.is_none());
19987        assert!(
19988            runner
19989                .state
19990                .verification_blocking_cause()
19991                .unwrap()
19992                .contains("review blocked")
19993        );
19994    }
19995
19996    #[cfg(unix)]
19997    #[tokio::test]
19998    async fn resumed_gate_cannot_certify_a_head_changed_by_its_command() {
19999        let (_tmp, mut runner, old) = resumed_gate_fixture().await;
20000        runner.state.gate_head = None;
20001        runner.state.config.verify.gate =
20002            vec!["git -c commit.gpgsign=false commit --allow-empty -m 'gate changed head'".into()];
20003        runner.review_loop().await.unwrap();
20004        runner.gate().await.unwrap();
20005        assert_ne!(
20006            git::rev_parse(&runner.state.repo, "HEAD").await.unwrap(),
20007            old
20008        );
20009        assert_eq!(runner.state.gate_head.as_deref(), Some(old.as_str()));
20010        assert!(!runner.state.gate_allows_progress());
20011        assert_eq!(runner.state.status, RunStatus::Blocked);
20012        runner.merge().await.unwrap();
20013        assert!(runner.state.merge.is_none());
20014    }
20015
20016    #[cfg(unix)]
20017    #[tokio::test]
20018    async fn base_recovery_success_requires_new_review_e2e_and_gate() {
20019        let (_tmp, mut runner, head, task) = exhausted_base_fixture().await;
20020        let mut old_review = review_round(true, 0, 1, 1, false, true);
20021        old_review.head = head.clone();
20022        old_review.verified_head = Some(head.clone());
20023        runner.state.reviews = vec![old_review];
20024        runner.state.gate = vec![CommandOutcome {
20025            command: "old gate".into(),
20026            code: None,
20027            output_tail: "timed out after 2400s".into(),
20028            duration_ms: 2_400_000,
20029            resource_blocked: false,
20030            ..Default::default()
20031        }];
20032        runner.state.gate_ran = true;
20033        runner.state.gate_head = Some(head.clone());
20034        runner.state.land_approval = Some(crate::run::LandApproval {
20035            question: "old-head-approval".into(),
20036            head: head.clone(),
20037        });
20038        runner.state.authorize_base_sync(&task).unwrap();
20039        runner.sync_to_base().await.unwrap();
20040        assert!(!runner.state.base_sync_blocked());
20041        let fresh = git::rev_parse(&runner.state.repo, "HEAD").await.unwrap();
20042        assert_ne!(head, fresh);
20043        assert_eq!(runner.state.reviews.len(), 1);
20044        assert!(!runner.state.gate_ran);
20045        let saved = &runner.state.base_sync_recovery.authorizations[0];
20046        assert_eq!(saved.reviews[0].head, head);
20047        assert_eq!(saved.gate_head.as_deref(), Some(head.as_str()));
20048        assert!(saved.gate_ran);
20049        assert!(!saved.gate[0].ok());
20050        runner.review_loop().await.unwrap();
20051        runner.gate().await.unwrap();
20052        assert_eq!(runner.state.reviews[0].head, head);
20053        assert_eq!(
20054            runner.state.reviews[0].verified_head.as_deref(),
20055            Some(head.as_str())
20056        );
20057        assert_eq!(runner.state.head_e2e.as_ref().unwrap().head, fresh);
20058        assert!(runner.state.head_e2e.as_ref().unwrap().passed);
20059        assert_eq!(runner.state.gate_head.as_deref(), Some(fresh.as_str()));
20060        assert!(runner.state.gate_ran);
20061        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
20062        assert_eq!(runner.state.land_approval.as_ref().unwrap().head, head);
20063        assert_ne!(runner.state.land_approval.as_ref().unwrap().head, fresh);
20064        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 5);
20065        assert_eq!(
20066            std::fs::read_to_string(runner.state.repo.join("retained")).unwrap(),
20067            "retained change"
20068        );
20069    }
20070
20071    #[cfg(unix)]
20072    #[tokio::test]
20073    async fn base_recovery_moving_base_uses_bounded_authorized_interval() {
20074        let (_tmp, mut runner, _head, task) = exhausted_base_fixture().await;
20075        let queue = crate::queue::Queue::open();
20076        let mut owner = queue.get(&task).unwrap();
20077        owner.release_operator("test-resume", None);
20078        queue.put(&mut owner).unwrap();
20079        let generation = owner.resumption.as_ref().unwrap().generation;
20080        runner.state.task_instruction = Some(owner.instruction.clone());
20081        runner.state.driver_exited = true;
20082        runner.state.save().unwrap();
20083        let home = crate::run::home();
20084        let _claim = queue.claim(&task).unwrap();
20085        owner.resumption.as_mut().unwrap().at =
20086            runner.state.base_sync_recovery.stop.as_ref().unwrap().at;
20087        queue.put(&mut owner).unwrap();
20088        assert!(
20089            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20090                .await
20091                .is_err(),
20092            "an approval from before the stop grants nothing"
20093        );
20094        owner.resumption.as_mut().unwrap().at = Timestamp::now();
20095        queue.put(&mut owner).unwrap();
20096        Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20097            .await
20098            .unwrap();
20099        assert!(
20100            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20101                .await
20102                .is_err()
20103        );
20104        runner.state = RunState::load(&runner.state.id).unwrap();
20105        assert_eq!(
20106            runner.state.base_sync_recovery.authorizations[0].generation,
20107            Some(generation)
20108        );
20109        runner.sync_to_base().await.unwrap();
20110        let repo = runner.state.repo.clone();
20111        let head = git::rev_parse(&repo, "HEAD").await.unwrap();
20112        git::git(&repo, &["checkout", "main"]).await.unwrap();
20113        std::fs::write(repo.join("base-change"), "base moved again").unwrap();
20114        git::git(&repo, &["add", "."]).await.unwrap();
20115        git::git(&repo, &["commit", "-m", "move base again"])
20116            .await
20117            .unwrap();
20118        git::git(&repo, &["push", "origin", "main"]).await.unwrap();
20119        git::git(&repo, &["checkout", "fix/retained"])
20120            .await
20121            .unwrap();
20122        runner.sync_to_base().await.unwrap();
20123        assert!(!runner.state.base_sync_blocked());
20124        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
20125        assert_eq!(runner.state.base_episode_used(), 2);
20126        let fresh = git::rev_parse(&repo, "HEAD").await.unwrap();
20127        assert_ne!(fresh, head);
20128        assert!(!runner.state.base_recovery_pending());
20129        // Even replaying the generation with a later timestamp grants nothing.
20130        owner.resumption.as_mut().unwrap().at = Timestamp::now();
20131        queue.put(&mut owner).unwrap();
20132        assert!(
20133            Runner::authorize_base_recovery_from_resumption(&home, &runner.state.id, &task)
20134                .await
20135                .is_err()
20136        );
20137        runner.state = RunState::load(&runner.state.id).unwrap();
20138        runner.sync_to_base().await.unwrap();
20139        assert_eq!(runner.state.base_sync.as_ref().unwrap().attempts, 6);
20140        assert_eq!(runner.state.base_sync_recovery.authorizations.len(), 1);
20141        assert_eq!(git::rev_parse(&repo, "HEAD").await.unwrap(), fresh);
20142    }
20143
20144    #[cfg(unix)]
20145    #[tokio::test]
20146    async fn base_recovery_tally_skips_deliberation_and_voting_without_a_sync_stop() {
20147        let (_tmp, mut runner, _, _) = exhausted_base_fixture().await;
20148        runner.state.base_sync = None;
20149        runner.state.status = RunStatus::Blocked;
20150        let mut second = runner.state.candidates[0].clone();
20151        second.label = 'B';
20152        runner.state.candidates.push(second);
20153        assert!(runner.state.votes.is_empty());
20154        assert!(runner.state.deliberation.is_empty());
20155        runner.deliberate().await.unwrap();
20156        runner.vote().await.unwrap();
20157        assert_eq!(runner.state.status, RunStatus::Blocked);
20158        assert!(runner.state.votes.is_empty());
20159        assert!(runner.state.deliberation.is_empty());
20160    }
20161
20162    /// A minimal, git-free `Runner` at a given status — `settle_questions`
20163    /// reads nothing else off it.
20164    fn runner_at(status: RunStatus) -> Runner {
20165        let mut state = RunState::new(
20166            PathBuf::from("/nonexistent/repo"),
20167            "main".to_owned(),
20168            "deadbeef".to_owned(),
20169            "task".to_owned(),
20170            Config::default(),
20171        );
20172        // These fixtures test execution flow, independent of host disk capacity.
20173        state.config.disk.min_free_bytes = 0;
20174        // These fixtures share one home and save concurrently. Short clock
20175        // IDs can collide, making an ownership test read another test's run.
20176        static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
20177        state.id = format!(
20178            "20000101-000000-{:04x}",
20179            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
20180        );
20181        state.status = status;
20182        Runner {
20183            state,
20184            roles: ResolvedRoles {
20185                implementers: Vec::new(),
20186                judges: Vec::new(),
20187                reviewers: Vec::new(),
20188                fixer: None,
20189                conductor: conductor(),
20190                implementer_roster: Vec::new(),
20191                judge_roster: Vec::new(),
20192                reviewer_roster: Vec::new(),
20193            },
20194            sem: Arc::new(Semaphore::new(1)),
20195            pause: Pause::new(),
20196            interrupt: Pause::new(),
20197        }
20198    }
20199
20200    #[tokio::test]
20201    async fn targeted_fix_refuses_independent_ownership_conflicts() {
20202        crate::run::pin_test_home();
20203        let home = crate::run::home();
20204        let mut runner = runner_at(RunStatus::Ready);
20205        runner.state.driver_exited = true;
20206        runner.state.save().unwrap();
20207        let id = runner.state.id.clone();
20208        let path = runner.state.dir().join("run.json");
20209        let ids = ["R1-1-1".into()];
20210        let lease = crate::driver::maintenance(&home, &id).unwrap();
20211        for (guard, expected) in [
20212            (Some(lease), "currently being worked on"),
20213            (None, "ownership is being updated"),
20214        ] {
20215            let owner = if guard.is_none() {
20216                Some(crate::pr_head::owner_lock(&home, &id).unwrap())
20217            } else {
20218                None
20219            };
20220            let before = std::fs::read(&path).unwrap();
20221            let err = runner
20222                .fix_selected(&ids, "ownership conflict", false)
20223                .await
20224                .unwrap_err();
20225            assert!(format!("{err:#}").contains(expected), "{err:#}");
20226            assert_eq!(std::fs::read(&path).unwrap(), before);
20227            assert!(!runner.state.dir().join("fix.lock").exists());
20228            drop(owner);
20229            drop(guard);
20230        }
20231        let mut disk = RunState::load(&id).unwrap();
20232        disk.driver_exited = false;
20233        disk.driver_pid = Some(std::process::id());
20234        disk.driver_started_at = Some(crate::proc::process_started_at(std::process::id()).unwrap());
20235        disk.save().unwrap();
20236        assert_eq!(
20237            disk.liveness_under(&home, false),
20238            crate::run::Liveness::Live
20239        );
20240        let before = std::fs::read(&path).unwrap();
20241        let err = runner
20242            .fix_selected(&ids, "live driver", false)
20243            .await
20244            .unwrap_err();
20245        assert!(
20246            err.to_string().contains("currently being worked on"),
20247            "{err:#}"
20248        );
20249        assert_eq!(std::fs::read(&path).unwrap(), before);
20250        assert!(!runner.state.dir().join("fix.lock").exists());
20251        disk.driver_exited = true;
20252        disk.driver_pid = None;
20253        disk.driver_started_at = None;
20254        disk.status = RunStatus::Reviewing;
20255        disk.save().unwrap();
20256        let before = std::fs::read(&path).unwrap();
20257        let err = runner
20258            .fix_selected(&ids, "stale state", false)
20259            .await
20260            .unwrap_err();
20261        assert!(
20262            err.to_string().contains("run changed since it was loaded"),
20263            "{err:#}"
20264        );
20265        assert_eq!(std::fs::read(&path).unwrap(), before);
20266        assert!(!runner.state.dir().join("fix.lock").exists());
20267        assert!(runner.state.operator_fixes.is_empty());
20268    }
20269
20270    #[tokio::test]
20271    async fn targeted_fix_preflight_releases_owner_and_cancellation_releases_claims() {
20272        use std::future::Future;
20273        use std::task::Poll;
20274
20275        crate::run::pin_test_home();
20276        let home = crate::run::home();
20277        let repo = tempfile::tempdir().unwrap();
20278        let mut runner = runner_at(RunStatus::Ready);
20279        runner.state.repo = repo.path().to_path_buf();
20280        runner.state.driver_exited = true;
20281        runner.state.candidates.push(Candidate {
20282            index: 0,
20283            label: 'A',
20284            agent: "mock".into(),
20285            branch: "magi/test/A".into(),
20286            worktree: repo.path().join("wt"),
20287            summary: String::new(),
20288            stat: String::new(),
20289            files: 0,
20290            commits: 0,
20291            empty: false,
20292            failed: None,
20293            verified_noop: None,
20294            duration_ms: 0,
20295            folded: false,
20296        });
20297        runner.state.tally = Some(Tally {
20298            first_choice: BTreeMap::from([('A', 1)]),
20299            borda: BTreeMap::new(),
20300            winner: 'A',
20301            rankings: 1,
20302            unanimous_initial: true,
20303            deliberated: false,
20304            changed_votes: 0,
20305            unanimous_final: true,
20306            tie_break: None,
20307            judges: 1,
20308            present: 1,
20309            quorum: 1,
20310            met_quorum: true,
20311            uncontested: None,
20312        });
20313        runner.state.save().unwrap();
20314        let id = runner.state.id.clone();
20315        let dir = runner.state.dir();
20316        let before = std::fs::read(dir.join("run.json")).unwrap();
20317        let ids = ["R1-1-1".into()];
20318        let mut fix = Box::pin(runner.fix_selected(&ids, "preflight lock check", false));
20319        std::future::poll_fn(|cx| match fix.as_mut().poll(cx) {
20320            Poll::Pending => Poll::Ready(()),
20321            Poll::Ready(result) => panic!("preflight completed without yielding: {result:?}"),
20322        })
20323        .await;
20324        assert!(FixClaim::acquire(&dir).is_err());
20325        assert!(crate::driver::maintenance(&home, &id).is_err());
20326        drop(crate::pr_head::owner_lock(&home, &id).unwrap());
20327        drop(fix);
20328        assert!(FixClaim::acquire(&dir).is_ok());
20329        assert!(crate::driver::maintenance(&home, &id).is_ok());
20330        assert_eq!(std::fs::read(dir.join("run.json")).unwrap(), before);
20331    }
20332
20333    #[tokio::test]
20334    async fn source_eviction_resume_restores_before_graph_shortcuts_and_setup() {
20335        crate::run::pin_test_home();
20336        let temp = tempfile::tempdir().unwrap();
20337        let root = temp.path().canonicalize().unwrap();
20338        let repo = root.join("repo");
20339        std::fs::create_dir(&repo).unwrap();
20340        init_repo(&repo);
20341        git::git(&repo, &["config", "core.autocrlf", "false"])
20342            .await
20343            .unwrap();
20344        let mut runner = runner_at(RunStatus::Blocked);
20345        runner.state.repo = repo.clone();
20346        runner.state.base_commit = git::rev_parse(&repo, "HEAD").await.unwrap();
20347        runner.state.config.agents = vec![conductor()];
20348        runner.state.config.graph.selected_implementer = Some("conductor".into());
20349        runner.state.config.graph.worktree_root = Some(root.join("worktrees"));
20350        let (shell, command, setup_output) = if cfg!(windows) {
20351            (
20352                vec!["cmd".into(), "/C".into()],
20353                "echo ready>seat-ready",
20354                "ready\r\n",
20355            )
20356        } else {
20357            (
20358                vec!["sh".into(), "-c".into()],
20359                "printf ready > seat-ready",
20360                "ready",
20361            )
20362        };
20363        runner.state.config.verify.shell = Some(shell);
20364        runner.state.config.worktree.setup = vec![crate::config::SetupStep {
20365            run: Some(command.into()),
20366            ..Default::default()
20367        }];
20368        runner.state.save().unwrap();
20369        let path = runner.state.worktree_root().join("judge-1");
20370        git::worktree_add_detached(&repo, &path, &runner.state.base_commit)
20371            .await
20372            .unwrap();
20373        std::fs::write(path.join("checkpoint"), "unrelated seat").unwrap();
20374        git::git(&path, &["add", "."]).await.unwrap();
20375        let tree = git::git(&path, &["write-tree"]).await.unwrap();
20376        let head = git::git(&path, &["commit-tree", &tree, "-m", "seat checkpoint"])
20377            .await
20378            .unwrap();
20379        git::git(&path, &["checkout", "--detach", &head])
20380            .await
20381            .unwrap();
20382        let evidence = crate::fold_evidence::snapshot(
20383            &runner.state,
20384            &crate::run::home().canonicalize().unwrap(),
20385            &head,
20386            64 * 1024 * 1024,
20387        )
20388        .await
20389        .unwrap();
20390        let mut contents = BTreeMap::new();
20391        contents.insert(
20392            repo.join("logs/HEAD"),
20393            format!("{head} {head} fixture\n").into_bytes(),
20394        );
20395        let record = serde_json::json!({
20396            "version":1, "run":runner.state.id, "source":path, "head":head,
20397            "evidence":evidence, "admin":{}, "admin_contents":contents,
20398            "history":{head.clone():evidence}, "phase":"evicted"
20399        });
20400        std::fs::write(
20401            runner.state.dir().join("artifacts/eviction-judge-1.json"),
20402            serde_json::to_vec(&record).unwrap(),
20403        )
20404        .unwrap();
20405        assert!(git::worktree_remove_clean(&repo, &path).await.unwrap());
20406        git::git(&repo, &["reflog", "expire", "--expire=now", "--all"])
20407            .await
20408            .unwrap();
20409        git::git(&repo, &["gc", "--prune=now"]).await.unwrap();
20410        assert!(
20411            !git::git_raw(&repo, &["cat-file", "-e", &head])
20412                .await
20413                .unwrap()
20414                .ok()
20415        );
20416        let mut resumed = Runner::resume(&runner.state.id).unwrap();
20417        let error = resumed.execute().await.unwrap_err();
20418        assert!(
20419            error
20420                .to_string()
20421                .contains("selected implementation is held"),
20422            "{error:#}"
20423        );
20424        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), head);
20425        assert_eq!(
20426            std::fs::read_to_string(path.join("seat-ready")).unwrap(),
20427            setup_output
20428        );
20429        assert_eq!(
20430            std::fs::read_to_string(path.join("checkpoint")).unwrap(),
20431            "unrelated seat"
20432        );
20433        let error = resumed.execute().await.unwrap_err();
20434        assert!(
20435            error
20436                .to_string()
20437                .contains("selected implementation is held"),
20438            "{error:#}"
20439        );
20440        std::fs::write(path.join("checkpoint"), "next recorded review").unwrap();
20441        git::git(&path, &["add", "."]).await.unwrap();
20442        let next_tree = git::git(&path, &["write-tree"]).await.unwrap();
20443        let next = git::git(
20444            &path,
20445            &[
20446                "commit-tree",
20447                &next_tree,
20448                "-p",
20449                &head,
20450                "-m",
20451                "next review checkpoint",
20452            ],
20453        )
20454        .await
20455        .unwrap();
20456        git::git(&path, &["checkout", "--detach", &next])
20457            .await
20458            .unwrap();
20459        resumed.state.reviews.push(
20460            serde_json::from_value(serde_json::json!({
20461                "round":1, "head":next, "reviews":[]
20462            }))
20463            .unwrap(),
20464        );
20465        resumed.state.save().unwrap();
20466        let error = resumed.execute().await.unwrap_err();
20467        assert!(
20468            error
20469                .to_string()
20470                .contains("selected implementation is held"),
20471            "{error:#}"
20472        );
20473        assert_eq!(git::rev_parse(&path, "HEAD").await.unwrap(), next);
20474    }
20475
20476    #[tokio::test]
20477    async fn driver_claim_waits_for_maintenance_before_starting_a_pass() {
20478        crate::run::pin_test_home();
20479        let mut runner = runner_at(RunStatus::Gating);
20480        runner.state.save().unwrap();
20481        let id = runner.state.id.clone();
20482        let passes = runner.state.passes.len();
20483        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
20484        let mut claiming = Box::pin(runner.claim_driver(None));
20485        std::future::poll_fn(|cx| {
20486            assert!(std::future::Future::poll(claiming.as_mut(), cx).is_pending());
20487            std::task::Poll::Ready(())
20488        })
20489        .await;
20490        assert_eq!(RunState::load(&id).unwrap().passes.len(), passes);
20491        drop(owner);
20492        let execution = tokio::time::timeout(Duration::from_secs(2), claiming)
20493            .await
20494            .unwrap()
20495            .unwrap();
20496        assert_eq!(execution.runner.state.passes.len(), passes + 1);
20497        assert!(execution.runner.state.resource_block.is_none());
20498        assert_eq!(
20499            execution.runner.state.liveness(false),
20500            crate::run::Liveness::Live
20501        );
20502        drop(execution);
20503        assert!(RunState::load(&id).unwrap().driver_exited);
20504    }
20505
20506    #[tokio::test]
20507    async fn a_failed_driver_lease_record_releases_the_claim_and_retained_state() {
20508        crate::run::pin_test_home();
20509        let mut runner = runner_at(RunStatus::Gating);
20510        runner.state.save().unwrap();
20511        // run.json can commit, but the subsequent lease metadata write fails.
20512        // Cleanup must run after releasing the short ownership lock.
20513        std::fs::create_dir(runner.state.dir().join("driver.json.tmp")).unwrap();
20514        assert!(runner.claim_driver(None).await.is_err());
20515        assert!(runner.state.driver_exited);
20516        assert_eq!(runner.state.driver_pid, None);
20517        let disk = RunState::load(&runner.state.id).unwrap();
20518        assert!(disk.driver_exited);
20519        assert_eq!(disk.driver_pid, None);
20520        assert_eq!(disk.status, RunStatus::Gating);
20521    }
20522
20523    #[tokio::test]
20524    async fn an_early_graph_error_releases_its_driver() {
20525        crate::run::pin_test_home();
20526        let mut runner = runner_at(RunStatus::Blocked);
20527        runner.state.config.graph.selected_implementer = Some("selected".into());
20528        runner.state.save().unwrap();
20529        assert!(runner.execute().await.is_err());
20530        let disk = RunState::load(&runner.state.id).unwrap();
20531        assert!(disk.driver_exited);
20532        assert_eq!(disk.driver_pid, None);
20533        assert_eq!(disk.status, RunStatus::Blocked);
20534    }
20535
20536    fn merge_repair_request(phase: crate::run::MergeRepairPhase) -> crate::run::MergeRepair {
20537        crate::run::MergeRepair {
20538            question: "repair-question".into(),
20539            head: "old-head".into(),
20540            pr: "https://github.com/o/r/pull/42".into(),
20541            reviews: vec![review_round(false, 1, 1, 1, false, true)],
20542            gate: vec![outcome(Some(0), false)],
20543            gate_head: Some("old-head".into()),
20544            gate_fixes: Vec::new(),
20545            pre_gate: Vec::new(),
20546            phase,
20547            failure: None,
20548        }
20549    }
20550
20551    #[tokio::test]
20552    async fn merge_repair_claim_refuses_concurrent_and_obsolete_drivers() {
20553        crate::run::pin_test_home();
20554        let mut runner = runner_at(RunStatus::Landing);
20555        runner.state.merge_repairs.push(merge_repair_request(
20556            crate::run::MergeRepairPhase::Requested,
20557        ));
20558        runner.state.save().unwrap();
20559        let claim = FixClaim::acquire(&runner.state.dir()).unwrap();
20560        assert!(
20561            runner
20562                .execute()
20563                .await
20564                .unwrap_err()
20565                .to_string()
20566                .contains("already running")
20567        );
20568        assert_eq!(
20569            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
20570            crate::run::MergeRepairPhase::Requested
20571        );
20572        drop(claim);
20573        let mut disk = runner.state.clone();
20574        disk.merge_repairs[0].phase = crate::run::MergeRepairPhase::Complete;
20575        disk.save().unwrap();
20576        assert!(
20577            runner
20578                .execute()
20579                .await
20580                .unwrap_err()
20581                .to_string()
20582                .contains("decision changed")
20583        );
20584        assert_eq!(
20585            RunState::load(&runner.state.id).unwrap().merge_repairs[0].phase,
20586            crate::run::MergeRepairPhase::Complete
20587        );
20588    }
20589
20590    #[test]
20591    fn merge_repair_starts_a_real_new_budget_and_preserves_old_evidence() {
20592        crate::run::pin_test_home();
20593        let mut runner = runner_at(RunStatus::Landing);
20594        let request = merge_repair_request(crate::run::MergeRepairPhase::Fixing);
20595        runner.state.reviews = request.reviews.clone();
20596        runner.state.gate = request.gate.clone();
20597        runner.state.gate_ran = true;
20598        runner.state.land_approval = Some(crate::run::LandApproval {
20599            question: "old".into(),
20600            head: "old-head".into(),
20601        });
20602        runner.state.merge_repairs.push(request);
20603        runner.begin_merge_repair_review(0).unwrap();
20604        assert_eq!(review_conclusion(&runner.state.reviews, 2), None);
20605        assert!(!runner.state.gate_status().ok());
20606        assert!(runner.state.land_approval.is_none());
20607        let disk = RunState::load(&runner.state.id).unwrap();
20608        assert_eq!(disk.merge_repairs[0].reviews[0].blocking, 1);
20609        assert!(disk.merge_repairs[0].gate[0].ok());
20610        assert_eq!(
20611            disk.merge_repairs[0].phase,
20612            crate::run::MergeRepairPhase::Reviewing
20613        );
20614        assert_eq!(disk.merge_repairs[0].pr, "https://github.com/o/r/pull/42");
20615        assert!(disk.reviews.is_empty());
20616    }
20617
20618    #[tokio::test]
20619    async fn merge_repair_interrupted_fixer_and_exhausted_generation_hold_without_repeating_work() {
20620        crate::run::pin_test_home();
20621        for phase in [
20622            crate::run::MergeRepairPhase::Fixing,
20623            crate::run::MergeRepairPhase::Requested,
20624        ] {
20625            let mut runner = runner_at(RunStatus::Landing);
20626            runner.state.config.graph.land_rounds = 0;
20627            runner.state.merge_repairs.push(merge_repair_request(phase));
20628            runner.state.save().unwrap();
20629            assert!(!runner.repair_merge_review().await.unwrap());
20630            assert_eq!(runner.state.status, RunStatus::Blocked);
20631            assert_eq!(
20632                runner.state.merge_repairs[0].phase,
20633                crate::run::MergeRepairPhase::Failed
20634            );
20635            let reason = runner.state.merge_repairs[0].failure.as_ref().unwrap();
20636            assert!(
20637                reason.contains(if phase == crate::run::MergeRepairPhase::Fixing {
20638                    "interrupted"
20639                } else {
20640                    "budget exhausted"
20641                })
20642            );
20643            assert!(runner.state.merge.is_none());
20644        }
20645    }
20646
20647    /// `park_here` folding in the reason `Pause::park_because` recorded -
20648    /// this is what lets an operator reading a run's events tell an
20649    /// interrupt-driven park from an ordinary shutdown park.
20650    #[test]
20651    fn park_here_folds_the_interrupt_reason_into_the_park_event() {
20652        crate::run::pin_test_home();
20653        let mut runner = runner_at(RunStatus::Implementing);
20654        let interrupt = Pause::new();
20655        runner.watch_interrupt(interrupt.clone());
20656
20657        interrupt.park_because("task a1b2 asked to run first");
20658
20659        assert!(runner.park_here().expect("park_here"));
20660        assert!(runner.state.parked);
20661        let last = runner.state.events.last().expect("a park event");
20662        assert_eq!(last.node, "park");
20663        assert!(
20664            last.message.contains("task a1b2 asked to run first"),
20665            "expected the interrupt reason in {:?}",
20666            last.message
20667        );
20668    }
20669
20670    /// The cause is stored on the pass when it parks, and the first cause a
20671    /// shared pause was given is the one that stays.
20672    #[test]
20673    fn park_here_records_the_structured_cause_and_the_first_one_wins() {
20674        crate::run::pin_test_home();
20675        let mut runner = runner_at(RunStatus::Implementing);
20676        runner.state.begin_pass();
20677        let shutdown = Pause::new();
20678        runner.on_pause(shutdown.clone());
20679        let upgrade = ParkCause::Upgrade {
20680            from: "0.121.0".to_owned(),
20681            to: Some("0.121.1".to_owned()),
20682        };
20683        shutdown.park_for(upgrade.clone());
20684        shutdown.park_for(ParkCause::Operator);
20685
20686        assert!(runner.park_here().expect("park_here"));
20687        assert_eq!(
20688            runner.state.passes[0].end,
20689            Some(crate::run::PassEnd::Parked { cause: upgrade })
20690        );
20691        let last = runner.state.events.last().expect("a park event");
20692        assert!(last.message.contains("0.121.0"), "{}", last.message);
20693    }
20694
20695    #[tokio::test]
20696    async fn driver_admission_accepts_a_freshly_minted_record_under_its_lease() {
20697        crate::run::pin_test_home();
20698        let mut runner = runner_at(RunStatus::Reviewing);
20699        runner.state.save().unwrap();
20700        let mut execution = runner.claim_driver(None).await.expect("first execution");
20701        assert_eq!(execution.runner.state.passes.len(), 1);
20702        execution
20703            .driver
20704            .finish(&mut execution.runner.state)
20705            .await
20706            .unwrap();
20707    }
20708
20709    #[tokio::test]
20710    async fn driver_admission_resumes_a_record_saved_before_its_first_claim() {
20711        crate::run::pin_test_home();
20712        let mut runner = runner_at(RunStatus::Reviewing);
20713        runner.state.config.agents = vec![conductor()];
20714        runner.state.config.graph.timeout_resource_wait = 0;
20715        runner.state.save().unwrap();
20716        let id = runner.state.id.clone();
20717        let owner = crate::pr_head::owner_lock(&crate::run::home(), &id).unwrap();
20718        assert!(runner.claim_driver(None).await.is_err());
20719        drop(owner);
20720        drop(runner);
20721        let mut resumed = Runner::resume(&id).unwrap();
20722        assert_eq!(resumed.state.driver_claimed, Some(false));
20723        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Dead);
20724        assert_eq!(resumed.state.liveness(true), crate::run::Liveness::Live);
20725        let mut execution = resumed
20726            .claim_driver(None)
20727            .await
20728            .expect("retry initial claim after reload");
20729        assert_eq!(execution.runner.state.driver_claimed, Some(true));
20730        assert_eq!(execution.runner.state.passes.len(), 1);
20731        execution
20732            .driver
20733            .finish(&mut execution.runner.state)
20734            .await
20735            .unwrap();
20736    }
20737
20738    #[tokio::test]
20739    async fn driver_admission_preclaim_marker_does_not_bypass_an_execution_lease() {
20740        crate::run::pin_test_home();
20741        let mut runner = runner_at(RunStatus::Reviewing);
20742        runner.state.config.agents = vec![conductor()];
20743        runner.state.save().unwrap();
20744        let id = runner.state.id.clone();
20745        let lease = crate::driver::maintenance(&crate::run::home(), &id).unwrap();
20746        let mut resumed = Runner::resume(&id).unwrap();
20747        assert_eq!(resumed.state.liveness(false), crate::run::Liveness::Live);
20748        assert!(resumed.claim_driver(None).await.is_err());
20749        assert!(RunState::load(&id).unwrap().passes.is_empty());
20750        drop(lease);
20751        let mut execution = resumed.claim_driver(None).await.unwrap();
20752        execution
20753            .driver
20754            .finish(&mut execution.runner.state)
20755            .await
20756            .unwrap();
20757    }
20758
20759    #[tokio::test]
20760    async fn driver_admission_accepts_legacy_unknown_process_with_a_proven_free_pass_lease() {
20761        crate::run::pin_test_home();
20762        let mut runner = runner_at(RunStatus::Reviewing);
20763        let state = &mut runner.state;
20764        state.config.agents = vec![conductor()];
20765        state.driver_claimed = None;
20766        state.driver_pid = Some(std::process::id());
20767        state.driver_started_at = None;
20768        state.begin_pass();
20769        state.save().unwrap();
20770        let lease = crate::driver::maintenance(&crate::run::home(), &state.id).unwrap();
20771        std::fs::write(
20772            state.dir().join("driver.json"),
20773            serde_json::to_vec(&serde_json::json!({
20774                "pid": state.driver_pid, "started_at": null,
20775                "pass": state.passes[0].started_at, "pass_index": state.passes[0].index,
20776            }))
20777            .unwrap(),
20778        )
20779        .unwrap();
20780        assert_eq!(state.liveness(false), crate::run::Liveness::Live);
20781        drop(lease);
20782        assert_eq!(state.liveness(false), crate::run::Liveness::Dead);
20783        let mut resumed = Runner::resume(&state.id).unwrap();
20784        assert!(!resumed.state.driver_exited);
20785        let mut execution = resumed
20786            .claim_driver(None)
20787            .await
20788            .expect("lease proves previous execution ended");
20789        assert_eq!(execution.runner.state.passes.len(), 2);
20790        execution
20791            .driver
20792            .finish(&mut execution.runner.state)
20793            .await
20794            .unwrap();
20795    }
20796
20797    #[tokio::test]
20798    async fn driver_admission_admits_a_legacy_record_without_a_claim_marker() {
20799        crate::run::pin_test_home();
20800        let mut runner = runner_at(RunStatus::Reviewing);
20801        let mut json = serde_json::to_value(&runner.state).unwrap();
20802        json.as_object_mut().unwrap().remove("driver_claimed");
20803        runner.state = serde_json::from_value(json).unwrap();
20804        assert_eq!(runner.state.driver_claimed, None);
20805        runner.state.save().unwrap();
20806        let mut execution = runner
20807            .claim_driver(None)
20808            .await
20809            .expect("the execution lease, not a missing marker, excludes a second driver");
20810        assert_eq!(execution.runner.state.passes.len(), 1);
20811        execution
20812            .driver
20813            .finish(&mut execution.runner.state)
20814            .await
20815            .unwrap();
20816    }
20817
20818    #[tokio::test]
20819    async fn driver_admission_refuses_a_proven_live_driver() {
20820        crate::run::pin_test_home();
20821        let mut runner = runner_at(RunStatus::Reviewing);
20822        let pid = std::process::id();
20823        runner.state.driver_pid = Some(pid);
20824        runner.state.driver_started_at = crate::proc::process_started_at(pid);
20825        assert!(runner.state.driver_started_at.is_some());
20826        runner.state.save().unwrap();
20827        let error = runner
20828            .claim_driver(None)
20829            .await
20830            .err()
20831            .expect("a live driver must refuse");
20832        let message = error.to_string();
20833        assert!(
20834            message.starts_with("run already has a live driver: "),
20835            "{message}"
20836        );
20837        assert!(message.contains(&format!("pid={pid}")), "{message}");
20838        assert!(
20839            message.contains(runner.state.driver_started_at.as_deref().unwrap()),
20840            "{message}"
20841        );
20842        let saved = RunState::load(&runner.state.id).unwrap();
20843        assert_eq!(saved.driver_pid, Some(pid));
20844        assert_eq!(saved.status, RunStatus::Reviewing);
20845        assert!(saved.passes.is_empty());
20846    }
20847
20848    #[tokio::test]
20849    async fn driver_admission_refuses_another_worker_claim_with_shared_format() {
20850        crate::run::pin_test_home();
20851        let home = crate::run::home();
20852        let mut runner = runner_at(RunStatus::Reviewing);
20853        runner.state.driver_exited = true;
20854        runner.state.driver_pid = None;
20855        runner.state.driver_started_at = None;
20856        runner.state.save().unwrap();
20857
20858        let queue = crate::queue::Queue::at(home.join("queue"));
20859        let mut task = crate::queue::Task::new(
20860            "task".into(),
20861            "task".into(),
20862            runner.state.repo.clone(),
20863            crate::queue::Source::Human,
20864        );
20865        task.runs.push(runner.state.id.clone());
20866        queue.put(&mut task).unwrap();
20867        let payload = serde_json::json!({
20868            "queue": home.join("queue"),
20869            "task": task.id,
20870            "opts": crate::daemon::Opts::default(),
20871            "standalone": false,
20872        });
20873        let (job, lease) =
20874            crate::worker::running_fixture(&home, &format!("task:{}", task.id), payload).unwrap();
20875
20876        let error = runner
20877            .claim_driver(None)
20878            .await
20879            .err()
20880            .expect("another active worker claim must refuse");
20881        let message = error.to_string();
20882        assert!(
20883            message.starts_with("run already has a live driver: worker claim"),
20884            "{message}"
20885        );
20886        assert!(message.contains(&job.id), "{message}");
20887        assert!(message.contains("status=running"), "{message}");
20888        assert!(message.contains("live.lock held"), "{message}");
20889
20890        drop(lease);
20891        let _ = std::fs::remove_dir_all(home.join("workers").join("jobs").join(&job.id));
20892    }
20893
20894    #[test]
20895    fn parking_resource_halt_persists_the_pass_once() {
20896        crate::run::pin_test_home();
20897        let mut runner = runner_at(RunStatus::Reviewing);
20898        runner.state.begin_pass();
20899        runner.state.resource_block = Some(crate::run::ResourceBlock {
20900            node: "fix".into(),
20901            kind: "shared build cache".into(),
20902            detail: "cancelled".into(),
20903            at: Timestamp::now(),
20904            cause: crate::run::ResourceBlockCause::Cancelled { park: None },
20905        });
20906        let cause = ParkCause::Upgrade {
20907            from: "old".into(),
20908            to: Some("new".into()),
20909        };
20910        runner.pause.park_for(cause.clone());
20911        // Both direct fixer exits and graph resource boundaries must complete
20912        // parking, rather than returning a stale Reviewing record.
20913        runner.stop_for_resource().unwrap();
20914        assert!(runner.resource_halt().unwrap());
20915        assert!(runner.park_here().unwrap());
20916        let saved = RunState::load(&runner.state.id).unwrap();
20917        assert!(saved.parked);
20918        assert_eq!(saved.status, RunStatus::Reviewing);
20919        assert!(saved.passes[0].ended_at.is_some());
20920        assert_eq!(
20921            saved.passes[0].end,
20922            Some(crate::run::PassEnd::Parked {
20923                cause: cause.clone()
20924            })
20925        );
20926        assert_eq!(
20927            saved.resource_block.unwrap().cause,
20928            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
20929        );
20930        assert_eq!(
20931            saved
20932                .events
20933                .iter()
20934                .filter(|event| event.node == "park")
20935                .count(),
20936            1
20937        );
20938    }
20939
20940    /// `watch_interrupt` and `on_pause` are genuinely independent: an ordinary
20941    /// shutdown `Pause` (what `Stop::park` hands every run, shared and never
20942    /// cleared) must not make a *different* run - one only watching its own,
20943    /// unshared interrupt `Pause` - see itself as parked. If a future change
20944    /// ever collapsed these back into one handle, the interrupt scheduler
20945    /// would park every run for the rest of the daemon's life, not just the
20946    /// one it meant to interrupt.
20947    #[test]
20948    fn the_stop_level_pause_and_a_runs_interrupt_pause_do_not_leak_into_each_other() {
20949        crate::run::pin_test_home();
20950        let mut runner = runner_at(RunStatus::Implementing);
20951        let shutdown = Pause::new();
20952        runner.on_pause(shutdown.clone());
20953        let interrupt = Pause::new();
20954        runner.watch_interrupt(interrupt.clone());
20955
20956        // Nobody has asked for anything yet.
20957        assert!(!runner.park_here().expect("park_here"));
20958        assert!(!runner.state.parked);
20959
20960        // Only the interrupt handle fires; the shutdown handle stays clear.
20961        interrupt.park_because("test");
20962        assert!(!shutdown.parked());
20963        assert!(runner.park_here().expect("park_here"));
20964    }
20965
20966    /// The property every prior attempt at this feature failed to pin down:
20967    /// asking a run to park while one of its nodes has a real, in-flight
20968    /// async operation running (an agent call, in production) must not cut
20969    /// that operation short. `park_here` is only ever consulted *between*
20970    /// `execute`'s node calls - see its own doc - so nothing inside a node
20971    /// can observe a park request until the node itself returns. This proves
20972    /// that structurally, with real `tokio` concurrency and a channel
20973    /// handshake (never a sleep, which would only prove "usually", not
20974    /// "cannot"): the "node" below reports that it has genuinely started,
20975    /// and only then is the park requested; the node still has to be told to
20976    /// finish before `park_here` is ever called, exactly mirroring every
20977    /// `self.some_node().await; if self.park_here()? { return Ok(()); }` pair
20978    /// in `execute`.
20979    #[tokio::test]
20980    async fn a_park_request_made_mid_node_only_takes_effect_at_the_next_boundary() {
20981        crate::run::pin_test_home();
20982        let mut runner = runner_at(RunStatus::Implementing);
20983        let interrupt = Pause::new();
20984        runner.watch_interrupt(interrupt.clone());
20985
20986        let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>();
20987        let (finish_tx, finish_rx) = tokio::sync::oneshot::channel::<()>();
20988
20989        // Stands in for one node's in-flight agent call: it proves it has
20990        // genuinely started, then blocks - exactly as a spawned CLI process
20991        // does - until told to finish.
20992        let node = async move {
20993            started_tx.send(()).expect("send started");
20994            finish_rx.await.expect("recv finish");
20995            "node finished"
20996        };
20997
20998        let interrupter = async move {
20999            started_rx.await.expect("recv started");
21000            // The call is now genuinely in flight. Ask it to park.
21001            interrupt.park_because("higher-priority task waiting");
21002            // Nothing the node does can observe this yet - there is no
21003            // check inside it, by construction - so let the executor run
21004            // anything pending and then let the node finish on its own.
21005            tokio::task::yield_now().await;
21006            finish_tx.send(()).expect("send finish");
21007        };
21008
21009        let (node_result, ()) = tokio::join!(node, interrupter);
21010        assert_eq!(
21011            node_result, "node finished",
21012            "the in-flight call ran to completion"
21013        );
21014
21015        // Only now, at the boundary the real `execute` would check right
21016        // after this node, does the park take effect.
21017        assert!(runner.park_here().expect("park_here"));
21018        assert!(runner.state.parked);
21019    }
21020
21021    /// A run parked mid-competition carries every field it had accumulated
21022    /// through the exact same disk round-trip an ordinary resume uses -
21023    /// `RunState::save`/`RunState::load`, which is all `Runner::resume` is.
21024    /// Nothing about parking for an interrupt is a special case of that path;
21025    /// this is what proves it rather than assuming it.
21026    #[test]
21027    fn a_run_parked_for_an_interrupt_resumes_with_nothing_lost() {
21028        crate::run::pin_test_home();
21029        let mut runner = runner_at(RunStatus::Judging);
21030        // `Runner::resume` re-resolves roles from the saved config, which
21031        // refuses an empty roster - give it the same minimal one `conductor`
21032        // itself uses.
21033        runner.state.config.agents = vec![conductor()];
21034        runner.state.candidates = vec![Candidate {
21035            index: 0,
21036            label: 'A',
21037            agent: "alpha".to_owned(),
21038            branch: "magi/x/A".to_owned(),
21039            worktree: PathBuf::from("/nonexistent/worktree"),
21040            summary: "did the thing".to_owned(),
21041            stat: "1 file changed".to_owned(),
21042            files: 1,
21043            commits: 1,
21044            empty: false,
21045            failed: None,
21046            verified_noop: None,
21047            duration_ms: 1234,
21048            folded: false,
21049        }];
21050        let run_id = runner.state.id.clone();
21051
21052        let interrupt = Pause::new();
21053        runner.watch_interrupt(interrupt.clone());
21054        interrupt.park_because("task c3d4 asked to run first");
21055        assert!(runner.park_here().expect("park_here"));
21056
21057        let resumed = Runner::resume(&run_id).expect("resume");
21058        assert_eq!(resumed.state.candidates.len(), 1);
21059        assert_eq!(resumed.state.candidates[0].summary, "did the thing");
21060        assert_eq!(resumed.state.candidates[0].branch, "magi/x/A");
21061        assert_eq!(resumed.state.status, runner.state.status);
21062        assert!(
21063            resumed.state.parked,
21064            "still parked until `execute` actually walks the graph again"
21065        );
21066        assert!(resumed.state.events.iter().any(|e| e.node == "park"));
21067    }
21068
21069    /// A fresh open question on `run`, stored and handed back for assertions.
21070    fn ask_open_question(store: &ask::Questions, run: &str) -> ask::Question {
21071        let mut q = ask::Question::new(
21072            run.to_owned(),
21073            "implement".to_owned(),
21074            "impl-A".to_owned(),
21075            "Which storage backend should the cache use?".to_owned(),
21076            String::new(),
21077            vec!["SQLite".to_owned(), "Redis".to_owned()],
21078        );
21079        store.put(&mut q).unwrap();
21080        q
21081    }
21082
21083    #[test]
21084    fn a_failed_runs_open_question_is_abandoned() {
21085        ask_test_home();
21086        let store = ask::Questions::open();
21087        let mut runner = runner_at(RunStatus::Failed);
21088        let run = runner.state.id.clone();
21089        let q = ask_open_question(&store, &run);
21090
21091        runner.settle_questions();
21092
21093        let back = store.get(&q.id).unwrap();
21094        assert!(
21095            !back.status.open(),
21096            "the seat that asked died with the run; nobody is left to read an answer"
21097        );
21098        assert!(
21099            back.detail.contains(&run) && back.detail.contains("failed"),
21100            "the reason names what the run became, not just that it is gone: {}",
21101            back.detail
21102        );
21103    }
21104
21105    #[test]
21106    fn a_merged_runs_open_question_is_abandoned_too() {
21107        ask_test_home();
21108        let store = ask::Questions::open();
21109        // A run that finishes cleanly still leaves nobody to read an answer -
21110        // this is not only a failure-path cleanup.
21111        for status in [RunStatus::Merged, RunStatus::Ready] {
21112            let mut runner = runner_at(status);
21113            let run = runner.state.id.clone();
21114            let q = ask_open_question(&store, &run);
21115
21116            runner.settle_questions();
21117
21118            let back = store.get(&q.id).unwrap();
21119            assert!(
21120                !back.status.open(),
21121                "{status:?} run's question must not outlive the run"
21122            );
21123        }
21124    }
21125
21126    #[test]
21127    fn a_still_resumable_runs_open_question_is_left_alone() {
21128        ask_test_home();
21129        let store = ask::Questions::open();
21130        // `Blocked` and `Stalled` can still be resumed — the candidates, the
21131        // review round and the seat sessions are all still on disk — so a
21132        // question asked mid-round may yet get a real answer from a real
21133        // resume. Sweeping it here would be exactly the failure mode this
21134        // whole feature exists to avoid on the other side.
21135        for status in [RunStatus::Blocked, RunStatus::Stalled] {
21136            let mut runner = runner_at(status);
21137            let run = runner.state.id.clone();
21138            let q = ask_open_question(&store, &run);
21139
21140            runner.settle_questions();
21141
21142            let back = store.get(&q.id).unwrap();
21143            assert!(
21144                back.status.open(),
21145                "{status:?} is still alive; the question must still be waiting"
21146            );
21147        }
21148    }
21149
21150    #[test]
21151    fn settle_questions_never_touches_an_already_answered_question() {
21152        ask_test_home();
21153        let store = ask::Questions::open();
21154        let mut runner = runner_at(RunStatus::Failed);
21155        let run = runner.state.id.clone();
21156        let mut q = ask_open_question(&store, &run);
21157        q.answer(crate::ask::Answer::Choice("SQLite".to_owned()))
21158            .unwrap();
21159        store.put(&mut q).unwrap();
21160
21161        // Called twice, the way a crash-recovered daemon reclaim and the
21162        // graph's own cleanup both can for the same run — `abandon_for_run`
21163        // only ever touches what is still open, so this must be inert both
21164        // times, not merely the second.
21165        runner.settle_questions();
21166        runner.settle_questions();
21167
21168        let back = store.get(&q.id).unwrap();
21169        assert_eq!(
21170            back.status,
21171            ask::QuestionStatus::Answered,
21172            "a real answer is a decision on record, never overwritten by a sweep"
21173        );
21174    }
21175
21176    #[tokio::test]
21177    async fn fold_reclaims_only_proven_idle_isolated_outputs() {
21178        let tmp = tempfile::tempdir().unwrap();
21179        let home = tmp.path().join("home");
21180        let repo = tmp.path().join("repo");
21181        std::fs::create_dir(&home).unwrap();
21182        std::fs::create_dir(&repo).unwrap();
21183        init_repo(&repo);
21184
21185        let mut config = Config::default();
21186        config.graph.worktree_root = Some(tmp.path().join("wt"));
21187        config.verify.build_cache = crate::config::BuildCache::Isolated;
21188        let mut state = RunState::new(
21189            repo.clone(),
21190            "main".into(),
21191            "base".into(),
21192            "fold fixture".into(),
21193            config,
21194        );
21195        let root = state.worktree_root();
21196        let mut outputs = Vec::new();
21197        for name in ["idle", "busy"] {
21198            let checkout = root.join(name);
21199            git::worktree_add_detached(&repo, &checkout, "main")
21200                .await
21201                .unwrap();
21202            let target = crate::build_target::resolve(&home, &checkout).unwrap();
21203            let output = target.join("generated");
21204            std::fs::write(&output, name).unwrap();
21205            outputs.push((target, output));
21206        }
21207        let unknown = crate::build_target::root(&home)
21208            .join("00000000-0000-0000-0000-000000000000")
21209            .join("target");
21210        std::fs::create_dir_all(&unknown).unwrap();
21211        let unowned = unknown.join("generated");
21212        std::fs::write(&unowned, "keep").unwrap();
21213        let owner = crate::cache::Owner::here("fixture", "build", "busy", &root.join("busy"), "");
21214        let crate::cache::AcquireOutcome::Acquired(_lease) =
21215            crate::cache::try_acquire(&home, &outputs[1].0, &owner).unwrap()
21216        else {
21217            panic!("fixture target must be free");
21218        };
21219
21220        fold_run(&mut state, true, &home).await.unwrap();
21221        assert!(!root.exists());
21222        assert!(!outputs[0].1.exists());
21223        assert!(outputs[1].1.is_file());
21224        assert!(unowned.is_file());
21225    }
21226
21227    /// `fold_run(&mut state, drop_winner = false)` is exactly the call
21228    /// `clean::fold_due` makes for a `Ready`/`Failed` run - one that finished
21229    /// without merging, whose winner is still the operator's answer to read.
21230    /// Nothing previously called `fold_run` itself with a real `tally`, so
21231    /// this is the first test to pin down the one distinction the whole
21232    /// automatic-fold feature depends on: the winner's worktree and branch
21233    /// must survive, everything else sharing the run's worktree bay - a
21234    /// loser, standing in for a judge/review worktree too, since `fold_run`'s
21235    /// second sweep treats every non-winner directory under the bay alike -
21236    /// must not.
21237    #[tokio::test]
21238    async fn fold_run_keeps_only_the_winner_when_the_winner_is_not_dropped() {
21239        crate::run::pin_test_home();
21240        let tmp = tempfile::tempdir().expect("tempdir");
21241        let repo = tmp.path().join("repo");
21242        std::fs::create_dir_all(&repo).unwrap();
21243        init_repo(&repo);
21244
21245        let mut config = Config::default();
21246        config.graph.worktree_root = Some(tmp.path().join("wt"));
21247
21248        let mut state = RunState::new(
21249            repo.clone(),
21250            "main".to_owned(),
21251            "deadbeef".to_owned(),
21252            "task".to_owned(),
21253            config,
21254        );
21255        let root = state.worktree_root();
21256        let wt_a = root.join("cand-A");
21257        let wt_b = root.join("cand-B");
21258        git::worktree_add_branch(&repo, &wt_a, "magi/x/A", "main")
21259            .await
21260            .expect("worktree A");
21261        git::worktree_add_branch(&repo, &wt_b, "magi/x/B", "main")
21262            .await
21263            .expect("worktree B");
21264
21265        state.candidates = vec![
21266            Candidate {
21267                index: 0,
21268                label: 'A',
21269                agent: "alpha".to_owned(),
21270                branch: "magi/x/A".to_owned(),
21271                worktree: wt_a.clone(),
21272                summary: String::new(),
21273                stat: String::new(),
21274                files: 0,
21275                commits: 0,
21276                empty: false,
21277                failed: None,
21278                verified_noop: None,
21279                duration_ms: 0,
21280                folded: false,
21281            },
21282            Candidate {
21283                index: 1,
21284                label: 'B',
21285                agent: "beta".to_owned(),
21286                branch: "magi/x/B".to_owned(),
21287                worktree: wt_b.clone(),
21288                summary: String::new(),
21289                stat: String::new(),
21290                files: 0,
21291                commits: 0,
21292                empty: false,
21293                failed: None,
21294                verified_noop: None,
21295                duration_ms: 0,
21296                folded: false,
21297            },
21298        ];
21299        state.tally = Some(Tally {
21300            first_choice: BTreeMap::from([('A', 1)]),
21301            borda: BTreeMap::new(),
21302            winner: 'A',
21303            rankings: 1,
21304            unanimous_initial: true,
21305            deliberated: false,
21306            changed_votes: 0,
21307            unanimous_final: true,
21308            tie_break: None,
21309            judges: 1,
21310            present: 1,
21311            quorum: 1,
21312            met_quorum: true,
21313            uncontested: None,
21314        });
21315        state.status = RunStatus::Ready;
21316
21317        fold_run(&mut state, false, &crate::run::home())
21318            .await
21319            .expect("fold_run");
21320
21321        assert!(wt_a.exists(), "the unmerged winner's worktree survives");
21322        assert!(
21323            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
21324            "the unmerged winner's branch survives"
21325        );
21326        assert!(
21327            !state.candidates[0].folded,
21328            "the winner is not marked folded"
21329        );
21330
21331        assert!(!wt_b.exists(), "the loser's worktree is removed");
21332        assert!(
21333            !git::branch_exists(&repo, "magi/x/B").await.unwrap(),
21334            "the loser's branch is removed"
21335        );
21336        assert!(state.candidates[1].folded, "the loser is marked folded");
21337    }
21338
21339    #[tokio::test]
21340    #[cfg(unix)]
21341    async fn fold_run_waits_for_shared_lock_before_removing_worktrees_branches_or_config() {
21342        use std::os::fd::AsRawFd as _;
21343        use std::time::Duration;
21344
21345        let tmp = tempfile::tempdir().unwrap();
21346        let repo = tmp.path().join("repo");
21347        std::fs::create_dir_all(&repo).unwrap();
21348        init_repo(&repo);
21349        let common = repo.join(".git");
21350        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
21351        let home = tmp.path().join("home");
21352        let mut config = Config::default();
21353        config.coordination = crate::config::test_coordination();
21354        config.graph.worktree_root = Some(tmp.path().join("wt"));
21355        config.graph.timeout_resource_wait = 1;
21356        let mut state = RunState::new(
21357            repo.clone(),
21358            "main".into(),
21359            "deadbeef".into(),
21360            "task".into(),
21361            config,
21362        );
21363        let root = state.worktree_root();
21364        let candidate = root.join("cand-A");
21365        let reviewer = root.join("review-1");
21366        let branch = state.branch_for('A');
21367        git::worktree_add_branch(&repo, &candidate, &branch, "main")
21368            .await
21369            .unwrap();
21370        git::worktree_add_detached(&repo, &reviewer, "main")
21371            .await
21372            .unwrap();
21373        git::acquire_worktree_config(&repo).await.unwrap();
21374        state.enabled_worktree_config = true;
21375        state.status = RunStatus::Ready;
21376        state.candidates.push(Candidate {
21377            index: 0,
21378            label: 'A',
21379            agent: "implement".into(),
21380            branch: branch.clone(),
21381            worktree: candidate.clone(),
21382            summary: String::new(),
21383            stat: String::new(),
21384            files: 0,
21385            commits: 0,
21386            empty: false,
21387            failed: None,
21388            verified_noop: None,
21389            duration_ms: 0,
21390            folded: false,
21391        });
21392        state.save_under(&home).unwrap();
21393        let config_before = std::fs::read(common.join("config")).unwrap();
21394        let worktrees_before = git::git(&repo, &["worktree", "list", "--porcelain"])
21395            .await
21396            .unwrap();
21397        // A separate OS handle bypasses the launcher's local gate, exactly as
21398        // an external updater does, and must still prevent all folding work.
21399        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
21400        assert_eq!(
21401            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
21402            0
21403        );
21404        let mut fold = Box::pin(fold_run(&mut state, true, &home));
21405        assert!(
21406            tokio::time::timeout(Duration::from_millis(200), &mut fold)
21407                .await
21408                .is_err()
21409        );
21410        assert!(candidate.exists());
21411        assert!(reviewer.exists());
21412        assert!(git::branch_exists(&repo, &branch).await.unwrap());
21413        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
21414        assert_eq!(
21415            git::git(&repo, &["worktree", "list", "--porcelain"])
21416                .await
21417                .unwrap(),
21418            worktrees_before
21419        );
21420        let error = tokio::time::timeout(Duration::from_secs(3), &mut fold)
21421            .await
21422            .unwrap()
21423            .unwrap_err();
21424        assert!(error.is::<crate::repo_lock::ResourceBlocked>());
21425        drop(fold);
21426        assert!(candidate.exists() && reviewer.exists());
21427        assert!(!state.candidates[0].folded && state.enabled_worktree_config);
21428        assert_eq!(
21429            state.resource_block.as_ref().unwrap().kind,
21430            "repository coordination"
21431        );
21432        assert_eq!(std::fs::read(common.join("config")).unwrap(), config_before);
21433        drop(external);
21434        let mut fold = Box::pin(fold_run(&mut state, true, &home));
21435        let removed = tokio::time::timeout(Duration::from_secs(10), &mut fold)
21436            .await
21437            .unwrap()
21438            .unwrap();
21439        drop(fold);
21440        assert!(removed.contains(&branch));
21441        assert!(!root.exists());
21442        assert!(!git::branch_exists(&repo, &branch).await.unwrap());
21443        assert!(state.candidates[0].folded);
21444        assert!(!state.enabled_worktree_config);
21445        assert_ne!(std::fs::read(common.join("config")).unwrap(), config_before);
21446        let enabled = git::git_raw(
21447            &repo,
21448            &["config", "--local", "--get", "extensions.worktreeConfig"],
21449        )
21450        .await
21451        .unwrap();
21452        assert!(!enabled.ok(), "the last config reference was released");
21453    }
21454
21455    /// A branch handed to a later run is that run's (and its pull request's):
21456    /// folding the run that released it must not delete it.
21457    #[tokio::test]
21458    async fn fold_run_keeps_a_branch_that_was_handed_to_a_later_run() {
21459        let tmp = tempfile::tempdir().expect("tempdir");
21460        let repo = tmp.path().join("repo");
21461        std::fs::create_dir_all(&repo).unwrap();
21462        init_repo(&repo);
21463        let home = tmp.path().join("home");
21464
21465        let mut config = Config::default();
21466        config.graph.worktree_root = Some(tmp.path().join("wt"));
21467        let mut state = RunState::new(
21468            repo.clone(),
21469            "main".to_owned(),
21470            "deadbeef".to_owned(),
21471            "task".to_owned(),
21472            config,
21473        );
21474        // The worktree is already gone (released); the branch survives.
21475        git::git(&repo, &["branch", "magi/x/A", "main"])
21476            .await
21477            .expect("branch");
21478        state.candidates = vec![Candidate {
21479            index: 0,
21480            label: 'A',
21481            agent: "alpha".to_owned(),
21482            branch: "magi/x/A".to_owned(),
21483            worktree: state.worktree_root().join("cand-A"),
21484            summary: String::new(),
21485            stat: String::new(),
21486            files: 0,
21487            commits: 0,
21488            empty: false,
21489            failed: None,
21490            verified_noop: None,
21491            duration_ms: 0,
21492            folded: true,
21493        }];
21494        state.released_to = Some("20260901-000000-new1".to_owned());
21495        state.released_branches = vec!["magi/x/A".to_owned()];
21496
21497        fold_run(&mut state, true, &home).await.expect("fold_run");
21498        state.status = RunStatus::Merged;
21499        state.base_commit = git::rev_parse(&repo, "main").await.unwrap();
21500        state.merge = Some(crate::run::MergeOutcome {
21501            mode: MergeMode::Pr,
21502            ok: true,
21503            detail: "confirmed merged".into(),
21504            empty: false,
21505        });
21506        fold_run(&mut state, true, &home)
21507            .await
21508            .expect("merged fold");
21509
21510        assert!(
21511            git::branch_exists(&repo, "magi/x/A").await.unwrap(),
21512            "the handed-over branch survives a fold"
21513        );
21514    }
21515
21516    /// A winner with nothing ahead of the base is caught before `gh` is ever
21517    /// asked for a pull request, and the message carries what the task's
21518    /// references resolved to.
21519    #[tokio::test]
21520    async fn an_empty_winner_is_detected_before_a_pull_request_is_attempted() {
21521        let tmp = tempfile::tempdir().expect("tempdir");
21522        let repo = tmp.path().join("repo");
21523        std::fs::create_dir_all(&repo).unwrap();
21524        init_repo(&repo);
21525        let run = |args: &[&str]| {
21526            let out = std::process::Command::new("git")
21527                .quiet()
21528                .args(args)
21529                .current_dir(&repo)
21530                .output()
21531                .expect("spawn git");
21532            assert!(out.status.success(), "git {args:?}");
21533        };
21534        run(&["branch", "magi/x/A"]);
21535        run(&["checkout", "-q", "-b", "magi/x/B"]);
21536        std::fs::write(repo.join("f.txt"), "x\n").unwrap();
21537        run(&["add", "-A"]);
21538        run(&["commit", "-q", "-m", "work"]);
21539        run(&["checkout", "-q", "main"]);
21540
21541        // A pull request is compared against the remote's base, so the
21542        // fixture needs one. Before it exists nothing can be read, and the
21543        // answer must be "not empty".
21544        let probe = RunState::new(
21545            repo.clone(),
21546            "main".to_owned(),
21547            "deadbeef".to_owned(),
21548            "task".to_owned(),
21549            Config::default(),
21550        );
21551        assert!(!merge_is_empty(&repo, &probe, "magi/x/A", MergeMode::Pr).await);
21552        let bare = tmp.path().join("origin.git");
21553        let out = std::process::Command::new("git")
21554            .quiet()
21555            .args(["init", "-q", "--bare"])
21556            .arg(&bare)
21557            .output()
21558            .expect("spawn git");
21559        assert!(out.status.success(), "git init --bare");
21560        run(&["remote", "add", "origin", bare.to_str().unwrap()]);
21561        run(&["push", "-q", "origin", "main"]);
21562
21563        let mut state = RunState::new(
21564            repo.clone(),
21565            "main".to_owned(),
21566            "deadbeef".to_owned(),
21567            "task".to_owned(),
21568            Config::default(),
21569        );
21570        state.seeds = vec![refs::Seed {
21571            token: "magi/27b2/A".to_owned(),
21572            kind: refs::SeedKind::Unresolved,
21573            sha: String::new(),
21574            branch: true,
21575            detail: "no branch or commit named magi/27b2/A".to_owned(),
21576        }];
21577
21578        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Pr).await);
21579        assert!(merge_is_empty(&repo, &state, "magi/x/A", MergeMode::Local).await);
21580        assert!(!merge_is_empty(&repo, &state, "magi/x/B", MergeMode::Pr).await);
21581        let detail = empty_candidate_detail(&state, "main");
21582        assert!(detail.starts_with("empty candidate"), "{detail}");
21583        assert!(!detail.contains("magi/27b2/A"), "{detail}");
21584        assert!(detail.contains("--start-from"), "{detail}");
21585    }
21586
21587    /// `status == Ready` used to be read as "this is the harmless
21588    /// `MergeMode::None` no-op path, nothing to guard" (graph.rs, prior to
21589    /// this test). But `land` sets the very same status when a `MergeMode::Pr`
21590    /// run's PR was closed without merging — and reentering `merge` with
21591    /// `mode` still `Pr` does not know the difference, so it pushed and
21592    /// opened a second pull request. `mode == Local` reproduces the same
21593    /// blind spot without a network call: reentry must not attempt another
21594    /// git merge once this node has already recorded an outcome.
21595    #[tokio::test]
21596    async fn merge_does_not_reattempt_once_a_run_has_concluded() {
21597        let tmp = tempfile::tempdir().expect("tempdir");
21598        let repo = tmp.path().join("repo");
21599        std::fs::create_dir_all(&repo).unwrap();
21600        init_repo(&repo);
21601
21602        let mut config = Config::default();
21603        config.merge.mode = MergeMode::Local;
21604
21605        let mut state = RunState::new(
21606            repo.clone(),
21607            "main".to_owned(),
21608            "deadbeef".to_owned(),
21609            "task".to_owned(),
21610            config,
21611        );
21612        state.candidates = vec![Candidate {
21613            index: 0,
21614            label: 'A',
21615            agent: "alpha".to_owned(),
21616            branch: "does-not-exist".to_owned(),
21617            worktree: repo.clone(),
21618            summary: String::new(),
21619            stat: String::new(),
21620            files: 0,
21621            commits: 0,
21622            empty: false,
21623            failed: None,
21624            verified_noop: None,
21625            duration_ms: 0,
21626            folded: false,
21627        }];
21628        state.tally = Some(Tally {
21629            first_choice: BTreeMap::from([('A', 1)]),
21630            borda: BTreeMap::new(),
21631            winner: 'A',
21632            rankings: 1,
21633            unanimous_initial: true,
21634            deliberated: false,
21635            changed_votes: 0,
21636            unanimous_final: true,
21637            tie_break: None,
21638            judges: 0,
21639            present: 0,
21640            quorum: 0,
21641            met_quorum: true,
21642            uncontested: Some("only candidate A produced a change".to_owned()),
21643        });
21644        state.reviews = vec![ReviewRound {
21645            round: 1,
21646            head: "deadbeef".to_owned(),
21647            verified_head: None,
21648            verified_at: None,
21649            reviews: Vec::new(),
21650            e2e: Vec::new(),
21651            fix: None,
21652            blocking: 0,
21653            answered: 0,
21654            expected: 0,
21655            clean: true,
21656            verify_retried: false,
21657            e2e_deferred: false,
21658            e2e_defer_reason: None,
21659            progressed: false,
21660            vote_split: false,
21661            reconsideration: Vec::new(),
21662            verdict: None,
21663        }];
21664        state.gate = vec![CommandOutcome {
21665            command: "test".to_owned(),
21666            code: Some(0),
21667            output_tail: String::new(),
21668            duration_ms: 0,
21669            resource_blocked: false,
21670            ..Default::default()
21671        }];
21672        state.gate_ran = true;
21673        // Reached its conclusion already — e.g. `land` closing the PR without
21674        // merging it, which (like the honest `MergeMode::None` path) leaves
21675        // `status` at `Ready`. The recorded outcome is what actually marks
21676        // this node done.
21677        state.status = RunStatus::Ready;
21678        state.merge = Some(MergeOutcome {
21679            mode: MergeMode::Local,
21680            ok: false,
21681            detail: "already concluded".to_owned(),
21682            empty: false,
21683        });
21684
21685        let mut runner = Runner {
21686            state,
21687            roles: ResolvedRoles {
21688                implementers: Vec::new(),
21689                judges: Vec::new(),
21690                reviewers: Vec::new(),
21691                fixer: None,
21692                conductor: conductor(),
21693                implementer_roster: Vec::new(),
21694                judge_roster: Vec::new(),
21695                reviewer_roster: Vec::new(),
21696            },
21697            sem: Arc::new(Semaphore::new(1)),
21698            pause: Pause::new(),
21699            interrupt: Pause::new(),
21700        };
21701
21702        runner.merge().await.expect("merge");
21703
21704        assert_eq!(
21705            runner.state.status,
21706            RunStatus::Ready,
21707            "a concluded run's status must not change on reentry"
21708        );
21709        assert_eq!(
21710            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
21711            Some("already concluded"),
21712            "merge must not run again once the node already recorded an outcome"
21713        );
21714    }
21715
21716    /// `gate` leaves `state.gate_ran` false both before it has ever run and
21717    /// when its last attempt was resource-blocked (the shared build cache
21718    /// could not be acquired or confirmed fresh in time - see
21719    /// `CommandOutcome::resource_blocked`'s own doc). Trusting the empty
21720    /// `Vec` this also leaves behind used to read as "nothing failed" and let
21721    /// a run merge a tree the gate never actually checked - exactly the case
21722    /// a contended cache produces on every retry until it clears. `merge`
21723    /// must refuse until `gate` has actually recorded an attempt.
21724    #[tokio::test]
21725    async fn merge_refuses_a_gate_that_has_not_actually_run() {
21726        let tmp = tempfile::tempdir().expect("tempdir");
21727        let repo = tmp.path().join("repo");
21728        std::fs::create_dir_all(&repo).unwrap();
21729        init_repo(&repo);
21730
21731        let mut config = Config::default();
21732        config.merge.mode = MergeMode::Local;
21733
21734        let mut state = RunState::new(
21735            repo.clone(),
21736            "main".to_owned(),
21737            "deadbeef".to_owned(),
21738            "task".to_owned(),
21739            config,
21740        );
21741        state.candidates = vec![Candidate {
21742            index: 0,
21743            label: 'A',
21744            agent: "alpha".to_owned(),
21745            branch: "does-not-exist".to_owned(),
21746            worktree: repo.clone(),
21747            summary: String::new(),
21748            stat: String::new(),
21749            files: 0,
21750            commits: 0,
21751            empty: false,
21752            failed: None,
21753            verified_noop: None,
21754            duration_ms: 0,
21755            folded: false,
21756        }];
21757        state.tally = Some(Tally {
21758            first_choice: BTreeMap::from([('A', 1)]),
21759            borda: BTreeMap::new(),
21760            winner: 'A',
21761            rankings: 1,
21762            unanimous_initial: true,
21763            deliberated: false,
21764            changed_votes: 0,
21765            unanimous_final: true,
21766            tie_break: None,
21767            judges: 0,
21768            present: 0,
21769            quorum: 0,
21770            met_quorum: true,
21771            uncontested: Some("only candidate A produced a change".to_owned()),
21772        });
21773        state.reviews = vec![ReviewRound {
21774            round: 1,
21775            head: "deadbeef".to_owned(),
21776            verified_head: None,
21777            verified_at: None,
21778            reviews: Vec::new(),
21779            e2e: Vec::new(),
21780            fix: None,
21781            blocking: 0,
21782            answered: 0,
21783            expected: 0,
21784            clean: true,
21785            verify_retried: false,
21786            e2e_deferred: false,
21787            e2e_defer_reason: None,
21788            progressed: false,
21789            vote_split: false,
21790            reconsideration: Vec::new(),
21791            verdict: None,
21792        }];
21793        // The point: `gate` has not recorded anything yet.
21794        state.gate = Vec::new();
21795        state.gate_ran = false;
21796        state.status = RunStatus::Gating;
21797
21798        let mut runner = Runner {
21799            state,
21800            roles: ResolvedRoles {
21801                implementers: Vec::new(),
21802                judges: Vec::new(),
21803                reviewers: Vec::new(),
21804                fixer: None,
21805                conductor: conductor(),
21806                implementer_roster: Vec::new(),
21807                judge_roster: Vec::new(),
21808                reviewer_roster: Vec::new(),
21809            },
21810            sem: Arc::new(Semaphore::new(1)),
21811            pause: Pause::new(),
21812            interrupt: Pause::new(),
21813        };
21814
21815        runner.merge().await.expect("merge");
21816
21817        assert!(
21818            runner.state.merge.is_none(),
21819            "an empty gate must never be read as a passing one: {:?}",
21820            runner.state.merge
21821        );
21822    }
21823
21824    /// The `shoka` repro this schema bump exists for: `verify.gate` has no
21825    /// commands configured and `merge.mode` is `none` (a review-only run).
21826    /// `gate` must still record a real attempt — zero commands, vacuously
21827    /// passed — rather than leaving `state.gate` empty in a way `merge`
21828    /// cannot tell apart from "never ran"; otherwise the run reaches
21829    /// `Gating` and can never leave it. See `RunState::gate_ran`'s own doc.
21830    #[tokio::test]
21831    async fn gate_and_merge_reach_ready_when_no_gate_commands_are_configured() {
21832        let tmp = tempfile::tempdir().expect("tempdir");
21833        let repo = tmp.path().join("repo");
21834        std::fs::create_dir_all(&repo).unwrap();
21835        init_repo(&repo);
21836
21837        // Default config: `verify.gate` empty, `merge.mode` is `none`.
21838        let config = Config::default();
21839
21840        let mut state = RunState::new(
21841            repo.clone(),
21842            "main".to_owned(),
21843            "deadbeef".to_owned(),
21844            "task".to_owned(),
21845            config,
21846        );
21847        state.candidates = vec![Candidate {
21848            index: 0,
21849            label: 'A',
21850            agent: "alpha".to_owned(),
21851            branch: "does-not-exist".to_owned(),
21852            worktree: repo.clone(),
21853            summary: String::new(),
21854            stat: String::new(),
21855            files: 0,
21856            commits: 0,
21857            empty: false,
21858            failed: None,
21859            verified_noop: None,
21860            duration_ms: 0,
21861            folded: false,
21862        }];
21863        state.tally = Some(Tally {
21864            first_choice: BTreeMap::from([('A', 1)]),
21865            borda: BTreeMap::new(),
21866            winner: 'A',
21867            rankings: 1,
21868            unanimous_initial: true,
21869            deliberated: false,
21870            changed_votes: 0,
21871            unanimous_final: true,
21872            tie_break: None,
21873            judges: 0,
21874            present: 0,
21875            quorum: 0,
21876            met_quorum: true,
21877            uncontested: Some("only candidate A produced a change".to_owned()),
21878        });
21879        state.reviews = vec![ReviewRound {
21880            round: 1,
21881            head: "deadbeef".to_owned(),
21882            verified_head: None,
21883            verified_at: None,
21884            reviews: Vec::new(),
21885            e2e: Vec::new(),
21886            fix: None,
21887            blocking: 0,
21888            answered: 0,
21889            expected: 0,
21890            clean: true,
21891            verify_retried: false,
21892            e2e_deferred: false,
21893            e2e_defer_reason: None,
21894            progressed: false,
21895            vote_split: false,
21896            reconsideration: Vec::new(),
21897            verdict: None,
21898        }];
21899
21900        let mut runner = Runner {
21901            state,
21902            roles: ResolvedRoles {
21903                implementers: Vec::new(),
21904                judges: Vec::new(),
21905                reviewers: Vec::new(),
21906                fixer: None,
21907                conductor: conductor(),
21908                implementer_roster: Vec::new(),
21909                judge_roster: Vec::new(),
21910                reviewer_roster: Vec::new(),
21911            },
21912            sem: Arc::new(Semaphore::new(1)),
21913            pause: Pause::new(),
21914            interrupt: Pause::new(),
21915        };
21916
21917        runner.gate().await.expect("gate");
21918        assert!(
21919            runner.state.gate_ran,
21920            "zero configured commands is still a real attempt, not an unrun gate"
21921        );
21922        assert!(runner.state.gate.is_empty());
21923        assert_eq!(runner.state.gate_status(), GateStatus::NotConfigured);
21924        assert_ne!(
21925            runner.state.status,
21926            RunStatus::Blocked,
21927            "a gate with nothing to check must not read as failed"
21928        );
21929
21930        runner.merge().await.expect("merge");
21931        assert_eq!(
21932            runner.state.status,
21933            RunStatus::Ready,
21934            "a clean review-only run with no gate commands must reach Ready, not stay stuck in Gating"
21935        );
21936    }
21937
21938    /// `Config::cache_dir` is derived from `verify.e2e` as well as
21939    /// `verify.gate` (so the e2e leg and the final gate never build against
21940    /// different directories). With zero `verify.gate` commands but a
21941    /// `CARGO_TARGET_DIR`-using `verify.e2e`, `gate` used to still queue for
21942    /// that lease before discovering it had nothing to run - so a repo with
21943    /// no gate commands could come back `resource_blocked` (and therefore
21944    /// still `gate_ran == false`) on nothing but an unrelated run holding the
21945    /// cache, exactly the contention this run's own zero commands could
21946    /// never have touched. `gate` must recognise there is nothing to check
21947    /// before it ever asks for the lease.
21948    #[tokio::test]
21949    async fn gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run() {
21950        crate::run::pin_test_home();
21951        let home = crate::run::home();
21952
21953        let tmp = tempfile::tempdir().expect("tempdir");
21954        let repo = tmp.path().join("repo");
21955        std::fs::create_dir_all(&repo).unwrap();
21956        init_repo(&repo);
21957        // Unique to this test, so holding its lease cannot collide with
21958        // another test sharing the same process-wide `home`.
21959        let cache_dir = tmp.path().join("target");
21960
21961        let mut config = Config::default();
21962        config.verify.e2e = vec![format!("CARGO_TARGET_DIR='{}' true", cache_dir.display())];
21963        // `verify.gate` stays empty (the default). Any accidental cache
21964        // acquisition must report contention immediately, regardless of how
21965        // long unrelated Git subprocesses take under parallel test load.
21966        config.graph.timeout_verify = Some(2);
21967        config.graph.timeout_resource_wait = 0;
21968
21969        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
21970        let _held = match crate::cache::try_acquire(&home, &cache_dir, &other)
21971            .expect("no io error acquiring directly")
21972        {
21973            crate::cache::AcquireOutcome::Acquired(g) => g,
21974            crate::cache::AcquireOutcome::Busy(b) => {
21975                panic!("expected the direct acquire to win the lease first: {b:?}")
21976            }
21977        };
21978
21979        let mut state = RunState::new(
21980            repo.clone(),
21981            "main".to_owned(),
21982            "deadbeef".to_owned(),
21983            "task".to_owned(),
21984            config,
21985        );
21986        state.candidates = vec![Candidate {
21987            index: 0,
21988            label: 'A',
21989            agent: "alpha".to_owned(),
21990            branch: "does-not-exist".to_owned(),
21991            worktree: repo.clone(),
21992            summary: String::new(),
21993            stat: String::new(),
21994            files: 0,
21995            commits: 0,
21996            empty: false,
21997            failed: None,
21998            verified_noop: None,
21999            duration_ms: 0,
22000            folded: false,
22001        }];
22002        state.tally = Some(Tally {
22003            first_choice: BTreeMap::from([('A', 1)]),
22004            borda: BTreeMap::new(),
22005            winner: 'A',
22006            rankings: 1,
22007            unanimous_initial: true,
22008            deliberated: false,
22009            changed_votes: 0,
22010            unanimous_final: true,
22011            tie_break: None,
22012            judges: 0,
22013            present: 0,
22014            quorum: 0,
22015            met_quorum: true,
22016            uncontested: Some("only candidate A produced a change".to_owned()),
22017        });
22018        state.reviews = vec![ReviewRound {
22019            round: 1,
22020            head: "deadbeef".to_owned(),
22021            verified_head: None,
22022            verified_at: None,
22023            reviews: Vec::new(),
22024            e2e: Vec::new(),
22025            fix: None,
22026            blocking: 0,
22027            answered: 0,
22028            expected: 0,
22029            clean: true,
22030            verify_retried: false,
22031            e2e_deferred: false,
22032            e2e_defer_reason: None,
22033            progressed: false,
22034            vote_split: false,
22035            reconsideration: Vec::new(),
22036            verdict: None,
22037        }];
22038
22039        state.reviews[0].verified_head = Some(git::rev_parse(&repo, "HEAD").await.unwrap());
22040        state.reviews[0].e2e = vec![CommandOutcome {
22041            command: state.config.verify.e2e[0].clone(),
22042            code: Some(0),
22043            output_tail: String::new(),
22044            duration_ms: 0,
22045            resource_blocked: false,
22046            ..Default::default()
22047        }];
22048        let mut runner = Runner {
22049            state,
22050            roles: ResolvedRoles {
22051                implementers: Vec::new(),
22052                judges: Vec::new(),
22053                reviewers: Vec::new(),
22054                fixer: None,
22055                conductor: conductor(),
22056                implementer_roster: Vec::new(),
22057                judge_roster: Vec::new(),
22058                reviewer_roster: Vec::new(),
22059            },
22060            sem: Arc::new(Semaphore::new(1)),
22061            pause: Pause::new(),
22062            interrupt: Pause::new(),
22063        };
22064
22065        runner.gate().await.expect("gate");
22066        assert!(runner.state.resource_block.is_none());
22067        assert!(
22068            !runner
22069                .state
22070                .events
22071                .iter()
22072                .any(|event| { event.message.contains("waiting for the shared build cache") }),
22073            "a gate with nothing to run must never request the held cache lease"
22074        );
22075        assert!(
22076            runner.state.gate_ran,
22077            "zero commands is still a real, immediate attempt"
22078        );
22079        assert!(runner.state.gate.is_empty());
22080        assert_ne!(
22081            runner.state.status,
22082            RunStatus::Blocked,
22083            "must not read as resource-blocked on a lease it never asked for"
22084        );
22085    }
22086
22087    /// A separate process carries a live worker's environment throughout all
22088    /// verification entry points; the parallel harness never changes its env.
22089    #[cfg(unix)]
22090    #[tokio::test]
22091    async fn verification_is_standalone_inside_a_live_worker() {
22092        const CHILD: &str = "MAGI_VERIFY_WORKER_TEST";
22093        if std::env::var_os(CHILD).is_none() {
22094            let home = tempfile::tempdir().unwrap();
22095            let generation = crate::worker::pin_current(home.path()).unwrap();
22096            let output = std::process::Command::new(std::env::current_exe().unwrap())
22097                .args([
22098                    "--exact",
22099                    "graph::tests::verification_is_standalone_inside_a_live_worker",
22100                    "--nocapture",
22101                ])
22102                .env(CHILD, "1")
22103                .env("MAGI_HOME", home.path())
22104                .env("MAGI_WORKER_HOME", home.path())
22105                .env("MAGI_WORKER_ID", "abcdef")
22106                .env("MAGI_WORKER_GENERATION", &generation.id)
22107                .env("MAGI_WORKER_EXE", &generation.executable)
22108                .env("MAGI_RUN", "verification-parent")
22109                .env("MAGI_NODE", "gate")
22110                .env("MAGI_SEAT", "worker-fixture")
22111                .env("MAGI_PROCESS_OWNER", "fixture-owner")
22112                .env("MAGI_NO_AUTOUPDATE", "0")
22113                .env("VERIFY_EXPECT_PATH", std::env::var_os("PATH").unwrap())
22114                .env("VERIFY_AUTH_TOKEN", "fixture-auth")
22115                .env(
22116                    "VERIFY_EXPECT_TOOLCHAIN",
22117                    std::env::var_os("RUSTUP_TOOLCHAIN").unwrap_or_default(),
22118                )
22119                .env(
22120                    "VERIFY_EXPECT_CACHE",
22121                    std::env::var_os("CARGO_TARGET_DIR").unwrap_or_default(),
22122                )
22123                .output()
22124                .unwrap();
22125            assert!(
22126                output.status.success()
22127                    && String::from_utf8_lossy(&output.stdout).contains("1 passed"),
22128                "{}\n{}",
22129                String::from_utf8_lossy(&output.stdout),
22130                String::from_utf8_lossy(&output.stderr)
22131            );
22132            return;
22133        }
22134        crate::run::set_home(PathBuf::from(std::env::var_os("MAGI_HOME").unwrap()));
22135        let home = crate::run::home();
22136        let directory = home.join("workers/jobs/abcdef");
22137        std::fs::create_dir_all(&directory).unwrap();
22138        let job = crate::worker::Job {
22139            id: "abcdef".into(),
22140            sequence: 1,
22141            kind: "task".into(),
22142            key: "task:verification".into(),
22143            payload: serde_json::json!({}),
22144            generation: std::env::var("MAGI_WORKER_GENERATION").unwrap(),
22145            version: Some(env!("CARGO_PKG_VERSION").into()),
22146            status: crate::worker::Status::Running,
22147            result: None,
22148            pid: Some(std::process::id()),
22149            created_at: 0,
22150            finished_at: None,
22151        };
22152        std::fs::write(
22153            directory.join("job.json"),
22154            serde_json::to_vec(&job).unwrap(),
22155        )
22156        .unwrap();
22157        let _lease = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
22158        let assert_worker = || {
22159            assert_eq!(
22160                crate::worker::current_job(&home).unwrap().unwrap().id,
22161                job.id
22162            );
22163            assert_eq!(crate::worker::active(&home).unwrap().len(), 1);
22164            assert_eq!(
22165                crate::worker::helper_executable(&home).unwrap(),
22166                PathBuf::from(std::env::var_os("MAGI_WORKER_EXE").unwrap())
22167            );
22168            assert!(
22169                crate::updater::Checker::new(&crate::config::Update {
22170                    mode: crate::config::UpdateMode::Notify,
22171                    interval: None,
22172                    auto_restart: false,
22173                })
22174                .is_none(),
22175                "the driver remains pinned, even while tests are standalone"
22176            );
22177        };
22178        assert_worker();
22179        let repo = home.join("repo");
22180        std::fs::create_dir_all(&repo).unwrap();
22181        init_repo(&repo);
22182        // Keep storage, seat/control context, containment and tool lookup.
22183        // No inherited values (or credentials) are printed on success.
22184        let probe = r#"test -z "${MAGI_WORKER_ID+x}" &&
22185            test -z "${MAGI_WORKER_GENERATION+x}" &&
22186            test -z "${MAGI_WORKER_HOME+x}" &&
22187            test -z "${MAGI_WORKER_EXE+x}" &&
22188            test "$MAGI_HOME/repo" -ef . &&
22189            test "$MAGI_RUN" = verification-parent &&
22190            test "$MAGI_NODE" = gate &&
22191            test "$MAGI_SEAT" = worker-fixture &&
22192            test -n "$MAGI_PROCESS_OWNER" &&
22193            test "$PATH" = "$VERIFY_EXPECT_PATH" &&
22194            test "$VERIFY_AUTH_TOKEN" = fixture-auth &&
22195            test "$RUSTUP_TOOLCHAIN" = "$VERIFY_EXPECT_TOOLCHAIN" &&
22196            test "$CARGO_TARGET_DIR" = "$VERIFY_EXPECT_CACHE""#;
22197        // Negative control: an ordinary child inherits the contamination.
22198        assert!(
22199            !std::process::Command::new("sh")
22200                .args(["-c", probe])
22201                .current_dir(&repo)
22202                .status()
22203                .unwrap()
22204                .success()
22205        );
22206        let unrelated_home = tempfile::tempdir().unwrap();
22207        assert!(
22208            crate::worker::current_job(unrelated_home.path()).is_err(),
22209            "an inherited worker id cannot be resolved in a unit fixture's home"
22210        );
22211        let mut runner = runner_at(RunStatus::Gating);
22212        runner.state.repo = repo.clone();
22213        runner.state.config.disk.min_free_bytes = 0;
22214        runner.state.config.coordination = crate::config::test_coordination();
22215        std::fs::write(repo.join(".git/updater.contract"), "test-protocol-v1\n").unwrap();
22216        runner.state.config.verify.e2e = vec![format!("{probe} && printf 'e2e\\n' >> phases")];
22217        runner.state.config.verify.pre_gate = vec![format!("{probe} && printf 'pre\\n' >> phases")];
22218        runner.state.config.verify.gate = vec![format!("{probe} && printf 'gate\\n' >> phases")];
22219        let winner = Candidate {
22220            index: 0,
22221            label: 'A',
22222            agent: "fixture".into(),
22223            branch: "main".into(),
22224            worktree: repo.clone(),
22225            summary: String::new(),
22226            stat: String::new(),
22227            files: 0,
22228            commits: 0,
22229            empty: false,
22230            failed: None,
22231            verified_noop: None,
22232            duration_ms: 0,
22233            folded: false,
22234        };
22235        let (e2e, retried, pids) = run_e2e_with_retry(
22236            &mut runner.state,
22237            &["sh".into(), "-c".into()],
22238            &[format!("{probe} && printf initial")],
22239            &repo,
22240            Duration::from_secs(10),
22241            "initial",
22242            None,
22243        )
22244        .await;
22245        assert!(!retried && pids.is_empty());
22246        assert_eq!(e2e[0].code, Some(0), "{e2e:?}");
22247        assert_eq!(e2e[0].output_tail, "initial");
22248        let gate = runner.run_gate(&winner).await.unwrap();
22249        assert!(gate.iter().all(CommandOutcome::ok), "{gate:?}");
22250        // An interrupted repair must recheck e2e from saved state. Landing
22251        // reuses that state and must run both pre-gate and gate again.
22252        runner.state.gate_repair_e2e = Some(crate::run::GateRepairE2e::new(
22253            git::rev_parse(&repo, "HEAD").await.unwrap(),
22254            false,
22255            Vec::new(),
22256        ));
22257        runner.state.save().unwrap();
22258        let mut resumed = RunState::load(&runner.state.id).unwrap();
22259        let wait = crate::repo_lock::WaitPolicy::default();
22260        assert!(matches!(
22261            check_gate_repair_e2e(&mut resumed, &winner, &wait)
22262                .await
22263                .unwrap(),
22264            GateFix::Retry
22265        ));
22266        let saved = RunState::load(&resumed.id).unwrap();
22267        let repair = saved.gate_repair_e2e.unwrap();
22268        assert!(repair.passed);
22269        assert_eq!(repair.outcomes.len(), 1);
22270        assert!(repair.outcomes[0].ok());
22271        let landing = run_landing_gate(&mut resumed, &winner, &wait)
22272            .await
22273            .unwrap();
22274        assert_eq!(landing.len(), 1);
22275        assert!(landing[0].ok(), "{landing:?}");
22276        assert_eq!(
22277            std::fs::read_to_string(repo.join("phases")).unwrap(),
22278            "pre\ngate\ne2e\npre\ngate\n"
22279        );
22280        assert_worker();
22281    }
22282
22283    #[cfg(unix)]
22284    #[tokio::test]
22285    async fn verification_keeps_the_panic_and_the_full_output() {
22286        crate::run::pin_test_home();
22287        let tmp = tempfile::tempdir().unwrap();
22288        let mut config = Config::default();
22289        config.disk.min_free_bytes = 0;
22290        let mut state = RunState::new(
22291            tmp.path().to_owned(),
22292            "main".into(),
22293            "base".into(),
22294            "verification evidence".into(),
22295            config,
22296        );
22297        let script = "echo \"thread 'x' panicked at t.rs:1:1:\"; echo 'boom assertion'; \
22298                      i=0; while [ $i -lt 20000 ]; do echo \"  $i: 0xabc - <a::b>\"; \
22299                      echo '             at /x/y.rs:1:1'; i=$((i+1)); done; exit 101";
22300        let mut names = Vec::new();
22301        for _ in 0..2 {
22302            let (outcomes, _) = run_commands(
22303                &mut state,
22304                "gate",
22305                "gate",
22306                0,
22307                &["sh".into(), "-c".into()],
22308                &[script.into()],
22309                tmp.path(),
22310                Duration::from_secs(60),
22311            )
22312            .await;
22313            let tail = &outcomes[0].output_tail;
22314            assert!(tail.contains("panicked at t.rs:1:1"), "{tail}");
22315            assert!(tail.contains("boom assertion"));
22316            assert!(tail.len() <= crate::run::VERIFY_SUMMARY + 100);
22317            let line = tail.lines().next().unwrap();
22318            names.push(line.to_owned());
22319        }
22320        assert_ne!(names[0], names[1], "the second run must not overwrite");
22321        let full = crate::run::read_artifact(&state, "gate-1.out").unwrap();
22322        assert!(full.len() > 500_000 && full.contains("boom assertion"));
22323        assert!(crate::run::read_artifact(&state, "gate-2.out").is_some());
22324
22325        // Storage failures are evidence too; preserve the command's verdict.
22326        std::fs::remove_dir_all(state.dir().join("artifacts")).unwrap();
22327        std::fs::write(state.dir().join("artifacts"), "blocked").unwrap();
22328        let (outcomes, _) = run_commands(
22329            &mut state,
22330            "gate",
22331            "gate",
22332            0,
22333            &["sh".into(), "-c".into()],
22334            &["echo failure-output; exit 7".into()],
22335            tmp.path(),
22336            Duration::from_secs(10),
22337        )
22338        .await;
22339        assert_eq!(outcomes[0].code, Some(7));
22340        assert!(state.events.iter().any(|e| {
22341            e.node == "gate" && e.message.contains("could not save the full gate output:")
22342        }));
22343    }
22344
22345    #[cfg(unix)]
22346    #[tokio::test]
22347    async fn verification_commands_distinguish_timeouts_signals_and_exit_codes() {
22348        crate::run::pin_test_home();
22349        let tmp = tempfile::tempdir().unwrap();
22350        let mut config = Config::default();
22351        config.disk.min_free_bytes = 0;
22352        let mut state = RunState::new(
22353            tmp.path().to_owned(),
22354            "main".into(),
22355            "base".into(),
22356            "verification evidence".into(),
22357            config,
22358        );
22359        let (outcomes, pids) = run_commands(
22360            &mut state,
22361            "gate",
22362            "gate",
22363            1,
22364            &["sh".into(), "-c".into()],
22365            &[
22366                "printf before-timeout; exec sleep 30".into(),
22367                "kill -TERM $$".into(),
22368                "exit 7".into(),
22369                "printf success".into(),
22370            ],
22371            tmp.path(),
22372            Duration::from_secs(1),
22373        )
22374        .await;
22375        wait_for_timed_out_children_to_die(&pids).await;
22376        assert_eq!(
22377            pids.len(),
22378            1,
22379            "unleased timeout retains its death-check PID"
22380        );
22381        assert_eq!(outcomes.len(), 4);
22382        assert_eq!(outcomes[0].code, None);
22383        assert!(outcomes[0].output_tail.contains("before-timeout"));
22384        assert!(outcomes[0].output_tail.contains("timed out after 1s"));
22385        assert_eq!(outcomes[1].code, None);
22386        assert!(outcomes[1].output_tail.contains("command terminated:"));
22387        assert!(!outcomes[1].output_tail.contains("timed out"));
22388        assert_eq!(outcomes[2].code, Some(7));
22389        assert!(!outcomes[2].output_tail.contains("timed out"));
22390        assert_eq!(outcomes[3].code, Some(0));
22391        assert_eq!(outcomes[3].output_tail, "success");
22392        assert!(outcomes.iter().all(|outcome| !outcome.resource_blocked));
22393    }
22394
22395    /// The addendum's second gap: a `verify.gate` command running for real
22396    /// wall-clock time had nothing at all to show for it in `active` before
22397    /// `run_commands` learned to record it — a run could sit in `Gating` for
22398    /// minutes with `magi show` and `GET /api/runs/{id}` both silent about
22399    /// what was actually happening. Proven with a genuinely still-running
22400    /// command, not just a before/after check on the final state: a poller
22401    /// task reads the same `run.json` `gate()` is writing, the same way the
22402    /// phone or `magi show` would, while the shell command is still blocked
22403    /// on its own release marker.
22404    #[tokio::test]
22405    async fn gate_records_a_running_task_entry_while_its_command_is_still_in_flight() {
22406        crate::run::pin_test_home();
22407
22408        let tmp = tempfile::tempdir().expect("tempdir");
22409        let repo = tmp.path().join("repo");
22410        std::fs::create_dir_all(&repo).unwrap();
22411        init_repo(&repo);
22412
22413        let mut config = Config::default();
22414        config.disk.min_free_bytes = 0;
22415        config.verify.gate = vec![
22416            "printf started > started.marker; i=0; while [ ! -f release.marker ] && \
22417             [ \"$i\" -lt 100 ]; do i=$((i+1)); sleep 0.05; done; test -f release.marker"
22418                .to_owned(),
22419        ];
22420
22421        let mut state = RunState::new(
22422            repo.clone(),
22423            "main".to_owned(),
22424            "deadbeef".to_owned(),
22425            "task".to_owned(),
22426            config,
22427        );
22428        let run_id = state.id.clone();
22429        state.candidates = vec![Candidate {
22430            index: 0,
22431            label: 'A',
22432            agent: "alpha".to_owned(),
22433            branch: "does-not-exist".to_owned(),
22434            worktree: repo.clone(),
22435            summary: String::new(),
22436            stat: String::new(),
22437            files: 0,
22438            commits: 0,
22439            empty: false,
22440            failed: None,
22441            verified_noop: None,
22442            duration_ms: 0,
22443            folded: false,
22444        }];
22445        state.tally = Some(Tally {
22446            first_choice: BTreeMap::from([('A', 1)]),
22447            borda: BTreeMap::new(),
22448            winner: 'A',
22449            rankings: 1,
22450            unanimous_initial: true,
22451            deliberated: false,
22452            changed_votes: 0,
22453            unanimous_final: true,
22454            tie_break: None,
22455            judges: 0,
22456            present: 0,
22457            quorum: 0,
22458            met_quorum: true,
22459            uncontested: Some("only candidate A produced a change".to_owned()),
22460        });
22461        state.reviews = vec![ReviewRound {
22462            round: 1,
22463            head: "deadbeef".to_owned(),
22464            verified_head: None,
22465            verified_at: None,
22466            reviews: Vec::new(),
22467            e2e: Vec::new(),
22468            fix: None,
22469            blocking: 0,
22470            answered: 0,
22471            expected: 0,
22472            clean: true,
22473            verify_retried: false,
22474            e2e_deferred: false,
22475            e2e_defer_reason: None,
22476            progressed: false,
22477            vote_split: false,
22478            reconsideration: Vec::new(),
22479            verdict: None,
22480        }];
22481
22482        let mut runner = Runner {
22483            state,
22484            roles: ResolvedRoles {
22485                implementers: Vec::new(),
22486                judges: Vec::new(),
22487                reviewers: Vec::new(),
22488                fixer: None,
22489                conductor: conductor(),
22490                implementer_roster: Vec::new(),
22491                judge_roster: Vec::new(),
22492                reviewer_roster: Vec::new(),
22493            },
22494            sem: Arc::new(Semaphore::new(1)),
22495            pause: Pause::new(),
22496            interrupt: Pause::new(),
22497        };
22498
22499        let started_marker = repo.join("started.marker");
22500        let release_marker = repo.join("release.marker");
22501        let observe = async {
22502            loop {
22503                if started_marker.exists()
22504                    && let Ok(s) = crate::run::RunState::load(&run_id)
22505                    && let Some(a) = s.active.get("gate")
22506                {
22507                    std::fs::write(&release_marker, b"go").expect("release marker");
22508                    break a.clone();
22509                }
22510                tokio::time::sleep(Duration::from_millis(50)).await;
22511            }
22512        };
22513        let captured = {
22514            let gate = runner.gate();
22515            tokio::pin!(gate);
22516            let captured = tokio::select! {
22517                observed = observe => observed,
22518                result = &mut gate => panic!(
22519                    "gate exited before its in-flight entry was observed: {result:?}"
22520                ),
22521            };
22522            gate.await.expect("gate");
22523            captured
22524        };
22525
22526        assert_eq!(captured.task.as_deref(), Some("gate"));
22527        assert_eq!(captured.node, "gate");
22528        assert_eq!(captured.index, Some(1));
22529        assert_eq!(captured.total, Some(1));
22530        assert!(
22531            captured
22532                .command
22533                .as_deref()
22534                .is_some_and(|c| c.contains("started.marker")),
22535            "{captured:?}"
22536        );
22537
22538        assert!(
22539            runner.state.active.is_empty(),
22540            "the entry must be cleared once the command actually finished: {:?}",
22541            runner.state.active
22542        );
22543        assert!(runner.state.gate_ran);
22544        assert!(runner.state.gate.iter().all(CommandOutcome::ok));
22545    }
22546
22547    /// The hand-off over a blocking finding a reviewer rejected on leaves a
22548    /// record for `land`; one with only a Minor, or no reject, leaves none.
22549    #[tokio::test]
22550    async fn stop_reviewing_records_a_contested_hand_off_only_for_major_plus_reject() {
22551        use crate::verdict::{Finding, ReviewVote, Severity};
22552        crate::run::pin_test_home();
22553        let tmp = tempfile::tempdir().expect("tempdir");
22554        let repo = tmp.path().join("repo");
22555        std::fs::create_dir_all(&repo).unwrap();
22556        init_repo(&repo);
22557
22558        for (severity, vote, expect) in [
22559            (Severity::Major, ReviewVote::Reject, true),
22560            (Severity::Minor, ReviewVote::Reject, false),
22561            (Severity::Major, ReviewVote::Approve, false),
22562        ] {
22563            let mut round = review_round(false, 1, 1, 1, false, true);
22564            round.reviews = vec![ReviewRecord {
22565                reviewer: 1,
22566                agent: "alpha".to_owned(),
22567                summary: String::new(),
22568                findings: vec![Finding {
22569                    id: "R1-1-1".to_owned(),
22570                    severity,
22571                    file: None,
22572                    line: None,
22573                    title: "t".to_owned(),
22574                    detail: String::new(),
22575                }],
22576                vote: Some(vote),
22577                failed: None,
22578                duration_ms: 0,
22579                attempts: 0,
22580            }];
22581            let mut state = RunState::new(
22582                repo.clone(),
22583                "main".to_owned(),
22584                "deadbeef".to_owned(),
22585                "task".to_owned(),
22586                Config::default(),
22587            );
22588            state.reviews = vec![round];
22589            let mut runner = Runner {
22590                state,
22591                roles: ResolvedRoles {
22592                    implementers: Vec::new(),
22593                    judges: Vec::new(),
22594                    reviewers: Vec::new(),
22595                    fixer: None,
22596                    conductor: conductor(),
22597                    implementer_roster: Vec::new(),
22598                    judge_roster: Vec::new(),
22599                    reviewer_roster: Vec::new(),
22600                },
22601                sem: Arc::new(Semaphore::new(1)),
22602                pause: Pause::new(),
22603                interrupt: Pause::new(),
22604            };
22605            let shell = runner.state.config.shell();
22606            runner
22607                .stop_reviewing("round budget spent", &shell, &repo)
22608                .await
22609                .expect("stop_reviewing");
22610            assert_eq!(runner.state.status, RunStatus::Gating);
22611            assert_eq!(
22612                runner.state.contested_handoff.is_some(),
22613                expect,
22614                "{severity:?} + {vote:?}"
22615            );
22616        }
22617    }
22618
22619    /// The shape the incident this whole fix responds to actually had: the
22620    /// round budget spent, the last round's own e2e blocked on the shared
22621    /// build cache (held here by a live pid — this test process — exactly
22622    /// `cache`'s own unit tests' pattern for "another owner, still alive"
22623    /// without forking a process). `stop_reviewing` must retry it — not
22624    /// silently leave the round looking untouched (the catch-up-only half of
22625    /// the bug), and not read the contention as a red `e2e` and block the
22626    /// run on it (the other half). Called directly, the same way
22627    /// `gate_never_asks_for_the_cache_lease_when_it_has_no_commands_to_run`
22628    /// above exercises `gate`, so this never needs a real cargo build to
22629    /// reach: the lease is never released, so `with_cache_lease` never gets
22630    /// past acquiring it into anything that would need a real workspace.
22631    #[tokio::test]
22632    async fn stop_reviewing_retries_a_resource_blocked_e2e_instead_of_reading_it_as_red() {
22633        crate::run::pin_test_home();
22634        let home = crate::run::home();
22635
22636        let tmp = tempfile::tempdir().expect("tempdir");
22637        let repo = tmp.path().join("repo");
22638        std::fs::create_dir_all(&repo).unwrap();
22639        init_repo(&repo);
22640        let head = crate::git::rev_parse(&repo, "HEAD")
22641            .await
22642            .expect("rev-parse");
22643        // Unique to this test, so holding its lease cannot collide with
22644        // another test sharing the same process-wide `home`.
22645        let cache_dir = tmp.path().join("target");
22646
22647        let mut config = Config::default();
22648        config.verify.e2e = vec![format!(
22649            "CARGO_TARGET_DIR='{}' test -f README.md",
22650            cache_dir.display()
22651        )];
22652        config.graph.review_rounds = 1;
22653        // Bounded so a regression that does start waiting fails the test in
22654        // seconds, not hangs it.
22655        config.graph.timeout_verify = Some(2);
22656        config.graph.timeout_resource_wait = 2;
22657
22658        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
22659        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
22660            .expect("no io error acquiring directly")
22661        {
22662            crate::cache::AcquireOutcome::Acquired(g) => g,
22663            crate::cache::AcquireOutcome::Busy(b) => {
22664                panic!("expected the direct acquire to win the lease first: {b:?}")
22665            }
22666        };
22667
22668        let mut state = RunState::new(
22669            repo.clone(),
22670            "main".to_owned(),
22671            head.clone(),
22672            "task".to_owned(),
22673            config,
22674        );
22675        state.candidates = vec![Candidate {
22676            index: 0,
22677            label: 'A',
22678            agent: "alpha".to_owned(),
22679            branch: "does-not-exist".to_owned(),
22680            worktree: repo.clone(),
22681            summary: String::new(),
22682            stat: String::new(),
22683            files: 0,
22684            commits: 0,
22685            empty: false,
22686            failed: None,
22687            verified_noop: None,
22688            duration_ms: 0,
22689            folded: false,
22690        }];
22691        state.tally = Some(Tally {
22692            first_choice: BTreeMap::from([('A', 1)]),
22693            borda: BTreeMap::new(),
22694            winner: 'A',
22695            rankings: 1,
22696            unanimous_initial: true,
22697            deliberated: false,
22698            changed_votes: 0,
22699            unanimous_final: true,
22700            tie_break: None,
22701            judges: 0,
22702            present: 0,
22703            quorum: 0,
22704            met_quorum: true,
22705            uncontested: Some("only candidate A produced a change".to_owned()),
22706        });
22707        // The round budget's last round, deferred: `needs_catchup_run`'s
22708        // other trigger. `stop_reviewing`'s retry machinery must treat this
22709        // exactly like a resource-blocked attempt once it actually runs.
22710        state.reviews = vec![ReviewRound {
22711            round: 1,
22712            head: head.clone(),
22713            verified_head: None,
22714            verified_at: None,
22715            reviews: Vec::new(),
22716            e2e: Vec::new(),
22717            fix: None,
22718            blocking: 1,
22719            answered: 1,
22720            expected: 1,
22721            clean: false,
22722            verify_retried: false,
22723            e2e_deferred: true,
22724            e2e_defer_reason: Some("1 blocking finding(s) already required a fix".to_owned()),
22725            progressed: false,
22726            vote_split: false,
22727            reconsideration: Vec::new(),
22728            verdict: None,
22729        }];
22730
22731        let mut runner = Runner {
22732            state,
22733            roles: ResolvedRoles {
22734                implementers: Vec::new(),
22735                judges: Vec::new(),
22736                reviewers: Vec::new(),
22737                fixer: None,
22738                conductor: conductor(),
22739                implementer_roster: Vec::new(),
22740                judge_roster: Vec::new(),
22741                reviewer_roster: Vec::new(),
22742            },
22743            sem: Arc::new(Semaphore::new(1)),
22744            pause: Pause::new(),
22745            interrupt: Pause::new(),
22746        };
22747
22748        let shell = runner.state.config.shell();
22749        runner
22750            .stop_reviewing("round budget spent", &shell, &repo)
22751            .await
22752            .expect("stop_reviewing");
22753
22754        let last = runner.state.reviews.last().expect("round record");
22755        assert_eq!(
22756            last.e2e_status(),
22757            E2eStatus::ResourceBlocked,
22758            "the shared cache is still held; the attempt must read as blocked, not deferred or \
22759             failed: {last:?}"
22760        );
22761        assert_eq!(
22762            last.verified_head.as_deref(),
22763            Some(head.as_str()),
22764            "which commit this attempt targeted is known even though nothing finished checking \
22765             it"
22766        );
22767        let first_attempt_at = last
22768            .verified_at
22769            .expect("when this attempt ran is known too");
22770        assert_ne!(
22771            runner.state.status,
22772            RunStatus::Blocked,
22773            "contention is evidence about the machine, not the patch — it must not settle the \
22774             run as blocked: {:?}",
22775            runner.state.status
22776        );
22777        assert!(
22778            !runner
22779                .state
22780                .events
22781                .iter()
22782                .any(|e| e.node == "review" && e.message.contains("e2e failed")),
22783            "a resource-blocked attempt must never be logged as a failed e2e: {:?}",
22784            runner.state.events
22785        );
22786
22787        // The cache is still held: a later reentry must retry the same
22788        // round's verification again — not leave it looking exactly as
22789        // untouched as the first blocked attempt, which is indistinguishable
22790        // from never having tried again at all.
22791        runner
22792            .stop_reviewing("round budget spent", &shell, &repo)
22793            .await
22794            .expect("stop_reviewing retry");
22795        assert_eq!(
22796            runner.state.reviews.len(),
22797            1,
22798            "no new round was started: {:?}",
22799            runner.state.reviews
22800        );
22801        let last = runner.state.reviews.last().expect("round record");
22802        assert_eq!(last.e2e_status(), E2eStatus::ResourceBlocked, "{last:?}");
22803        assert!(
22804            last.verified_at.expect("still known") > first_attempt_at,
22805            "a second reentry must be a fresh attempt, not a stale copy of the first"
22806        );
22807        assert_ne!(runner.state.status, RunStatus::Blocked);
22808
22809        held.release();
22810    }
22811
22812    #[cfg(unix)]
22813    #[tokio::test]
22814    async fn catchup_compile_failure_after_clean_base_sync_uses_remaining_review_rounds() {
22815        ask_test_home();
22816        for (max_rounds, reentry) in [(2, false), (2, true), (1, false)] {
22817            let tmp = tempfile::tempdir().unwrap();
22818            let repo = tmp.path().join("repo");
22819            std::fs::create_dir(&repo).unwrap();
22820            init_repo(&repo);
22821            let run_git = |args: &[&str]| {
22822                let out = std::process::Command::new("git")
22823                    .args(args)
22824                    .current_dir(&repo)
22825                    .output()
22826                    .unwrap();
22827                assert!(
22828                    out.status.success(),
22829                    "{args:?}: {}",
22830                    String::from_utf8_lossy(&out.stderr)
22831                );
22832            };
22833            let origin = tmp.path().join("origin.git");
22834            run_git(&["init", "--bare", origin.to_str().unwrap()]);
22835            run_git(&["remote", "add", "origin", origin.to_str().unwrap()]);
22836            std::fs::write(repo.join("spec.rs"), "struct AgentSpec {}\n").unwrap();
22837            run_git(&["add", "spec.rs"]);
22838            run_git(&["commit", "-m", "initial spec"]);
22839            run_git(&["push", "origin", "main"]);
22840            let base = git::rev_parse(&repo, "HEAD").await.unwrap();
22841            run_git(&["checkout", "-b", "fix/review"]);
22842            std::fs::write(
22843                repo.join("check.rs"),
22844                "include!(\"spec.rs\"); fn main() { let _ = AgentSpec {}; }\n",
22845            )
22846            .unwrap();
22847            run_git(&["add", "check.rs"]);
22848            run_git(&["commit", "-m", "use spec"]);
22849            let reviewed = git::rev_parse(&repo, "HEAD").await.unwrap();
22850            run_git(&["checkout", "main"]);
22851            std::fs::write(
22852                repo.join("spec.rs"),
22853                "struct AgentSpec { max_turn_secs: u64 }\n",
22854            )
22855            .unwrap();
22856            run_git(&["add", "spec.rs"]);
22857            run_git(&["commit", "-m", "extend spec"]);
22858            run_git(&["push", "origin", "main"]);
22859            run_git(&["checkout", "fix/review"]);
22860
22861            let mut runner = runner_at(RunStatus::Reviewing);
22862            runner.state.repo = repo.clone();
22863            runner.state.base_commit = base;
22864            runner.state.pr_head = Some("fix/review".into());
22865            runner.state.config.graph.review_rounds = max_rounds;
22866            runner.state.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
22867            runner.state.config.graph.sessions = false;
22868            runner.state.config.disk.min_free_bytes = 0;
22869            runner.state.config.verify.e2e =
22870                vec!["rustc --emit=metadata -o ../check.rmeta check.rs || { echo 'error: could not compile fixture' >&2; exit 101; }".into()];
22871            runner.state.candidates = vec![Candidate {
22872                index: 0,
22873                label: 'A',
22874                agent: "fixture".into(),
22875                branch: "fix/review".into(),
22876                worktree: repo.clone(),
22877                summary: String::new(),
22878                stat: String::new(),
22879                files: 1,
22880                commits: 1,
22881                empty: false,
22882                failed: None,
22883                verified_noop: None,
22884                duration_ms: 0,
22885                folded: false,
22886            }];
22887            runner.state.tally = Some(Tally {
22888                first_choice: BTreeMap::new(),
22889                borda: BTreeMap::new(),
22890                winner: 'A',
22891                rankings: 0,
22892                unanimous_initial: true,
22893                deliberated: false,
22894                changed_votes: 0,
22895                unanimous_final: true,
22896                tie_break: None,
22897                judges: 0,
22898                present: 0,
22899                quorum: 0,
22900                met_quorum: true,
22901                uncontested: Some("review-only".into()),
22902            });
22903            let mut last = review_round(false, 0, 1, 1, false, false);
22904            last.head = reviewed.clone();
22905            last.e2e_deferred = true;
22906            last.e2e[0].resource_blocked = true;
22907            last.e2e[0].output_tail = "waiting for the shared build cache".into();
22908            if max_rounds == 1 {
22909                last.e2e.clear();
22910            }
22911            runner.state.reviews = vec![last];
22912            let calls = tmp.path().join("fix-calls");
22913            let mut fixer = spec("repair");
22914            fixer
22915                .env
22916                .insert("FIX_CALLS".into(), calls.display().to_string());
22917            fixer.command = vec!["sh".into(), "-c".into(), r#"
22918                echo fix >> "$FIX_CALLS"
22919                grep -q E0063 "$MAGI_PROMPT_FILE" || exit 1
22920                grep -q max_turn_secs "$MAGI_PROMPT_FILE" || exit 1
22921                printf 'include!("spec.rs"); fn main() { let _ = AgentSpec { max_turn_secs: 0 }; }\n' > check.rs
22922                printf '{"addressed":[],"rejected":[],"notes":"initialize the new field"}\n'
22923            "#.into()];
22924            let mut reviewer = spec("reviewer");
22925            reviewer.command = vec![
22926                "sh".into(),
22927                "-c".into(),
22928                "printf '%s\\n' '{\"summary\":\"clean\",\"vote\":\"approve\",\"findings\":[]}'"
22929                    .into(),
22930            ];
22931            runner.roles.fixer = Some(vec![fixer]);
22932            runner.roles.reviewers = vec![reviewer];
22933
22934            runner.sync_to_base().await.unwrap();
22935            let rebased = git::rev_parse(&repo, "HEAD").await.unwrap();
22936            assert_ne!(rebased, reviewed);
22937            assert!(runner.state.base_sync.as_ref().unwrap().conflict.is_none());
22938            if reentry {
22939                // Simulate a crash after catch-up evidence was saved but before
22940                // dispatching the fixer. No dedicated pending-repair field exists.
22941                let shell = runner.state.config.shell();
22942                runner
22943                    .stop_unresolved_review("deferred verification", &shell, &repo)
22944                    .await
22945                    .unwrap();
22946                assert!(runner.catchup_repairable());
22947                assert!(!calls.exists());
22948                runner.state = RunState::load(&runner.state.id).unwrap();
22949                assert!(runner.catchup_repairable());
22950            }
22951            runner.review_loop().await.unwrap();
22952            let first = &runner.state.reviews[0];
22953            assert_eq!(first.head, reviewed);
22954            assert_eq!(first.verified_head.as_deref(), Some(rebased.as_str()));
22955            assert!(
22956                first.verify_retried,
22957                "a reproduced build failure gets exactly one retry: {:?}",
22958                first.e2e
22959            );
22960            assert!(first.e2e[0].output_tail.contains("E0063"));
22961            assert!(!runner.catchup_repairable());
22962            if max_rounds == 2 {
22963                assert_eq!(
22964                    runner.state.status,
22965                    RunStatus::Gating,
22966                    "{}",
22967                    crate::report::run(&runner.state)
22968                );
22969                assert_eq!(runner.state.reviews.len(), 2);
22970                assert!(first.fix.as_ref().unwrap().committed);
22971                assert!(runner.state.reviews[1].clean);
22972                assert_eq!(
22973                    runner
22974                        .state
22975                        .reviews
22976                        .iter()
22977                        .filter(|r| r.fix.is_some())
22978                        .count(),
22979                    1
22980                );
22981                assert_eq!(std::fs::read_to_string(&calls).unwrap().lines().count(), 1);
22982                assert_eq!(runner.state.reviews[1].e2e_status(), E2eStatus::Passed);
22983            } else {
22984                assert_eq!(runner.state.status, RunStatus::Blocked);
22985                assert!(first.fix.is_none());
22986                assert!(!calls.exists());
22987                let recovery = crate::recovery::assess(
22988                    "prior",
22989                    Some(&runner.state),
22990                    &runner.landing_base(),
22991                    crate::recovery::Relation::Diverged,
22992                );
22993                assert_eq!(recovery.mode, crate::recovery::Mode::FullReview);
22994                let reasons = recovery.reasons.join("\n");
22995                assert!(
22996                    reasons.contains(&reviewed) && reasons.contains(&rebased),
22997                    "{reasons}"
22998                );
22999                assert!(
23000                    reasons.contains("base sync to")
23001                        && reasons.contains("additional review is required"),
23002                    "{reasons}"
23003                );
23004            }
23005        }
23006    }
23007
23008    /// A resumed run — a fresh `Runner`, `self.state.reviews` already
23009    /// holding the round `stop_reviewing` left `ResourceBlocked` from a
23010    /// prior process — must not sit at `Reviewing` forever: `review_loop`'s
23011    /// own top-of-function fast path (`review_conclusion`) correctly reads
23012    /// this shape as `None` rather than guessing `Blocked`, and the loop's
23013    /// own `for` range is empty once the round budget is spent, so
23014    /// `review_loop` must retry the check itself rather than silently doing
23015    /// nothing. Reaches the exact same retry `stop_reviewing_retries_a_*`
23016    /// above exercises directly, but through `review_loop`'s own entry point
23017    /// this time, proving the wiring between the two rather than just the
23018    /// retry logic in isolation.
23019    #[tokio::test]
23020    async fn a_resumed_review_loop_retries_a_last_round_left_resource_blocked() {
23021        crate::run::pin_test_home();
23022        let home = crate::run::home();
23023
23024        let tmp = tempfile::tempdir().expect("tempdir");
23025        let repo = tmp.path().join("repo");
23026        std::fs::create_dir_all(&repo).unwrap();
23027        init_repo(&repo);
23028        let head = crate::git::rev_parse(&repo, "HEAD")
23029            .await
23030            .expect("rev-parse");
23031        let cache_dir = tmp.path().join("target");
23032
23033        let mut config = Config::default();
23034        config.verify.e2e = vec![format!(
23035            "CARGO_TARGET_DIR='{}' test -f README.md",
23036            cache_dir.display()
23037        )];
23038        config.graph.review_rounds = 1;
23039        config.graph.timeout_verify = Some(2);
23040        config.graph.timeout_resource_wait = 2;
23041
23042        let other = crate::cache::Owner::here("other-run", "e2e", "e2e", &repo, "deadbeef");
23043        let held = match crate::cache::try_acquire(&home, &cache_dir, &other)
23044            .expect("no io error acquiring directly")
23045        {
23046            crate::cache::AcquireOutcome::Acquired(g) => g,
23047            crate::cache::AcquireOutcome::Busy(b) => {
23048                panic!("expected the direct acquire to win the lease first: {b:?}")
23049            }
23050        };
23051
23052        let mut state = RunState::new(
23053            repo.clone(),
23054            "main".to_owned(),
23055            head.clone(),
23056            "task".to_owned(),
23057            config,
23058        );
23059        state.candidates = vec![Candidate {
23060            index: 0,
23061            label: 'A',
23062            agent: "alpha".to_owned(),
23063            branch: "does-not-exist".to_owned(),
23064            worktree: repo.clone(),
23065            summary: String::new(),
23066            stat: String::new(),
23067            files: 0,
23068            commits: 0,
23069            empty: false,
23070            failed: None,
23071            verified_noop: None,
23072            duration_ms: 0,
23073            folded: false,
23074        }];
23075        state.tally = Some(Tally {
23076            first_choice: BTreeMap::from([('A', 1)]),
23077            borda: BTreeMap::new(),
23078            winner: 'A',
23079            rankings: 1,
23080            unanimous_initial: true,
23081            deliberated: false,
23082            changed_votes: 0,
23083            unanimous_final: true,
23084            tie_break: None,
23085            judges: 0,
23086            present: 0,
23087            quorum: 0,
23088            met_quorum: true,
23089            uncontested: Some("only candidate A produced a change".to_owned()),
23090        });
23091        // The exact shape a prior process's `stop_reviewing` would have left
23092        // on disk: the round budget's last round, a real attempt already
23093        // made and already resource-blocked.
23094        state.reviews = vec![ReviewRound {
23095            round: 1,
23096            head: head.clone(),
23097            verified_head: Some(head.clone()),
23098            verified_at: Some(jiff::Timestamp::now()),
23099            reviews: Vec::new(),
23100            e2e: vec![CommandOutcome {
23101                command: format!(
23102                    "CARGO_TARGET_DIR='{}' test -f README.md",
23103                    cache_dir.display()
23104                ),
23105                code: None,
23106                output_tail: "waiting for the shared build cache".to_owned(),
23107                duration_ms: 0,
23108                resource_blocked: true,
23109                ..Default::default()
23110            }],
23111            fix: None,
23112            blocking: 1,
23113            answered: 1,
23114            expected: 1,
23115            clean: false,
23116            verify_retried: false,
23117            e2e_deferred: false,
23118            e2e_defer_reason: None,
23119            progressed: false,
23120            vote_split: false,
23121            reconsideration: Vec::new(),
23122            verdict: None,
23123        }];
23124
23125        let first_attempt_at = state.reviews[0].verified_at.expect("set above");
23126        let mut runner = Runner {
23127            state,
23128            roles: ResolvedRoles {
23129                implementers: Vec::new(),
23130                judges: Vec::new(),
23131                reviewers: Vec::new(),
23132                fixer: None,
23133                conductor: conductor(),
23134                implementer_roster: Vec::new(),
23135                judge_roster: Vec::new(),
23136                reviewer_roster: Vec::new(),
23137            },
23138            sem: Arc::new(Semaphore::new(1)),
23139            pause: Pause::new(),
23140            interrupt: Pause::new(),
23141        };
23142
23143        // The lease is still held throughout, so this reentry's own retry is
23144        // also contended — proving `review_loop` actually tried again (not
23145        // that it happened to succeed) is what the timestamp comparison
23146        // below is for.
23147        runner.review_loop().await.expect("review_loop");
23148
23149        assert_eq!(
23150            runner.state.reviews.len(),
23151            1,
23152            "no new round was started on top of the unresolved one: {:?}",
23153            runner.state.reviews
23154        );
23155        let last = &runner.state.reviews[0];
23156        assert_eq!(
23157            last.e2e_status(),
23158            E2eStatus::ResourceBlocked,
23159            "still contended: {last:?}"
23160        );
23161        assert!(
23162            last.verified_at.expect("still known") > first_attempt_at,
23163            "review_loop must have actually retried the check, not left it exactly as found"
23164        );
23165        assert_ne!(
23166            runner.state.status,
23167            RunStatus::Blocked,
23168            "a resumed run must not read leftover contention as a verdict on the patch: {:?}",
23169            runner.state.status
23170        );
23171
23172        held.release();
23173    }
23174
23175    #[tokio::test]
23176    async fn stopped_landing_resumes_from_structured_pr_even_with_legacy_gating_status() {
23177        crate::run::pin_test_home();
23178        for status in [RunStatus::Blocked, RunStatus::Gating] {
23179            let mut runner = runner_at(status);
23180            runner.state.config.graph.land = true;
23181            runner.state.gate_ran = true;
23182            runner.state.merge = Some(MergeOutcome {
23183                mode: MergeMode::Pr,
23184                ok: false,
23185                detail: "the fixer produced no commit".into(),
23186                empty: false,
23187            });
23188            let url = "https://example.invalid/o/r/pull/1";
23189            runner.state.pr = Some(crate::run::PrRecord {
23190                url: url.into(),
23191                number: 1,
23192                state: "open".into(),
23193                checks: "red".into(),
23194                round: 1,
23195                rounds: 1,
23196                red_at_merge: Vec::new(),
23197            });
23198            runner.state.save().unwrap();
23199            // The nonexistent repository makes observation fail before a forge
23200            // command can run. We still must reach land, rather than silently
23201            // return from the graph with its old gate and merge records.
23202            runner.execute_graph().await.unwrap();
23203            assert_eq!(runner.state.status, RunStatus::Blocked);
23204            assert!(runner.state.land_sync_pending);
23205            assert!(runner.state.events.iter().any(|event|
23206                event.node == "land" && event.message == format!("watching {url}")));
23207            assert_eq!(
23208                runner.state.merge.as_ref().unwrap().detail,
23209                "the fixer produced no commit"
23210            );
23211        }
23212    }
23213
23214    #[tokio::test]
23215    async fn a_run_resumed_mid_landing_reenters_land_instead_of_opening_a_second_pull_request() {
23216        crate::run::pin_test_home();
23217        let tmp = tempfile::tempdir().expect("tempdir");
23218        let repo = tmp.path().join("repo");
23219        std::fs::create_dir_all(&repo).unwrap();
23220        init_repo(&repo);
23221
23222        let mut config = Config::default();
23223        config.merge.mode = MergeMode::Pr;
23224        config.graph.land = true;
23225        config.graph.land_approval = false;
23226
23227        let mut state = RunState::new(
23228            repo.clone(),
23229            "main".to_owned(),
23230            "deadbeef".to_owned(),
23231            "task".to_owned(),
23232            config,
23233        );
23234        state.candidates = vec![Candidate {
23235            index: 0,
23236            label: 'A',
23237            agent: "alpha".to_owned(),
23238            branch: "does-not-exist".to_owned(),
23239            worktree: repo.clone(),
23240            summary: String::new(),
23241            stat: String::new(),
23242            files: 0,
23243            commits: 0,
23244            empty: false,
23245            failed: None,
23246            verified_noop: None,
23247            duration_ms: 0,
23248            folded: false,
23249        }];
23250        state.tally = Some(Tally {
23251            first_choice: BTreeMap::from([('A', 1)]),
23252            borda: BTreeMap::new(),
23253            winner: 'A',
23254            rankings: 1,
23255            unanimous_initial: true,
23256            deliberated: false,
23257            changed_votes: 0,
23258            unanimous_final: true,
23259            tie_break: None,
23260            judges: 0,
23261            present: 0,
23262            quorum: 0,
23263            met_quorum: true,
23264            uncontested: Some("only candidate A produced a change".to_owned()),
23265        });
23266        state.reviews = vec![ReviewRound {
23267            round: 1,
23268            head: "deadbeef".to_owned(),
23269            verified_head: None,
23270            verified_at: None,
23271            reviews: Vec::new(),
23272            e2e: Vec::new(),
23273            fix: None,
23274            blocking: 0,
23275            answered: 0,
23276            expected: 0,
23277            clean: true,
23278            verify_retried: false,
23279            e2e_deferred: false,
23280            e2e_defer_reason: None,
23281            progressed: false,
23282            vote_split: false,
23283            reconsideration: Vec::new(),
23284            verdict: None,
23285        }];
23286        state.gate = vec![CommandOutcome {
23287            command: "test".to_owned(),
23288            code: Some(0),
23289            output_tail: String::new(),
23290            duration_ms: 0,
23291            resource_blocked: false,
23292            ..Default::default()
23293        }];
23294        state.gate_ran = true;
23295        // A first pass through `merge` already pushed and opened this pull
23296        // request; `status` is `Landing` because a previous call into `land`
23297        // parked or was interrupted before it reached a terminal outcome.
23298        state.status = RunStatus::Landing;
23299        state.merge = Some(MergeOutcome {
23300            mode: MergeMode::Pr,
23301            ok: true,
23302            detail: "https://example.invalid/x/y/pull/1".to_owned(),
23303            empty: false,
23304        });
23305
23306        // The Landing-resume shortcut calls `run_land` directly rather than
23307        // through `merge`, which is exactly the call site that used to skip
23308        // `settle_questions` - see the fixture below.
23309        ask_test_home();
23310        // A real resume loads a persisted run; driver ownership is checked
23311        // against that record before the Landing shortcut is entered.
23312        state.save().expect("save landing run");
23313        let store = ask::Questions::open();
23314        let q = ask_open_question(&store, &state.id);
23315
23316        let mut runner = Runner {
23317            state,
23318            roles: ResolvedRoles {
23319                implementers: Vec::new(),
23320                judges: Vec::new(),
23321                reviewers: Vec::new(),
23322                fixer: None,
23323                conductor: conductor(),
23324                implementer_roster: Vec::new(),
23325                judge_roster: Vec::new(),
23326                reviewer_roster: Vec::new(),
23327            },
23328            sem: Arc::new(Semaphore::new(1)),
23329            pause: Pause::new(),
23330            interrupt: Pause::new(),
23331        };
23332
23333        // `execute`, not `merge` directly: the Landing-resume shortcut lives
23334        // at the top of `execute`, not inside `merge` (see `execute`'s doc)
23335        // exactly because `review_loop` would otherwise clobber the marker
23336        // first.
23337        runner.execute().await.expect("execute");
23338
23339        assert_eq!(
23340            runner.state.merge.as_ref().map(|m| m.detail.as_str()),
23341            Some("https://example.invalid/x/y/pull/1"),
23342            "reentry must not push again or open a second pull request over the \
23343             one `land` is already watching"
23344        );
23345        assert_ne!(
23346            runner.state.status,
23347            RunStatus::Landing,
23348            "land could not actually reach the fake pull request, so it must \
23349             have given up rather than left the run silently parked forever"
23350        );
23351        // `land` could not reach the fake pull request, so it gave up into
23352        // `Blocked` - still resumable, so the question must not have been
23353        // swept just because this branch now also calls `settle_questions`.
23354        assert_eq!(runner.state.status, RunStatus::Blocked);
23355        assert!(
23356            store.get(&q.id).unwrap().status.open(),
23357            "Blocked is still alive; settle_questions must have been a no-op here"
23358        );
23359    }
23360
23361    fn state_with_round(round: ReviewRound) -> RunState {
23362        let mut s = RunState::new(
23363            PathBuf::from("/repo"),
23364            "main".to_owned(),
23365            "abc1234".to_owned(),
23366            "add retries".to_owned(),
23367            Config::default(),
23368        );
23369        s.reviews = vec![round];
23370        s
23371    }
23372
23373    fn finding(id: &str, severity: Severity, title: &str) -> crate::verdict::Finding {
23374        crate::verdict::Finding {
23375            id: id.to_owned(),
23376            severity,
23377            file: None,
23378            line: None,
23379            title: title.to_owned(),
23380            detail: String::new(),
23381        }
23382    }
23383
23384    #[test]
23385    fn pr_body_names_open_findings_and_declined_ones() {
23386        let round = ReviewRound {
23387            round: 2,
23388            head: "deadbee".to_owned(),
23389            verified_head: None,
23390            verified_at: None,
23391            reviews: vec![ReviewRecord {
23392                attempts: 0,
23393                reviewer: 1,
23394                agent: "alpha".to_owned(),
23395                summary: String::new(),
23396                findings: vec![finding("R2-1-1", Severity::Minor, "unused import")],
23397                vote: None,
23398                failed: None,
23399                duration_ms: 0,
23400            }],
23401            e2e: vec![CommandOutcome {
23402                command: "cargo test".to_owned(),
23403                code: Some(0),
23404                output_tail: String::new(),
23405                duration_ms: 0,
23406                resource_blocked: false,
23407                ..Default::default()
23408            }],
23409            verify_retried: false,
23410            e2e_deferred: false,
23411            e2e_defer_reason: None,
23412            fix: Some(FixRecord {
23413                agent: "alpha".to_owned(),
23414                addressed: Vec::new(),
23415                rejected: vec![crate::verdict::Rejection {
23416                    id: "R1-1-1".to_owned(),
23417                    why: "not reachable from any caller".to_owned(),
23418                }],
23419                notes: String::new(),
23420                committed: true,
23421                failed: None,
23422                duration_ms: 0,
23423                continuation: None,
23424            }),
23425            blocking: 0,
23426            answered: 1,
23427            expected: 1,
23428            clean: false,
23429            progressed: true,
23430            vote_split: false,
23431            reconsideration: Vec::new(),
23432            verdict: None,
23433        };
23434        let state = state_with_round(round);
23435        let body = pr_message(&state, 'A').body;
23436
23437        assert!(body.contains("add retries"), "the task must still be there");
23438        assert!(body.contains("R2-1-1"), "{body}");
23439        assert!(!body.contains("unused import"), "{body}");
23440        assert!(body.contains("R1-1-1"), "the declined finding: {body}");
23441        assert!(
23442            !body.contains("not reachable from any caller"),
23443            "the reason it was declined: {body}"
23444        );
23445    }
23446
23447    #[test]
23448    fn pr_body_says_nothing_extra_when_the_round_was_clean() {
23449        let round = ReviewRound {
23450            round: 1,
23451            head: "deadbee".to_owned(),
23452            verified_head: None,
23453            verified_at: None,
23454            reviews: vec![ReviewRecord {
23455                attempts: 0,
23456                reviewer: 1,
23457                agent: "alpha".to_owned(),
23458                summary: String::new(),
23459                findings: Vec::new(),
23460                vote: None,
23461                failed: None,
23462                duration_ms: 0,
23463            }],
23464            e2e: Vec::new(),
23465            verify_retried: false,
23466            e2e_deferred: false,
23467            e2e_defer_reason: None,
23468            fix: None,
23469            blocking: 0,
23470            answered: 1,
23471            expected: 1,
23472            clean: true,
23473            progressed: false,
23474            vote_split: false,
23475            reconsideration: Vec::new(),
23476            verdict: None,
23477        };
23478        let state = state_with_round(round);
23479        let body = pr_message(&state, 'A').body;
23480        assert!(!body.contains("Open review findings"), "{body}");
23481        assert!(!body.contains("Declined"), "{body}");
23482    }
23483
23484    fn state_with_summary(instruction: &str, summary: &str) -> RunState {
23485        let mut state = RunState::new(
23486            PathBuf::from("/repo"),
23487            "main".to_owned(),
23488            "abc1234".to_owned(),
23489            instruction.to_owned(),
23490            Config::default(),
23491        );
23492        // These fixtures test execution flow, independent of host disk capacity.
23493        state.config.disk.min_free_bytes = 0;
23494        state.candidates.push(Candidate {
23495            index: 0,
23496            label: 'A',
23497            agent: "alpha".to_owned(),
23498            branch: "magi/x/A".to_owned(),
23499            worktree: PathBuf::from("/wt"),
23500            summary: summary.to_owned(),
23501            stat: String::new(),
23502            files: 1,
23503            commits: 1,
23504            empty: false,
23505            failed: None,
23506            verified_noop: None,
23507            folded: false,
23508            duration_ms: 0,
23509        });
23510        state
23511    }
23512
23513    fn review_state(subjects: &[&str]) -> RunState {
23514        let mut state = state_with_summary(
23515            "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",
23516            "",
23517        );
23518        state.candidates[0].agent = EXISTING_BRANCH.to_owned();
23519        state.reviewed_commits = Some(subjects.iter().map(|s| (*s).to_owned()).collect());
23520        state
23521    }
23522
23523    /// A branch rebased onto a main that moved past the recorded
23524    /// `base_commit` is titled from its own first commit, never main's.
23525    #[tokio::test]
23526    async fn a_rebased_review_branch_is_titled_from_its_own_commits() {
23527        ask_test_home();
23528        let tmp = tempfile::tempdir().unwrap();
23529        let repo = tmp.path().join("repo");
23530        std::fs::create_dir_all(&repo).unwrap();
23531        init_repo(&repo);
23532        let origin = tmp.path().join("origin.git");
23533        let g = |dir: &Path, args: &[&str]| {
23534            let out = std::process::Command::new("git")
23535                .args(args)
23536                .current_dir(dir)
23537                .quiet()
23538                .output()
23539                .expect("spawn git");
23540            assert!(
23541                out.status.success(),
23542                "git {args:?}: {}",
23543                String::from_utf8_lossy(&out.stderr)
23544            );
23545        };
23546        g(
23547            tmp.path(),
23548            &[
23549                "clone",
23550                "--bare",
23551                "-q",
23552                repo.to_str().unwrap(),
23553                origin.to_str().unwrap(),
23554            ],
23555        );
23556        g(
23557            &repo,
23558            &["remote", "add", "origin", origin.to_str().unwrap()],
23559        );
23560        let c1 = git::rev_parse(&repo, "main").await.unwrap();
23561
23562        // Main moves on; the branch is built on top of the new main.
23563        std::fs::write(repo.join("dep.txt"), "bump\n").unwrap();
23564        g(&repo, &["add", "-A"]);
23565        g(
23566            &repo,
23567            &["commit", "-q", "-m", "chore(deps): update a crate"],
23568        );
23569        g(&repo, &["push", "-q", "origin", "main"]);
23570        g(&repo, &["checkout", "-q", "-b", "feat/own"]);
23571        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
23572        g(&repo, &["add", "-A"]);
23573        g(
23574            &repo,
23575            &["commit", "-q", "-m", "fix(daemon): apply a chosen action"],
23576        );
23577        g(&repo, &["checkout", "-q", "main"]);
23578
23579        let start = review_base(&repo, "origin", "main", &c1, "feat/own").await;
23580        assert_eq!(start, git::rev_parse(&repo, "main").await.unwrap());
23581        // Without a readable tracking ref the recorded base's merge base is used.
23582        let fallback = review_base(&repo, "nowhere", "main", &c1, "feat/own").await;
23583        assert_eq!(fallback, c1);
23584
23585        let mut state = review_state(&[
23586            "chore(deps): update a crate",
23587            "fix(daemon): apply a chosen action",
23588        ]);
23589        state.repo = repo.clone();
23590        state.base_branch = "main".to_owned();
23591        state.base_commit = c1;
23592        refresh_reviewed_commits(&mut state, "feat/own").await;
23593        assert_eq!(
23594            state.reviewed_commits,
23595            Some(vec!["fix(daemon): apply a chosen action".to_owned()])
23596        );
23597        assert_eq!(
23598            review_title(&state).as_deref(),
23599            Some("fix(daemon): apply a chosen action")
23600        );
23601        assert_eq!(
23602            leaked_subjects(&state, "feat/own").await,
23603            Some(vec!["chore(deps): update a crate".to_owned()])
23604        );
23605        // A stale tracking ref is still used when the fetch fails, but the
23606        // leak list is withheld.
23607        state.config.merge.remote = "nowhere".to_owned();
23608        assert_eq!(leaked_subjects(&state, "feat/own").await, None);
23609    }
23610
23611    /// A review-only run whose winner is `feat/own`, checked out in `repo`,
23612    /// with `origin/main` one commit behind it, and a summarizing agent that
23613    /// prints whatever `reply` holds.
23614    struct SummaryFixture {
23615        _tmp: tempfile::TempDir,
23616        repo: PathBuf,
23617        reply: PathBuf,
23618        runner: Runner,
23619    }
23620
23621    fn summary_fixture() -> SummaryFixture {
23622        ask_test_home();
23623        let tmp = tempfile::tempdir().unwrap();
23624        let repo = tmp.path().join("repo");
23625        std::fs::create_dir_all(&repo).unwrap();
23626        init_repo(&repo);
23627        let origin = tmp.path().join("origin.git");
23628        let g = |args: &[&str]| {
23629            let out = std::process::Command::new("git")
23630                .args(args)
23631                .current_dir(&repo)
23632                .quiet()
23633                .output()
23634                .expect("spawn git");
23635            assert!(
23636                out.status.success(),
23637                "git {args:?}: {}",
23638                String::from_utf8_lossy(&out.stderr)
23639            );
23640        };
23641        g(&["init", "-q", "--bare", origin.to_str().unwrap()]);
23642        g(&["remote", "add", "origin", origin.to_str().unwrap()]);
23643        g(&["push", "-q", "origin", "main"]);
23644        g(&["checkout", "-q", "-b", "feat/own"]);
23645        std::fs::write(repo.join("own.txt"), "own\n").unwrap();
23646        g(&["add", "-A"]);
23647        g(&["commit", "-q", "-m", "feat(own): add the own file"]);
23648        let reply = tmp.path().join("reply.txt");
23649        std::fs::write(
23650            &reply,
23651            "TITLE: feat(own): add the own file\nAdds `own.txt` so the first summary is read.",
23652        )
23653        .unwrap();
23654        let mut runner = runner_at(RunStatus::Gating);
23655        let mut state = review_state(&["feat(own): add the own file"]);
23656        state.repo = repo.clone();
23657        state.base_branch = "main".to_owned();
23658        state.candidates[0].branch = "feat/own".to_owned();
23659        state.candidates[0].worktree = repo.clone();
23660        let mut author = spec("alpha");
23661        author.command = vec!["sh".into(), "-c".into(), "cat \"$REPLY_FILE\"".into()];
23662        author
23663            .env
23664            .insert("REPLY_FILE".into(), reply.to_string_lossy().into_owned());
23665        state.config.agents = vec![author];
23666        runner.state = state;
23667        SummaryFixture {
23668            _tmp: tmp,
23669            repo,
23670            reply,
23671            runner,
23672        }
23673    }
23674
23675    async fn posted(f: &mut SummaryFixture) -> PrMessage {
23676        let winner = f.runner.state.candidates[0].clone();
23677        f.runner
23678            .guarded_pr_message(&winner, None, true)
23679            .await
23680            .unwrap()
23681            .expect("an English description never parks")
23682    }
23683
23684    fn clean_round_with_minor_findings() -> ReviewRound {
23685        let mut round = passing_round(2, None);
23686        round.verdict = Some(crate::verdict::ReviewVote::ApproveWithFindings);
23687        round.reviews = vec![ReviewRecord {
23688            attempts: 0,
23689            reviewer: 1,
23690            agent: "alpha".into(),
23691            summary: "内部レビュー".into(),
23692            findings: vec![
23693                finding("R2-1-1", Severity::Minor, "未修正の懸念その一"),
23694                finding("R2-1-2", Severity::Minor, "未修正の懸念その二"),
23695            ],
23696            vote: Some(crate::verdict::ReviewVote::ApproveWithFindings),
23697            failed: None,
23698            duration_ms: 0,
23699        }];
23700        round
23701    }
23702
23703    #[tokio::test]
23704    async fn public_descriptions_cover_minor_findings_from_clean_rounds_in_both_modes() {
23705        for review_only in [false, true] {
23706            let mut f = summary_fixture();
23707            if !review_only {
23708                f.runner.state.candidates[0].agent = "alpha".into();
23709            }
23710            f.runner.state.reviews = vec![clean_round_with_minor_findings()];
23711            assert!(f.runner.state.reviews[0].clean);
23712            assert!(f.runner.state.reviews[0].fix.is_none());
23713            assert!(f.runner.state.open_findings().is_empty());
23714            assert_eq!(
23715                crate::pr_outcome::required_finding_ids(&f.runner.state),
23716                ["R2-1-1", "R2-1-2"]
23717            );
23718            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23719            let evidence = crate::pr_outcome::summary_evidence(
23720                &f.runner.state,
23721                crate::pr_outcome::FinalHead::At(&head),
23722            );
23723            assert!(
23724                evidence.contains("未修正の懸念その一") && evidence.contains("未修正の懸念その二")
23725            );
23726            // The ordinary reply omits both IDs: no cached description is adopted.
23727            let omitted = posted(&mut f).await;
23728            assert!(omitted.body.contains("No description"));
23729            assert!(omitted.body.contains("`R2-1-1` [Minor]"));
23730            assert!(omitted.body.contains("`R2-1-2` [Minor]"));
23731            assert!(f.runner.state.change_summary.is_none());
23732            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();
23733            let described = posted(&mut f).await;
23734            assert!(described.body.contains("improve documentation for callers"));
23735            assert!(described.body.contains("remaining edge case"));
23736            assert!(described.body.contains("## Open review findings"));
23737            assert!(!described.body.contains("未修正"));
23738        }
23739    }
23740
23741    async fn rewrite_fixture_with_findings(review_only: bool, reply: &str) -> SummaryFixture {
23742        let mut f = summary_fixture();
23743        if !review_only {
23744            f.runner.state.candidates[0].agent = "alpha".into();
23745        }
23746        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23747        let mut fixed = round_with_notes(1, Some("日本語の内部修正報告"));
23748        fixed
23749            .fix
23750            .as_mut()
23751            .unwrap()
23752            .rejected
23753            .push(crate::verdict::Rejection {
23754                id: "R1-1-1".into(),
23755                why: "呼び出されないコードのため辞退".into(),
23756            });
23757        let mut clean = clean_round_with_minor_findings();
23758        clean.verified_head = Some(head.clone());
23759        f.runner.state.reviews = vec![fixed, clean];
23760        ok_gate(&mut f.runner.state, Some(&head));
23761        std::fs::write(&f.reply, "TITLE: fix: public description\n日本語の公開用説明です。R1-1-1 は辞退。R2-1-1 と R2-1-2 の懸念が残ります。").unwrap();
23762        f.runner.state.config.agents.push(scripted("beta", reply));
23763        f.runner.state.config.roles.language_judge =
23764            Some(crate::config::AgentChoice::One("beta".into()));
23765        f
23766    }
23767
23768    #[tokio::test]
23769    async fn posting_rewrite_retains_structured_evidence_and_finding_explanations() {
23770        for review_only in [false, true] {
23771            let mut f = rewrite_fixture_with_findings(review_only,
23772                "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;
23773            let m = posted(&mut f).await;
23774            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23775            let expected =
23776                public_pr_evidence(&f.runner.state, crate::pr_outcome::FinalHead::At(&head));
23777            assert!(m.body.contains(&expected));
23778            assert!(m.body.contains("## Review rounds"));
23779            assert!(
23780                m.body
23781                    .contains("Gate (`verify.gate`): passed on the final commit")
23782            );
23783            assert!(
23784                m.body
23785                    .contains("Tests (`verify.e2e`): passed on the final commit")
23786            );
23787            let c = f.runner.state.change_summary.as_ref().unwrap();
23788            assert!(
23789                m.body
23790                    .contains(&format!("Evidence: final diff `{}`..`{}`", c.base, head))
23791            );
23792            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
23793            assert!(crate::pr_outcome::covers_required_findings(
23794                &f.runner.state,
23795                &m.body
23796            ));
23797            assert!(m.body.contains("documentation remains incomplete"));
23798            assert!(!m.body.contains("内部") && !m.body.contains("辞退"));
23799            assert_eq!(f.runner.state.seats["github-text-rewrite"].turns, 1);
23800            assert!(f.runner.state.github_text.is_none());
23801        }
23802    }
23803
23804    #[tokio::test]
23805    async fn posting_rewrite_missing_required_finding_context_is_not_offered_or_published() {
23806        for review_only in [false, true] {
23807            for reply in [
23808                "TITLE: fix: public description\nA short English description.",
23809                "TITLE: fix: public description\nR1-1-1 and R2-1-2 remain; R2-1-1-extra is a different ID.",
23810            ] {
23811                let mut f = rewrite_fixture_with_findings(review_only, reply).await;
23812                let winner = f.runner.state.candidates[0].clone();
23813                let posted = f
23814                    .runner
23815                    .guarded_pr_message(&winner, None, true)
23816                    .await
23817                    .unwrap();
23818                assert!(posted.is_none());
23819                assert!(f.runner.state.parked);
23820                let withheld = f.runner.state.github_text.as_ref().unwrap();
23821                assert!(
23822                    withheld.rewrite.is_none(),
23823                    "an incomplete rewrite must not be selectable"
23824                );
23825                let q = ask::Questions::open()
23826                    .get(withheld.question.as_ref().unwrap())
23827                    .unwrap();
23828                assert!(
23829                    !q.choices
23830                        .contains(&crate::github_text::USE_REWRITE.to_owned())
23831                );
23832                assert!(
23833                    q.detail.contains("R1-1-1")
23834                        && q.detail.contains("R2-1-1")
23835                        && q.detail.contains("R2-1-2")
23836                );
23837            }
23838        }
23839    }
23840
23841    #[tokio::test]
23842    async fn japanese_reports_stay_local_in_both_public_run_modes() {
23843        for review_only in [false, true] {
23844            let mut f = summary_fixture();
23845            if !review_only {
23846                f.runner.state.candidates[0].agent = "alpha".into();
23847            }
23848            f.runner.state.instruction = "内部タスクの説明".into();
23849            f.runner.state.candidates[0].summary = "内部の候補報告".into();
23850            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23851            f.runner.state.reviews = vec![
23852                round_with_notes(1, Some("コミットできません。テストは実行できません。")),
23853                round_with_notes(2, Some("二回目の内部修正報告です。")),
23854                passing_round(3, Some(&head)),
23855            ];
23856            f.runner.state.reviews[0].fix.as_mut().unwrap().addressed = vec!["R1-1-1".into()];
23857            ok_gate(&mut f.runner.state, Some(&head));
23858            let captured = f.repo.join("public-prompt.txt");
23859            let author = &mut f.runner.state.config.agents[0];
23860            author.command = vec![
23861                "sh".into(),
23862                "-c".into(),
23863                "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
23864            ];
23865            author.env.insert(
23866                "PROMPT_FILE".into(),
23867                captured.to_string_lossy().into_owned(),
23868            );
23869            let m = posted(&mut f).await;
23870            assert!(m.body.contains("Adds `own.txt`"));
23871            assert!(m.body.contains("Round 1") && m.body.contains("Round 2"));
23872            assert!(m.body.contains("R1-1-1"));
23873            assert!(
23874                m.body
23875                    .contains("Gate (`verify.gate`): passed on the final commit")
23876            );
23877            assert!(
23878                m.body
23879                    .contains("Tests (`verify.e2e`): passed on the final commit")
23880            );
23881            assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
23882            assert!(!m.body.contains("内部") && !m.body.contains("できません"));
23883            let prompt = std::fs::read_to_string(captured).unwrap();
23884            assert!(prompt.contains(&format!(
23885                "git diff {} {head}",
23886                f.runner.state.change_summary.as_ref().unwrap().base
23887            )));
23888            assert!(!prompt.contains("二回目") && !prompt.contains("コミットできません"));
23889            assert_eq!(
23890                f.runner.state.reviews[1].fix.as_ref().unwrap().notes,
23891                "二回目の内部修正報告です。"
23892            );
23893        }
23894    }
23895
23896    #[tokio::test]
23897    async fn public_generation_failure_never_falls_back_to_internal_notes_and_resume_retries() {
23898        for review_only in [false, true] {
23899            let mut f = summary_fixture();
23900            if !review_only {
23901                f.runner.state.candidates[0].agent = "alpha".into();
23902            }
23903            f.runner.state.candidates[0].summary = "内部報告を公開しない".into();
23904            f.runner.state.reviews = vec![round_with_notes(1, Some("日本語の修正報告"))];
23905            std::fs::write(&f.reply, "no usable description").unwrap();
23906            let failed = posted(&mut f).await;
23907            assert!(
23908                failed
23909                    .body
23910                    .contains("No description of what this change does could be generated")
23911            );
23912            assert!(failed.body.is_ascii());
23913            assert!(f.runner.state.github_text.is_none());
23914            assert!(f.runner.state.change_summary.is_none());
23915            let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23916            let evidence = crate::pr_outcome::summary_evidence(
23917                &f.runner.state,
23918                crate::pr_outcome::FinalHead::At(&head),
23919            );
23920            let fp = crate::pr_outcome::summary_fingerprint(&f.runner.state, &evidence);
23921            assert!(
23922                crate::run::artifact_path(&f.runner.state, &format!("public-description-{fp}.md"))
23923                    .exists()
23924            );
23925            f.runner.state =
23926                serde_json::from_str(&serde_json::to_string(&f.runner.state).unwrap()).unwrap();
23927            std::fs::write(
23928                &f.reply,
23929                "TITLE: feat(own): add the own file\nAdds the committed own file.",
23930            )
23931            .unwrap();
23932            let retried = posted(&mut f).await;
23933            assert!(retried.body.contains("Adds the committed own file."));
23934            assert_eq!(
23935                f.runner.state.reviews[0].fix.as_ref().unwrap().notes,
23936                "日本語の修正報告"
23937            );
23938        }
23939    }
23940
23941    #[tokio::test]
23942    async fn same_head_verification_and_findings_invalidate_public_prose() {
23943        let mut f = summary_fixture();
23944        posted(&mut f).await;
23945        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
23946        let original = f
23947            .runner
23948            .state
23949            .change_summary
23950            .as_ref()
23951            .unwrap()
23952            .evidence
23953            .clone();
23954        ok_gate(&mut f.runner.state, Some(&head));
23955        std::fs::write(
23956            &f.reply,
23957            "TITLE: feat(own): add the own file\nDescribes the now verified final change.",
23958        )
23959        .unwrap();
23960        let verified = posted(&mut f).await;
23961        assert!(verified.body.contains("now verified"));
23962        assert_ne!(
23963            f.runner.state.change_summary.as_ref().unwrap().evidence,
23964            original
23965        );
23966        let mut round = round_with_notes(1, Some("内部報告"));
23967        round.reviews.push(ReviewRecord {
23968            attempts: 0,
23969            reviewer: 1,
23970            agent: "alpha".into(),
23971            summary: "内部レビュー".into(),
23972            findings: vec![finding("R1-1-1", Severity::Minor, "残っている懸念")],
23973            vote: None,
23974            failed: None,
23975            duration_ms: 0,
23976        });
23977        round
23978            .fix
23979            .as_mut()
23980            .unwrap()
23981            .rejected
23982            .push(crate::verdict::Rejection {
23983                id: "R1-1-1".into(),
23984                why: "呼び出し元から到達できない".into(),
23985            });
23986        f.runner.state.reviews = vec![round];
23987        // A description omitting the required ID is unusable, even with a title.
23988        let omitted = posted(&mut f).await;
23989        assert!(omitted.body.contains("No description"));
23990        assert!(omitted.body.contains("R1-1-1"));
23991        assert!(!omitted.body.contains("到達"));
23992        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();
23993        let described = posted(&mut f).await;
23994        assert!(described.body.contains("unreachable from callers"));
23995        assert!(described.body.contains("R1-1-1"));
23996        assert!(!described.body.contains("到達"));
23997        let evidence = f
23998            .runner
23999            .state
24000            .change_summary
24001            .as_ref()
24002            .unwrap()
24003            .evidence
24004            .clone();
24005        f.runner.state.reviews[0].fix.as_mut().unwrap().rejected[0].why = "別の根拠".into();
24006        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: decline rationale updated after review.").unwrap();
24007        assert!(posted(&mut f).await.body.contains("rationale updated"));
24008        assert_ne!(
24009            f.runner.state.change_summary.as_ref().unwrap().evidence,
24010            evidence
24011        );
24012        // Old serialized summaries have no evidence fingerprint and must regenerate.
24013        f.runner
24014            .state
24015            .change_summary
24016            .as_mut()
24017            .unwrap()
24018            .evidence
24019            .clear();
24020        std::fs::write(&f.reply, "TITLE: feat(own): add the own file\nR1-1-1 [Minor]: regenerated under the current specification.").unwrap();
24021        assert!(posted(&mut f).await.body.contains("current specification"));
24022    }
24023
24024    #[tokio::test]
24025    async fn a_review_only_run_with_no_fixer_gets_a_summary_of_the_final_diff() {
24026        let mut f = summary_fixture();
24027        let m = posted(&mut f).await;
24028        assert_eq!(m.title, "feat(own): add the own file");
24029        assert!(
24030            m.body
24031                .contains("## Summary\n\nAdds `own.txt` so the first summary is read."),
24032            "{}",
24033            m.body
24034        );
24035        assert!(!m.body.contains("## Review fixes"), "{}", m.body);
24036        assert!(m.body.contains("Evidence: final diff"), "{}", m.body);
24037        assert!(m.body.contains(&format!("magi:run/{}", f.runner.state.id)));
24038        let head = git::rev_parse(&f.repo, "HEAD").await.unwrap();
24039        let base = git::rev_parse(&f.repo, "origin/main").await.unwrap();
24040        let kept = f.runner.state.change_summary.as_ref().unwrap();
24041        assert_eq!(
24042            (kept.head.as_str(), kept.base.as_str()),
24043            (head.as_str(), base.as_str())
24044        );
24045        assert!(!f.runner.state.seats["change-summary"].key.is_empty());
24046    }
24047
24048    #[tokio::test]
24049    async fn review_only_summary_receives_the_configured_github_language() {
24050        let mut f = summary_fixture();
24051        f.runner.state.config.graph.github_language = "ja".into();
24052        let captured = f.repo.join("summary-prompt.txt");
24053        let author = &mut f.runner.state.config.agents[0];
24054        author.command = vec![
24055            "sh".into(),
24056            "-c".into(),
24057            "cat > \"$PROMPT_FILE\"; cat \"$REPLY_FILE\"".into(),
24058        ];
24059        author.env.insert(
24060            "PROMPT_FILE".into(),
24061            captured.to_string_lossy().into_owned(),
24062        );
24063        std::fs::write(
24064            &f.reply,
24065            "TITLE: feat(own): ファイルを追加\nown.txt を追加します。",
24066        )
24067        .unwrap();
24068        let m = posted(&mut f).await;
24069        let prompt = std::fs::read_to_string(captured).unwrap();
24070        assert!(prompt.contains("Write the TITLE line and the Markdown description in Japanese."));
24071        assert!(!prompt.contains("in English"));
24072        assert_eq!(m.title, "feat(own): ファイルを追加");
24073        assert!(m.body.contains("own.txt を追加します。"));
24074    }
24075
24076    #[tokio::test]
24077    async fn review_fixes_come_after_the_whole_change_summary() {
24078        let mut f = summary_fixture();
24079        f.runner.state.reviews = vec![
24080            round_with_notes(1, Some("handled the PATH case")),
24081            round_with_notes(2, None),
24082        ];
24083        let m = posted(&mut f).await;
24084        let summary = m.body.find("## Summary").expect("summary");
24085        let fixes = m.body.find("## Review rounds").expect("review rounds");
24086        assert!(summary < fixes, "{}", m.body);
24087        assert!(!m.body.contains("handled the PATH case"), "{}", m.body);
24088        assert!(m.body.contains("## Final verification"), "{}", m.body);
24089    }
24090
24091    #[tokio::test]
24092    async fn a_changed_final_diff_invalidates_the_earlier_summary() {
24093        let mut f = summary_fixture();
24094        let first = posted(&mut f).await;
24095        let first_head = f.runner.state.change_summary.clone().unwrap().head;
24096        // The same head reuses the record: a different reply is not read.
24097        std::fs::write(&f.reply, "TITLE: feat(own): other\nNot read yet.").unwrap();
24098        let again = posted(&mut f).await;
24099        assert_eq!((again.title, again.body), (first.title, first.body));
24100
24101        let g = |args: &[&str]| {
24102            let out = std::process::Command::new("git")
24103                .args(args)
24104                .current_dir(&f.repo)
24105                .quiet()
24106                .output()
24107                .expect("spawn git");
24108            assert!(out.status.success(), "git {args:?}");
24109        };
24110        std::fs::write(f.repo.join("more.txt"), "more\n").unwrap();
24111        g(&["add", "-A"]);
24112        g(&["commit", "-q", "-m", "fix(own): handle more"]);
24113        let second = posted(&mut f).await;
24114        let kept = f.runner.state.change_summary.clone().unwrap();
24115        assert_ne!(kept.head, first_head);
24116        assert!(second.body.contains("Not read yet."), "{}", second.body);
24117        assert!(!second.body.contains("so the first summary is read"));
24118        assert_eq!(second.title, "feat(own): other");
24119    }
24120
24121    #[tokio::test]
24122    async fn an_unavailable_summary_is_stated_and_never_invented() {
24123        let mut f = summary_fixture();
24124        std::fs::write(&f.reply, "no title line here").unwrap();
24125        let m = posted(&mut f).await;
24126        assert!(
24127            m.body
24128                .contains("No description of what this change does could be generated"),
24129            "{}",
24130            m.body
24131        );
24132        assert!(m.body.contains("internal reports remain in local records"));
24133        assert!(f.runner.state.change_summary.is_none());
24134        assert!(!m.body.contains("## Commits under review"), "{}", m.body);
24135        // A preview asks nobody and claims nothing.
24136        let winner = f.runner.state.candidates[0].clone();
24137        let preview = f
24138            .runner
24139            .guarded_pr_message(&winner, None, false)
24140            .await
24141            .unwrap()
24142            .unwrap();
24143        assert!(!preview.body.contains("## Summary"), "{}", preview.body);
24144    }
24145
24146    #[test]
24147    fn pr_message_review_single_commit_uses_its_subject() {
24148        let state = review_state(&["feat(nats): per-role user"]);
24149        let m = pr_message(&state, 'A');
24150        assert_eq!(m.title, "feat(nats): per-role user");
24151        assert!(!m.body.contains("Review the work already"), "{}", m.body);
24152        assert!(m.body.contains("## Commits under review"), "{}", m.body);
24153    }
24154
24155    #[test]
24156    fn pr_message_review_multi_commit_takes_the_oldest() {
24157        let state = review_state(&["feat: the change", "fix: typo", "fix: again"]);
24158        let m = pr_message(&state, 'A');
24159        assert_eq!(m.title, "feat: the change");
24160        for s in ["feat: the change", "fix: typo", "fix: again"] {
24161            assert!(m.body.contains(&format!("- {s}\n")), "{}", m.body);
24162        }
24163    }
24164
24165    #[test]
24166    fn pr_message_review_without_a_usable_first_subject_is_neutral() {
24167        for first in ["日本語の件名", "", "magi: candidate A (uncommitted work)"] {
24168            let mut state = review_state(&[first, "fix: later fixup"]);
24169            state.candidates[0].branch = "機能/ログイン".to_owned();
24170            let m = pr_message(&state, 'A');
24171            assert!(
24172                m.title.starts_with("chore: land candidate A of run"),
24173                "{}",
24174                m.title
24175            );
24176        }
24177    }
24178
24179    fn facts(commits: &[(&str, &str)], stat: &str) -> BranchFacts {
24180        BranchFacts {
24181            commits: commits
24182                .iter()
24183                .map(|(s, b)| ((*s).to_owned(), (*b).to_owned()))
24184                .collect(),
24185            stat: stat.to_owned(),
24186        }
24187    }
24188
24189    fn round_with_notes(round: usize, notes: Option<&str>) -> ReviewRound {
24190        let mut r = review_round(true, 0, 1, 1, true, true);
24191        r.round = round;
24192        r.fix = notes.map(|n| FixRecord {
24193            agent: "fixer".to_owned(),
24194            addressed: Vec::new(),
24195            rejected: Vec::new(),
24196            notes: n.to_owned(),
24197            committed: true,
24198            failed: None,
24199            duration_ms: 0,
24200            continuation: None,
24201        });
24202        r
24203    }
24204
24205    #[test]
24206    fn pr_message_review_with_branch_facts_uses_commits_and_stat() {
24207        let state = review_state(&["ignored"]);
24208        let f = facts(
24209            &[
24210                (
24211                    "fix(login): resolve PATH on macOS",
24212                    "Login shells skip rc files.",
24213                ),
24214                ("fix: address review", ""),
24215            ],
24216            " src/a.rs | 2 +-\n 1 file changed, 1 insertion(+), 1 deletion(-)",
24217        );
24218        let m = pr_message_with(&state, 'A', Some(&f));
24219        assert_eq!(m.title, "fix(login): resolve PATH on macOS");
24220        assert!(
24221            m.body
24222                .contains("- fix(login): resolve PATH on macOS\n  Login shells skip rc files.\n"),
24223            "{}",
24224            m.body
24225        );
24226        assert!(m.body.contains("- fix: address review\n"), "{}", m.body);
24227        assert!(m.body.contains("## Diff stat"), "{}", m.body);
24228        assert!(m.body.contains("src/a.rs | 2 +-"), "{}", m.body);
24229        for banned in [
24230            "Review the work already",
24231            "no task statement",
24232            "Original task",
24233        ] {
24234            assert!(!m.body.contains(banned), "{banned}: {}", m.body);
24235        }
24236        assert!(m.body.ends_with("magi:candidate-a\n"), "{}", m.body);
24237    }
24238
24239    #[test]
24240    fn pr_message_review_truncates_a_huge_first_commit_body() {
24241        let state = review_state(&["ignored"]);
24242        let f = facts(
24243            &[("feat: big", &"x".repeat(70_000)), ("fix: later", "")],
24244            "s",
24245        );
24246        let m = pr_message_with(&state, 'A', Some(&f));
24247        assert!(m.body.len() < 30_000, "{}", m.body.len());
24248        assert!(m.body.contains("(truncated)"), "{}", m.body.len());
24249        assert!(
24250            m.body.contains("- ... 1 more commit(s)"),
24251            "{}",
24252            m.body.len()
24253        );
24254        assert!(m.body.ends_with("magi:candidate-a\n"));
24255    }
24256
24257    #[test]
24258    fn pr_message_review_without_facts_falls_back_to_recorded_subjects() {
24259        let m = pr_message_with(&review_state(&["feat: x", "fix: y"]), 'A', None);
24260        assert_eq!(m.title, "feat: x");
24261        assert!(m.body.contains("- fix: y\n"), "{}", m.body);
24262        assert!(!m.body.contains("Diff stat"), "{}", m.body);
24263        assert!(!m.body.contains("no task statement"), "{}", m.body);
24264    }
24265
24266    #[test]
24267    fn pr_message_review_titles_from_the_branch_name_when_subjects_are_unusable() {
24268        let mut state = review_state(&["日本語の件名"]);
24269        state.candidates[0].branch = "fix/macos-login-path".to_owned();
24270        assert_eq!(pr_message(&state, 'A').title, "fix/macos-login-path");
24271        state.candidates[0].branch = "機能/ログイン".to_owned();
24272        assert!(
24273            pr_message(&state, 'A')
24274                .title
24275                .starts_with("chore: land candidate A")
24276        );
24277    }
24278
24279    #[test]
24280    fn pr_message_review_fixes_survive_a_clean_final_round() {
24281        let mut state = review_state(&["feat: x"]);
24282        state.reviews = vec![
24283            round_with_notes(1, Some("handled the PATH case")),
24284            round_with_notes(2, None),
24285        ];
24286        let body = pr_message(&state, 'A').body;
24287        assert!(
24288            body.contains("## Review rounds") && !body.contains("handled the PATH case"),
24289            "{body}"
24290        );
24291        assert!(body.contains("### Round 1"), "{body}");
24292
24293        state.reviews = vec![
24294            round_with_notes(1, Some("first fix")),
24295            round_with_notes(2, Some("")),
24296            round_with_notes(3, Some("second fix")),
24297            round_with_notes(4, None),
24298        ];
24299        let body = pr_message(&state, 'A').body;
24300        assert!(
24301            body.contains("### Round 1") && !body.contains("first fix"),
24302            "{body}"
24303        );
24304        assert!(
24305            body.contains("### Round 3") && !body.contains("second fix"),
24306            "{body}"
24307        );
24308        assert!(body.contains("### Round 2"), "{body}");
24309    }
24310
24311    const FINAL: &str = "abcdef1234567890";
24312
24313    fn passing_round(round: usize, verified: Option<&str>) -> ReviewRound {
24314        let mut r = round_with_notes(round, None);
24315        r.verified_head = verified.map(str::to_owned);
24316        r
24317    }
24318
24319    fn ok_gate(state: &mut RunState, head: Option<&str>) {
24320        state.gate = vec![CommandOutcome {
24321            command: "gate".to_owned(),
24322            code: Some(0),
24323            output_tail: String::new(),
24324            duration_ms: 0,
24325            resource_blocked: false,
24326            ..Default::default()
24327        }];
24328        state.gate_ran = true;
24329        state.gate_head = head.map(str::to_owned);
24330    }
24331
24332    fn body_at(state: &RunState) -> String {
24333        pr_message_raw(
24334            state,
24335            'A',
24336            None,
24337            crate::pr_outcome::FinalHead::At(FINAL),
24338            ChangeNote::NotAsked,
24339        )
24340        .body
24341    }
24342
24343    const SANDBOXED: &str = "Handled the PATH case.\nI could not commit because of the sandbox. HTTP tests could not run in the sandbox.";
24344
24345    #[test]
24346    fn rescued_commit_and_later_verification_override_the_fixers_limits() {
24347        let mut state = review_state(&["feat: x"]);
24348        state.reviews = vec![
24349            round_with_notes(1, Some(SANDBOXED)),
24350            passing_round(2, Some(FINAL)),
24351        ];
24352        ok_gate(&mut state, Some(FINAL));
24353        let body = body_at(&state);
24354        assert!(!body.contains("Handled the PATH case."), "{body}");
24355        assert!(!body.contains("could not commit"), "{body}");
24356        assert!(!body.contains("could not run"), "{body}");
24357        assert!(
24358            body.contains("The fix is committed on the branch"),
24359            "{body}"
24360        );
24361        assert!(!body.contains("sandbox"), "{body}");
24362        assert!(
24363            body.contains("Tests (`verify.e2e`): passed on the final commit"),
24364            "{body}"
24365        );
24366        assert!(
24367            body.contains("Gate (`verify.gate`): passed on the final commit"),
24368            "{body}"
24369        );
24370        // The raw report is untouched in the record.
24371        assert!(
24372            state.reviews[0]
24373                .fix
24374                .as_ref()
24375                .unwrap()
24376                .notes
24377                .contains("could not commit")
24378        );
24379    }
24380
24381    #[test]
24382    fn unresolved_commit_and_test_limits_stay_and_nothing_claims_success() {
24383        let mut state = review_state(&["feat: x"]);
24384        let mut r1 = round_with_notes(1, Some(SANDBOXED));
24385        r1.fix.as_mut().unwrap().committed = false;
24386        let mut r2 = passing_round(2, Some(FINAL));
24387        r2.e2e[0].code = Some(1);
24388        state.reviews = vec![r1, r2];
24389        let body = body_at(&state);
24390        assert!(!body.contains("could not commit"), "{body}");
24391        assert!(!body.contains("could not run"), "{body}");
24392        assert!(body.contains("This round produced no commit"), "{body}");
24393        assert!(body.contains("Tests (`verify.e2e`): FAILED"), "{body}");
24394        assert!(body.contains("Gate (`verify.gate`): not run"), "{body}");
24395        assert!(!body.contains("passed"), "{body}");
24396    }
24397
24398    #[test]
24399    fn verification_on_an_earlier_commit_does_not_supersede_test_limits() {
24400        let mut state = review_state(&["feat: x"]);
24401        state.reviews = vec![
24402            round_with_notes(1, Some(SANDBOXED)),
24403            passing_round(2, Some("0123456789abcdef")),
24404        ];
24405        ok_gate(&mut state, Some("0123456789abcdef"));
24406        let body = body_at(&state);
24407        assert!(!body.contains("HTTP tests could not run"), "{body}");
24408        // The commit claim is still settled by the structured record.
24409        assert!(!body.contains("could not commit"), "{body}");
24410        assert!(
24411            body.contains("passed on an earlier commit (`0123456`)"),
24412            "{body}"
24413        );
24414        assert!(!body.contains("passed on the final commit"), "{body}");
24415
24416        // A gate recorded before `gate_head` existed is "not recorded".
24417        ok_gate(&mut state, None);
24418        let body = body_at(&state);
24419        assert!(
24420            body.contains("passed on a commit that was not recorded"),
24421            "{body}"
24422        );
24423    }
24424
24425    #[test]
24426    fn pr_message_implementation_run_keeps_its_shape_and_marker() {
24427        let state = state_with_summary(
24428            "add retries to the client",
24429            "TITLE: feat: retries\n\nDid it.",
24430        );
24431        let m = pr_message_with(&state, 'A', Some(&facts(&[("x", "")], "s")));
24432        assert_eq!(m.title, "feat: retries");
24433        assert!(
24434            m.body.contains("<summary>Original task</summary>"),
24435            "{}",
24436            m.body
24437        );
24438        assert!(!m.body.contains("Commits under review"), "{}", m.body);
24439        assert!(
24440            m.body
24441                .ends_with(&format!("magi:run/{} magi:candidate-a\n", state.id)),
24442            "{}",
24443            m.body
24444        );
24445    }
24446
24447    #[test]
24448    fn pr_message_review_bounds_a_long_english_subject() {
24449        let long = format!("feat: {}", "word ".repeat(100));
24450        let m = pr_message(&review_state(&[&long]), 'A');
24451        assert!(m.title.starts_with("feat: word"), "{}", m.title);
24452        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
24453    }
24454
24455    #[test]
24456    fn pr_message_implementation_run_is_unchanged_by_review_support() {
24457        let state = state_with_summary("add retries\n\ndetails", "- did some things");
24458        let m = pr_message(&state, 'A');
24459        assert_eq!(m.title, "add retries");
24460        assert!(m.body.contains("<summary>Original task</summary>"));
24461        assert!(!m.body.contains("Commits under review"));
24462        assert_eq!(landing_subject_source(&state), state.instruction);
24463    }
24464
24465    #[test]
24466    fn review_run_squash_subject_is_the_change_not_the_prompt() {
24467        let state = review_state(&["feat: the change", "fix: typo"]);
24468        let source = landing_subject_source(&state);
24469        assert_eq!(land::merge_subject("", &source), "feat: the change");
24470        assert_eq!(
24471            land::merge_subject("magi: candidate A (uncommitted work)", &source),
24472            "feat: the change"
24473        );
24474        // An operator's rename still wins.
24475        assert_eq!(
24476            land::merge_subject("feat: renamed by hand", &source),
24477            "feat: renamed by hand"
24478        );
24479        let blank = review_state(&["日本語"]);
24480        assert!(
24481            land::merge_subject("", &landing_subject_source(&blank)).starts_with("chore: land")
24482        );
24483    }
24484
24485    #[test]
24486    fn review_run_drops_a_prompt_shaped_pr_title_at_landing() {
24487        let state = review_state(&["feat: the change"]);
24488        let source = landing_subject_source(&state);
24489        let old = "Review the work already on branch `magi/x/A`. There is no task statement";
24490        assert_eq!(
24491            land::merge_subject(landing_title(&state, old), &source),
24492            "feat: the change"
24493        );
24494        assert_eq!(landing_title(&state, "feat: renamed"), "feat: renamed");
24495        let task = state_with_summary("add retries", "");
24496        assert_eq!(landing_title(&task, old), old);
24497    }
24498
24499    #[test]
24500    fn pr_message_describes_the_change_not_the_task() {
24501        let state = state_with_summary(
24502            "今回やってほしいこと: results projector を直す",
24503            "TITLE: fix(web): batch the runs list reads\n- reads run.json once\n- risk: none",
24504        );
24505        let m = pr_message(&state, 'A');
24506        assert_eq!(m.title, "fix(web): batch the runs list reads");
24507        assert!(
24508            m.body.starts_with("## Summary\n\n- reads run.json once"),
24509            "{}",
24510            m.body
24511        );
24512        assert!(!m.body.contains("TITLE:"), "{}", m.body);
24513        let task_at = m.body.find("今回やってほしいこと").unwrap();
24514        let details_at = m.body.find("<details>").unwrap();
24515        assert!(
24516            details_at < task_at,
24517            "the task lives inside <details>: {}",
24518            m.body
24519        );
24520        assert!(m.body.contains(&format!("magi:run/{}", state.id)));
24521        assert!(m.body.contains("magi:candidate-a"));
24522    }
24523
24524    #[test]
24525    fn pr_message_falls_back_to_the_task_without_a_title_line() {
24526        let state = state_with_summary("\n\nadd retries\n\ndetails", "- did some things");
24527        let m = pr_message(&state, 'A');
24528        assert_eq!(m.title, "add retries");
24529        assert!(
24530            m.body.contains("## Summary\n\n- did some things"),
24531            "{}",
24532            m.body
24533        );
24534
24535        let none = RunState::new(
24536            PathBuf::from("/repo"),
24537            "main".to_owned(),
24538            "abc1234".to_owned(),
24539            "add retries".to_owned(),
24540            Config::default(),
24541        );
24542        let m = pr_message(&none, 'A');
24543        assert_eq!(m.title, "add retries");
24544        assert!(!m.body.contains("## Summary"), "{}", m.body);
24545    }
24546
24547    #[test]
24548    fn pr_message_refuses_the_candidate_commit_subject() {
24549        for bad in [
24550            "TITLE: magi: candidate A (uncommitted work)",
24551            "TITLE: chore: stuff (uncommitted work)",
24552            "TITLE:   ",
24553        ] {
24554            let state = state_with_summary("add retries", bad);
24555            assert_eq!(pr_message(&state, 'A').title, "add retries", "{bad}");
24556        }
24557    }
24558
24559    #[test]
24560    fn pr_message_bounds_a_very_long_task_and_title() {
24561        let long = format!("fix the thing 🎉 {}", "x".repeat(5000));
24562        let state = state_with_summary(&long, "- nothing");
24563        let m = pr_message(&state, 'A');
24564        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
24565        assert!(!m.title.contains('\n'));
24566
24567        let state = state_with_summary("task", &format!("TITLE: feat: {}", "y".repeat(5000)));
24568        let m = pr_message(&state, 'A');
24569        assert!(m.title.starts_with("feat: "));
24570        assert!(m.title.chars().count() <= PR_TITLE_MAX, "{}", m.title);
24571        assert_eq!(m.commit_message().lines().next(), Some(m.title.as_str()));
24572    }
24573
24574    fn long_title_of(instruction: &str) -> String {
24575        pr_message(&state_with_summary(instruction, "- nothing"), 'A').title
24576    }
24577
24578    #[test]
24579    fn pr_message_cuts_a_long_english_line_at_its_first_sentence() {
24580        let first = "Make the landing path keep a readable title for long tasks";
24581        let line = format!(
24582            "{first}. {}",
24583            "And then keep going with more words ".repeat(20)
24584        );
24585        let t = long_title_of(&line);
24586        assert_eq!(t, first);
24587        assert!(!t.starts_with("chore: land"));
24588    }
24589
24590    #[test]
24591    fn pr_message_cuts_a_sentenceless_long_line_at_a_word() {
24592        let line = "word ".repeat(200);
24593        let t = long_title_of(&line);
24594        assert!(t.ends_with("word..."), "{t}");
24595        assert!(t.is_ascii() && t.chars().count() <= PR_TITLE_MAX, "{t}");
24596    }
24597
24598    #[test]
24599    fn pr_message_long_non_english_or_letterless_line_is_neutral() {
24600        for line in ["日本語のタスク ".repeat(80), "1234 ".repeat(100)] {
24601            assert!(long_title_of(&line).starts_with("chore: land"), "{line}");
24602        }
24603    }
24604
24605    #[test]
24606    fn pr_message_keeps_a_japanese_title_when_github_language_is_japanese() {
24607        let mut state = state_with_summary("再試行を追加する", "- nothing");
24608        assert!(pr_message(&state, 'A').title.starts_with("chore: land"));
24609        state.config.graph.github_language = "ja".into();
24610        assert_eq!(pr_message(&state, 'A').title, "再試行を追加する");
24611    }
24612
24613    #[test]
24614    fn pr_message_title_limit_is_exact() {
24615        let at = "a".repeat(PR_TITLE_MAX);
24616        assert_eq!(long_title_of(&at), at);
24617        let over = long_title_of(&"a".repeat(PR_TITLE_MAX + 1));
24618        assert!(over.ends_with("..."), "{over}");
24619        assert_eq!(over.chars().count(), PR_TITLE_MAX);
24620    }
24621
24622    #[test]
24623    fn pr_message_judges_the_kept_text_not_what_follows_the_cut() {
24624        let line = format!("{} \u{2014} tail", "alpha beta ".repeat(40));
24625        let t = long_title_of(&line);
24626        assert!(t.ends_with("..."), "{t}");
24627        assert!(t.is_ascii(), "{t}");
24628    }
24629
24630    #[test]
24631    fn pr_message_sentence_cut_skips_abbreviations_and_decimals() {
24632        let line = format!(
24633            "Support several shells, e.g. bash and zsh, at version 1.5 or newer when it matters {}",
24634            "plus more filler words ".repeat(20)
24635        );
24636        let t = long_title_of(&line);
24637        assert!(t.contains("e.g. bash") && t.contains("1.5 or newer"), "{t}");
24638    }
24639
24640    #[test]
24641    fn pr_message_long_title_survives_a_blank_first_line_and_the_squash_subject() {
24642        let line = format!("\n\n# {}", "title words ".repeat(40));
24643        let state = state_with_summary(&line, "- nothing");
24644        let m = pr_message(&state, 'A');
24645        assert!(m.title.starts_with("title words"), "{}", m.title);
24646        assert_eq!(
24647            land::merge_subject(&m.title, &landing_subject_source(&state)),
24648            m.title
24649        );
24650        // An operator's rename wins untouched.
24651        assert_eq!(
24652            land::merge_subject("feat: renamed by hand", &landing_subject_source(&state)),
24653            "feat: renamed by hand"
24654        );
24655    }
24656
24657    #[tokio::test]
24658    async fn github_text_rewrite_is_bounded_and_falls_back() {
24659        crate::run::pin_test_home();
24660        for (reply, accepted) in [
24661            (
24662                "TITLE: fix: retries\nAdd retries for failed requests.",
24663                true,
24664            ),
24665            (
24666                "TITLE: fix: retries\n日本語の説明をもう一度書きます。",
24667                false,
24668            ),
24669            (
24670                "TITLE: fix: retries\nAdd retries for failed requests. Use token=secret",
24671                true,
24672            ),
24673            (
24674                "TITLE: fix: retries\nAdd retries for failed requests. Example: password=\"prefix\\\"secret tail\"",
24675                true,
24676            ),
24677            (
24678                "TITLE: fix: retries token=secret\nAdd retries for failed requests. Example: password=\"日本語の秘密secret\"",
24679                true,
24680            ),
24681            (
24682                "TITLE: fix: retries\n日本語の説明です。 token=secret",
24683                false,
24684            ),
24685            ("TITLE: fix: retries\n", false),
24686        ] {
24687            let dir = tempfile::tempdir().unwrap();
24688            let mut runner = runner_at(RunStatus::Gating);
24689            runner.state = state_with_summary(
24690                "add retries",
24691                "TITLE: fix: retries\n日本語の説明を書きます。",
24692            );
24693            runner.state.repo = dir.path().to_owned();
24694            runner.state.candidates[0].worktree = dir.path().to_owned();
24695            let mut author = spec("alpha");
24696            author.command = vec![
24697                "sh".into(),
24698                "-c".into(),
24699                "printf '%s' \"$REWRITE_REPLY\"".into(),
24700            ];
24701            author.env.insert("REWRITE_REPLY".into(), reply.into());
24702            runner.state.config.agents = vec![author];
24703            seed_public_summary(&mut runner);
24704            let winner = runner.state.candidates[0].clone();
24705            let first = runner
24706                .guarded_pr_message(&winner, None, true)
24707                .await
24708                .unwrap();
24709            let message = if accepted {
24710                first.expect("a passing rewrite never asks")
24711            } else {
24712                // Withheld: the run parks on a question and posts nothing yet.
24713                assert!(first.is_none());
24714                assert!(runner.state.parked);
24715                let store = ask::Questions::open();
24716                let asked: Vec<_> = store
24717                    .list()
24718                    .into_iter()
24719                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
24720                    .collect();
24721                assert_eq!(asked.len(), 1);
24722                assert!(!asked[0].detail.contains("secret"));
24723                let rewrite = runner.state.github_text.as_ref().unwrap().rewrite.as_ref();
24724                assert_eq!(rewrite.is_some(), !reply.ends_with('\n'));
24725                assert_eq!(
24726                    asked[0]
24727                        .choices
24728                        .contains(&crate::github_text::USE_REWRITE.to_owned()),
24729                    rewrite.is_some()
24730                );
24731                // Silence: the question lapses and the neutral text is used,
24732                // without a second rewrite call or a second question.
24733                store
24734                    .update(&asked[0].id, |q| {
24735                        q.abandon("test");
24736                        Ok(())
24737                    })
24738                    .unwrap();
24739                let again = runner
24740                    .guarded_pr_message(&winner, None, true)
24741                    .await
24742                    .unwrap()
24743                    .expect("an abandoned question falls back");
24744                let n = store
24745                    .list()
24746                    .into_iter()
24747                    .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
24748                    .count();
24749                assert_eq!(n, 1, "asked once per rejected text");
24750                again
24751            };
24752            assert!(crate::github_text::check(&message.title, &message.body).is_empty());
24753            assert!(!message.body.contains("secret"));
24754            assert!(!message.body.contains("prefix"));
24755            assert!(!message.title.contains("secret"));
24756            assert_eq!(
24757                message.body.contains("Add retries for failed requests."),
24758                accepted
24759            );
24760            assert_eq!(
24761                runner.state.seats["github-text-rewrite"].turns, 1,
24762                "only one rewrite invocation"
24763            );
24764            assert!(runner.state.events.iter().any(|e| e.node == "github-text"));
24765            if accepted {
24766                assert!(runner.state.github_text.is_none());
24767                assert!(!runner.state.parked);
24768                assert!(!message.body.contains(crate::github_text::NEUTRAL_BODY));
24769                assert!(message.body.contains("## Final verification"));
24770                assert!(message.body.contains("Evidence: final diff"));
24771                assert!(
24772                    message
24773                        .body
24774                        .contains(&format!("magi:run/{}", runner.state.id))
24775                );
24776            }
24777            if !accepted {
24778                assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
24779                assert!(
24780                    message
24781                        .body
24782                        .contains(&format!("magi:run/{}", runner.state.id))
24783                );
24784            }
24785        }
24786    }
24787
24788    fn scripted(id: &str, reply: &str) -> AgentSpec {
24789        let mut a = spec(id);
24790        a.command = vec![
24791            "sh".into(),
24792            "-c".into(),
24793            "printf '%s' \"$REWRITE_REPLY\"".into(),
24794        ];
24795        a.env.insert("REWRITE_REPLY".into(), reply.into());
24796        a
24797    }
24798
24799    const JA_SUMMARY: &str = "TITLE: fix: retries\n日本語の説明を書きます。";
24800    const EN_REWRITE: &str = "TITLE: fix: retries\nAdd retries in `src/net.rs` for 3 failed requests.\n\n<details>kept</details>";
24801
24802    /// Gate tests inject generated public output, not internal reports.
24803    fn seed_public_summary(runner: &mut Runner) {
24804        let repo = &runner.state.repo;
24805        let g = |args: &[&str]| {
24806            let out = std::process::Command::new("git")
24807                .args(args)
24808                .current_dir(repo)
24809                .quiet()
24810                .output()
24811                .unwrap();
24812            assert!(out.status.success(), "git {args:?}");
24813            String::from_utf8_lossy(&out.stdout).trim().to_owned()
24814        };
24815        g(&["init", "-q", "-b", "main"]);
24816        g(&[
24817            "-c",
24818            "user.name=Test",
24819            "-c",
24820            "user.email=test@example.invalid",
24821            "commit",
24822            "-q",
24823            "--allow-empty",
24824            "-m",
24825            "feat: fixture",
24826        ]);
24827        let head = g(&["rev-parse", "HEAD"]);
24828        g(&["update-ref", "refs/remotes/origin/main", &head]);
24829        let evidence = crate::pr_outcome::summary_evidence(
24830            &runner.state,
24831            crate::pr_outcome::FinalHead::At(&head),
24832        );
24833        let generated = &runner.state.candidates[0].summary;
24834        runner.state.change_summary = Some(crate::run::ChangeSummary {
24835            base: head.clone(),
24836            head,
24837            evidence: crate::pr_outcome::summary_fingerprint(&runner.state, &evidence),
24838            title: summary_title(generated).unwrap(),
24839            body: summary_without_title(generated),
24840        });
24841    }
24842
24843    fn rewrite_runner(dir: &Path, review_only: bool, agents: Vec<AgentSpec>) -> Runner {
24844        let mut runner = runner_at(RunStatus::Gating);
24845        runner.state = state_with_summary("add retries", JA_SUMMARY);
24846        if review_only {
24847            runner.state.candidates[0].agent = EXISTING_BRANCH.to_owned();
24848        }
24849        runner.state.repo = dir.to_owned();
24850        runner.state.candidates[0].worktree = dir.to_owned();
24851        runner.state.config.agents = agents;
24852        seed_public_summary(&mut runner);
24853        runner
24854    }
24855
24856    fn gate_questions(runner: &Runner) -> usize {
24857        ask::Questions::open()
24858            .list()
24859            .into_iter()
24860            .filter(|q| q.run == runner.state.id && q.node == crate::github_text::ASK_NODE)
24861            .count()
24862    }
24863
24864    #[tokio::test]
24865    async fn review_only_description_is_rewritten_by_the_language_judge_role() {
24866        crate::run::pin_test_home();
24867        let dir = tempfile::tempdir().unwrap();
24868        let mut runner = rewrite_runner(
24869            dir.path(),
24870            true,
24871            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
24872        );
24873        runner.state.config.roles.language_judge =
24874            Some(crate::config::AgentChoice::Chain(vec!["beta".into()]));
24875        let winner = runner.state.candidates[0].clone();
24876        let msg = runner
24877            .guarded_pr_message(&winner, None, true)
24878            .await
24879            .unwrap()
24880            .expect("an English rewrite posts without asking");
24881        assert!(msg.body.contains("`src/net.rs` for 3 failed requests"));
24882        assert!(msg.body.contains("<details>kept</details>"));
24883        assert!(msg.body.contains(&format!("magi:run/{}", runner.state.id)));
24884        assert_eq!(gate_questions(&runner), 0);
24885        assert!(runner.state.github_text.is_none());
24886        assert!(!runner.state.seats.contains_key("impl-A"));
24887        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24888    }
24889
24890    #[tokio::test]
24891    async fn rewrite_without_an_implementer_session_uses_the_role_not_the_seat() {
24892        crate::run::pin_test_home();
24893        let dir = tempfile::tempdir().unwrap();
24894        let mut runner = rewrite_runner(
24895            dir.path(),
24896            false,
24897            vec![scripted("alpha", "nope"), scripted("beta", EN_REWRITE)],
24898        );
24899        runner.state.config.roles.language_judge =
24900            Some(crate::config::AgentChoice::One("beta".into()));
24901        runner.state.seats.insert(
24902            "impl-A".into(),
24903            SeatState::new("impl-A", "alpha", runner.state.seed),
24904        );
24905        let winner = runner.state.candidates[0].clone();
24906        let msg = runner
24907            .guarded_pr_message(&winner, None, true)
24908            .await
24909            .unwrap()
24910            .expect("rewritten");
24911        assert!(msg.body.contains("<details>kept</details>"));
24912        assert_eq!(runner.state.seats["impl-A"].turns, 0);
24913        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24914        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
24915    }
24916
24917    #[tokio::test]
24918    async fn rewrite_reuses_a_resumable_implementer_session() {
24919        crate::run::pin_test_home();
24920        let dir = tempfile::tempdir().unwrap();
24921        let mut runner = rewrite_runner(
24922            dir.path(),
24923            false,
24924            vec![scripted("alpha", EN_REWRITE), scripted("beta", "nope")],
24925        );
24926        runner.state.config.roles.language_judge =
24927            Some(crate::config::AgentChoice::One("beta".into()));
24928        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
24929        seat.turns = 1;
24930        runner.state.seats.insert("impl-A".into(), seat);
24931        let winner = runner.state.candidates[0].clone();
24932        runner
24933            .guarded_pr_message(&winner, None, true)
24934            .await
24935            .unwrap()
24936            .expect("rewritten");
24937        assert_eq!(runner.state.seats["impl-A"].turns, 2);
24938        assert!(!runner.state.seats.contains_key("github-text-rewrite"));
24939    }
24940
24941    #[tokio::test]
24942    async fn a_failing_resumed_implementer_falls_back_to_the_language_judge_role() {
24943        // Runs 7861 / 344a: the winning implementer (agy) had a resumable
24944        // session, was out of quota, and nothing else was asked.
24945        crate::run::pin_test_home();
24946        let dir = tempfile::tempdir().unwrap();
24947        let mut exhausted = spec("alpha");
24948        exhausted.command = vec!["false".into()];
24949        let mut runner = rewrite_runner(
24950            dir.path(),
24951            false,
24952            vec![exhausted, scripted("beta", EN_REWRITE)],
24953        );
24954        // The implementer's own agent is in the role too: it is not asked twice.
24955        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
24956            "alpha".into(),
24957            "beta".into(),
24958        ]));
24959        let mut seat = SeatState::new("impl-A", "alpha", runner.state.seed);
24960        seat.turns = 1;
24961        runner.state.seats.insert("impl-A".into(), seat);
24962        let winner = runner.state.candidates[0].clone();
24963        let msg = runner
24964            .guarded_pr_message(&winner, None, true)
24965            .await
24966            .unwrap()
24967            .expect("the role rewrites after the implementer fails");
24968        assert!(msg.body.contains("`src/net.rs`"));
24969        assert_eq!(
24970            runner.state.seats["impl-A"].turns, 2,
24971            "the implementer was tried once"
24972        );
24973        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "beta");
24974        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
24975    }
24976
24977    #[tokio::test]
24978    async fn rewrite_chain_advances_past_a_failing_or_unparsable_agent() {
24979        crate::run::pin_test_home();
24980        let dir = tempfile::tempdir().unwrap();
24981        let mut broken = spec("bad");
24982        broken.command = vec!["false".into()];
24983        let mut runner = rewrite_runner(
24984            dir.path(),
24985            true,
24986            vec![
24987                broken,
24988                scripted("noformat", "Add retries."),
24989                scripted("good", EN_REWRITE),
24990            ],
24991        );
24992        runner.state.config.roles.language_judge = Some(crate::config::AgentChoice::Chain(vec![
24993            "bad".into(),
24994            "noformat".into(),
24995            "good".into(),
24996        ]));
24997        let winner = runner.state.candidates[0].clone();
24998        let msg = runner
24999            .guarded_pr_message(&winner, None, true)
25000            .await
25001            .unwrap()
25002            .expect("the third agent rewrites");
25003        assert!(msg.body.contains("`src/net.rs`"));
25004        assert_eq!(runner.state.seats["github-text-rewrite"].agent, "good");
25005        assert!(runner.state.handovers.is_empty(), "no handover is recorded");
25006    }
25007
25008    #[tokio::test]
25009    async fn unsuccessful_review_only_rewrites_ask_the_owner_and_never_post_the_original() {
25010        crate::run::pin_test_home();
25011        // (agents, role): still Japanese; no TITLE; nothing resolvable.
25012        for (agents, role, saved) in [
25013            (
25014                vec![scripted("beta", "TITLE: fix: retries\n日本語の説明です。")],
25015                Some("beta"),
25016                true,
25017            ),
25018            (vec![scripted("beta", "Add retries.")], Some("beta"), false),
25019            (Vec::new(), None, false),
25020        ] {
25021            let dir = tempfile::tempdir().unwrap();
25022            let mut runner = rewrite_runner(dir.path(), true, agents);
25023            runner.state.config.roles.language_judge =
25024                role.map(|r| crate::config::AgentChoice::One(r.into()));
25025            let winner = runner.state.candidates[0].clone();
25026            let first = runner
25027                .guarded_pr_message(&winner, None, true)
25028                .await
25029                .unwrap();
25030            assert!(first.is_none(), "withheld text parks the run");
25031            assert!(runner.state.parked);
25032            assert_eq!(gate_questions(&runner), 1);
25033            let g = runner.state.github_text.as_ref().unwrap();
25034            assert_eq!(g.rewrite.is_some(), saved);
25035            assert!(g.choice.is_none() && !g.resolved, "nothing posts unasked");
25036        }
25037    }
25038
25039    #[tokio::test]
25040    async fn github_text_rejected_rewrite_survives_retry_and_posts_verbatim() {
25041        crate::run::pin_test_home();
25042        let dir = tempfile::tempdir().unwrap();
25043        let mut runner = runner_at(RunStatus::Gating);
25044        runner.state =
25045            state_with_summary("add retries", "TITLE: 日本語のタイトル\n日本語の説明です。");
25046        runner.state.repo = dir.path().to_owned();
25047        runner.state.candidates[0].worktree = dir.path().to_owned();
25048        let mut author = spec("alpha");
25049        author.command = vec![
25050            "sh".into(),
25051            "-c".into(),
25052            "printf '%s' \"$REWRITE_REPLY\"".into(),
25053        ];
25054        author.env.insert(
25055            "REWRITE_REPLY".into(),
25056            format!(
25057                "TITLE: fix: rewritten title\n{}\n日本語の説明です。",
25058                "English sentence. ".repeat(600)
25059            ),
25060        );
25061        runner.state.config.agents = vec![author];
25062        seed_public_summary(&mut runner);
25063        let winner = runner.state.candidates[0].clone();
25064        assert!(
25065            runner
25066                .guarded_pr_message(&winner, None, true)
25067                .await
25068                .unwrap()
25069                .is_none()
25070        );
25071        let record = runner.state.github_text.clone().unwrap();
25072        let rewrite = record.rewrite.clone().unwrap();
25073        assert_eq!(rewrite.failed, ["body-language"]);
25074        assert!(
25075            rewrite
25076                .body
25077                .ends_with(&format!("magi:run/{}", runner.state.id))
25078        );
25079        let store = ask::Questions::open();
25080        let q = store.get(record.question.as_ref().unwrap()).unwrap();
25081        assert!(
25082            q.choices
25083                .contains(&crate::github_text::USE_REWRITE.to_owned())
25084        );
25085        for label in [
25086            "ORIGINAL",
25087            "FALLBACK",
25088            "REWRITE",
25089            "Rules still failed: body-language",
25090            "truncated",
25091        ] {
25092            assert!(q.detail.contains(label), "{label}");
25093        }
25094        let artifact = std::fs::read_to_string(crate::run::artifact_path(
25095            &runner.state,
25096            &crate::github_text::artifact_name(&record.fingerprint),
25097        ))
25098        .unwrap();
25099        assert!(artifact.contains(&rewrite.title) && artifact.contains(&rewrite.body));
25100        // Restart from serialized state, then retry after a bad owner title.
25101        runner.state =
25102            serde_json::from_str(&serde_json::to_string(&runner.state).unwrap()).unwrap();
25103        store
25104            .update(&q.id, |q| {
25105                q.say("まだ日本語")?;
25106                q.answer(ask::Answer::Choice(crate::github_text::USE_MY_TEXT.into()))
25107            })
25108            .unwrap();
25109        assert!(
25110            runner
25111                .guarded_pr_message(&winner, None, true)
25112                .await
25113                .unwrap()
25114                .is_none()
25115        );
25116        let retry = runner.state.github_text.as_ref().unwrap();
25117        assert_eq!(retry.rewrite.as_ref(), Some(&rewrite));
25118        let q = store.get(retry.question.as_ref().unwrap()).unwrap();
25119        assert!(q.detail.contains("REWRITE") && q.detail.contains(&rewrite.title));
25120        assert!(
25121            q.posting_comparison
25122                .as_ref()
25123                .unwrap()
25124                .matches_detail(&q.detail)
25125        );
25126        store
25127            .update(&q.id, |q| {
25128                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
25129            })
25130            .unwrap();
25131        let message = runner
25132            .guarded_pr_message(&winner, None, true)
25133            .await
25134            .unwrap()
25135            .unwrap();
25136        assert_eq!(message.title, rewrite.title);
25137        assert_eq!(message.body, rewrite.body);
25138        assert_eq!(
25139            runner.state.github_text.as_ref().unwrap().choice,
25140            Some(GithubTextChoice::Rewrite)
25141        );
25142        let again = runner
25143            .guarded_pr_message(&winner, None, true)
25144            .await
25145            .unwrap()
25146            .unwrap();
25147        assert_eq!(again.title, message.title);
25148        assert_eq!(again.body, message.body);
25149        assert_eq!(runner.state.seats["github-text-rewrite"].turns, 1);
25150        assert!(
25151            !runner
25152                .state
25153                .events
25154                .iter()
25155                .any(|e| e.message.contains(&rewrite.title)
25156                    || e.message.contains("English sentence."))
25157        );
25158    }
25159
25160    #[tokio::test]
25161    async fn historical_posting_reply_never_expires_into_fallback() {
25162        crate::run::pin_test_home();
25163        let dir = tempfile::tempdir().unwrap();
25164        let mut runner = runner_at(RunStatus::Gating);
25165        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
25166        runner.state.repo = dir.path().to_owned();
25167        runner.state.candidates[0].worktree = dir.path().to_owned();
25168        seed_public_summary(&mut runner);
25169        let winner = runner.state.candidates[0].clone();
25170        assert!(
25171            runner
25172                .guarded_pr_message(&winner, None, true)
25173                .await
25174                .unwrap()
25175                .is_none()
25176        );
25177        let id = runner
25178            .state
25179            .github_text
25180            .as_ref()
25181            .unwrap()
25182            .question
25183            .clone()
25184            .unwrap();
25185        let store = ask::Questions::open();
25186        let mut q = store.get(&id).unwrap();
25187        q.asked_at = "2020-01-01T00:00:00Z".parse().unwrap();
25188        q.answer(ask::Answer::Choice(
25189            crate::github_text::POST_ORIGINAL.into(),
25190        ))
25191        .unwrap();
25192        q.answer_delivered = true;
25193        store.put(&mut q).unwrap();
25194        let source = std::fs::read(store.path_of(&id)).unwrap();
25195        let migration = crate::run::home().join("notifications/task-chat-migration-v1");
25196        std::fs::create_dir_all(&migration).unwrap();
25197        std::fs::write(
25198            migration.join("state.json"),
25199            serde_json::to_vec(&serde_json::json!({
25200                "schema": 1, "sources": [id], "pending": [id]
25201            }))
25202            .unwrap(),
25203        )
25204        .unwrap();
25205        for _ in 0..2 {
25206            assert!(
25207                runner
25208                    .guarded_pr_message(&winner, None, true)
25209                    .await
25210                    .unwrap()
25211                    .is_none()
25212            );
25213            assert!(!runner.state.github_text.as_ref().unwrap().resolved);
25214            assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
25215        }
25216        let home = crate::run::home();
25217        crate::task_chat::sweep(
25218            &crate::queue::Queue::at(home.join("queue")),
25219            &crate::talk::Talks::at(home.join("talks")),
25220            &store,
25221            &home,
25222        );
25223        let outbox = crate::task_inquiry::Outbox::at(&home);
25224        outbox
25225            .update_decision(&id, |d| {
25226                d.accept(&format!("decision: {}", crate::github_text::POST_ORIGINAL))?;
25227                d.source_answer_at = q.answered_at;
25228                Ok(true)
25229            })
25230            .unwrap();
25231        outbox
25232            .settle(
25233                &id,
25234                "owner-chat",
25235                "Owner confirms no publication remains necessary",
25236                None,
25237            )
25238            .unwrap();
25239        assert!(
25240            runner
25241                .guarded_pr_message(&winner, None, true)
25242                .await
25243                .unwrap()
25244                .is_none()
25245        );
25246        assert!(!runner.state.github_text.as_ref().unwrap().resolved);
25247        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), source);
25248    }
25249
25250    #[tokio::test]
25251    async fn github_text_rewrite_choice_without_saved_text_falls_back() {
25252        crate::run::pin_test_home();
25253        let dir = tempfile::tempdir().unwrap();
25254        let mut runner = runner_at(RunStatus::Gating);
25255        runner.state = state_with_summary("add retries", "TITLE: fix: retries\n日本語の説明です。");
25256        runner.state.repo = dir.path().to_owned();
25257        runner.state.candidates[0].worktree = dir.path().to_owned();
25258        seed_public_summary(&mut runner);
25259        let winner = runner.state.candidates[0].clone();
25260        assert!(
25261            runner
25262                .guarded_pr_message(&winner, None, true)
25263                .await
25264                .unwrap()
25265                .is_none()
25266        );
25267        let record = runner.state.github_text.as_ref().unwrap();
25268        assert!(record.rewrite.is_none());
25269        // Records written before the additive field deserialize with no rewrite.
25270        let mut old = serde_json::to_value(record).unwrap();
25271        old.as_object_mut().unwrap().remove("rewrite");
25272        let old: crate::run::GithubTextAsk = serde_json::from_value(old).unwrap();
25273        assert!(old.rewrite.is_none());
25274        let id = record.question.clone().unwrap();
25275        ask::Questions::open()
25276            .update(&id, |q| {
25277                q.choices.push(crate::github_text::USE_REWRITE.into());
25278                q.answer(ask::Answer::Choice(crate::github_text::USE_REWRITE.into()))
25279            })
25280            .unwrap();
25281        let message = runner
25282            .guarded_pr_message(&winner, None, true)
25283            .await
25284            .unwrap()
25285            .unwrap();
25286        assert!(message.body.contains(crate::github_text::NEUTRAL_BODY));
25287        assert_eq!(
25288            runner.state.github_text.as_ref().unwrap().choice,
25289            Some(GithubTextChoice::Fallback)
25290        );
25291    }
25292
25293    #[tokio::test]
25294    async fn withheld_title_takes_the_owner_replacement_and_rechecks_it() {
25295        crate::run::pin_test_home();
25296        let dir = tempfile::tempdir().unwrap();
25297        let mut runner = runner_at(RunStatus::Gating);
25298        runner.state = state_with_summary("add retries", "TITLE: 日本語のタイトル\nAdd retries.");
25299        runner.state.repo = dir.path().to_owned();
25300        runner.state.candidates[0].worktree = dir.path().to_owned();
25301        seed_public_summary(&mut runner);
25302        let winner = runner.state.candidates[0].clone();
25303        assert!(
25304            runner
25305                .guarded_pr_message(&winner, None, true)
25306                .await
25307                .unwrap()
25308                .is_none()
25309        );
25310        let store = ask::Questions::open();
25311        let find = |run: &str| {
25312            store
25313                .list()
25314                .into_iter()
25315                .find(|q| q.run == run && q.node == crate::github_text::ASK_NODE && q.status.open())
25316                .unwrap()
25317        };
25318        let run = runner.state.id.clone();
25319        let q = find(&run);
25320        let fp = runner
25321            .state
25322            .github_text
25323            .as_ref()
25324            .unwrap()
25325            .fingerprint
25326            .clone();
25327        let name = crate::github_text::artifact_name(&fp);
25328        let path = crate::run::artifact_path(&runner.state, &name);
25329        assert!(q.detail.contains(&path.display().to_string()));
25330        assert!(q.detail.contains("title-language: title"));
25331        let saved = std::fs::read_to_string(&path).expect("artifact written");
25332        assert!(saved.contains("日本語のタイトル"));
25333        assert!(q.cwd.is_none());
25334        assert_eq!(q.choices, ["use fallback", "post original", "use my text"]);
25335        // A bad replacement is refused and asked about once more.
25336        let say = |id: &str, text: &str, choice: &str| {
25337            store
25338                .update(id, |q| {
25339                    q.thread.push(ask::Turn {
25340                        who: ask::Who::Operator,
25341                        body: text.to_owned(),
25342                        at: jiff::Timestamp::now(),
25343                        note: None,
25344                    });
25345                    q.answer(ask::Answer::Choice(choice.to_owned()))
25346                })
25347                .unwrap();
25348        };
25349        say(&q.id, "まだ日本語", "use my text");
25350        assert!(
25351            runner
25352                .guarded_pr_message(&winner, None, true)
25353                .await
25354                .unwrap()
25355                .is_none()
25356        );
25357        let second = find(&run);
25358        assert_ne!(second.id, q.id);
25359        assert!(second.detail.contains("did not pass"));
25360        // The retry still compares the original text; the rejected
25361        // replacement is named by category only.
25362        assert!(second.detail.contains("日本語のタイトル"));
25363        assert!(!second.detail.contains("まだ日本語"));
25364        assert!(second.detail.contains(&path.display().to_string()));
25365        say(&second.id, "fix: retry failed requests", "use my text");
25366        let message = runner
25367            .guarded_pr_message(&winner, None, true)
25368            .await
25369            .unwrap()
25370            .expect("a vetted replacement is posted");
25371        assert_eq!(message.title, "fix: retry failed requests");
25372        assert_eq!(
25373            runner
25374                .state
25375                .github_text
25376                .as_ref()
25377                .unwrap()
25378                .chosen_title
25379                .as_deref(),
25380            Some("fix: retry failed requests")
25381        );
25382        assert!(runner.state.github_text.as_ref().unwrap().resolved);
25383        // Resumed again: the saved decision is applied, nothing is re-asked.
25384        let again = runner
25385            .guarded_pr_message(&winner, None, true)
25386            .await
25387            .unwrap()
25388            .unwrap();
25389        assert_eq!(again.title, message.title);
25390        assert_eq!(
25391            store
25392                .list()
25393                .into_iter()
25394                .filter(|q| q.run == run && q.node == crate::github_text::ASK_NODE)
25395                .count(),
25396            2
25397        );
25398    }
25399
25400    #[test]
25401    fn pr_message_magi_text_is_english_and_the_task_is_verbatim() {
25402        // What magi itself writes stays English under any configured language,
25403        // so a future localisation of these headings fails here. (The agents'
25404        // own text is also checked by the posting gate.)
25405        let mut state = state_with_summary(
25406            "add retries",
25407            "TITLE: fix(web): batch reads\n- reads run.json once",
25408        );
25409        state.config.graph.language = "ja".to_owned();
25410        let m = pr_message(&state, 'A');
25411        assert!(crate::github_text::check(&m.title, &m.body).is_empty());
25412        assert!(m.title.is_ascii() && m.body.is_ascii(), "{}", m.body);
25413
25414        // The task is the operator's own text: it goes in untouched, and the
25415        // fallback title (no summary) may be in its language too.
25416        let task = "今回やってほしいこと: results projector を直す";
25417        let mut state = state_with_summary(task, "- no title line");
25418        state.config.graph.language = "ja".to_owned();
25419        let m = pr_message(&state, 'A');
25420        assert_eq!(
25421            m.title,
25422            format!("chore: land candidate A of run {}", state.id)
25423        );
25424        assert!(
25425            m.body.contains(&format!(
25426                "<summary>Original task</summary>\n\n{task}\n\n</details>"
25427            )),
25428            "{}",
25429            m.body
25430        );
25431    }
25432
25433    #[test]
25434    fn pr_message_scrubs_home_paths_and_addresses() {
25435        let state = state_with_summary(
25436            "fix it in /Users/someone/src/x",
25437            "TITLE: fix(x): y\n- edited /home/someone/repo/src/a.rs on 10.1.2.3",
25438        );
25439        let m = pr_message(&state, 'A');
25440        for leak in ["/Users/someone", "/home/someone", "10.1.2.3"] {
25441            assert!(!m.body.contains(leak), "{}", m.body);
25442        }
25443        assert!(m.body.contains("~/repo/src/a.rs"), "{}", m.body);
25444    }
25445
25446    #[test]
25447    fn pr_message_survives_a_task_that_closes_details() {
25448        let state = state_with_summary("a </details> b", "TITLE: fix: x");
25449        let m = pr_message(&state, 'A');
25450        assert_eq!(m.body.matches("</details>").count(), 1, "{}", m.body);
25451    }
25452
25453    #[test]
25454    fn manual_squash_subject_cannot_break_out_of_its_quotes() {
25455        let cmd = manual_merge_command(
25456            MergeStyle::Squash,
25457            Path::new("/repo"),
25458            "b",
25459            "fix: \"quoted\" $(x) `y`\n\nbody",
25460        );
25461        assert!(cmd.ends_with("commit -m \"fix: quoted (x) y\""), "{cmd}");
25462    }
25463
25464    #[test]
25465    fn manual_merge_command_matches_the_configured_style() {
25466        let repo = Path::new("/repo");
25467        let message = "Merge magi run 0832 (candidate A)\n\nadd retries";
25468
25469        let merge = manual_merge_command(MergeStyle::Merge, repo, "magi/0832/A", message);
25470        assert_eq!(merge, "git -C /repo merge --no-ff magi/0832/A");
25471
25472        let squash = manual_merge_command(MergeStyle::Squash, repo, "magi/0832/A", message);
25473        assert_eq!(
25474            squash,
25475            "git -C /repo merge --squash magi/0832/A && git -C /repo commit -m \
25476             \"Merge magi run 0832 (candidate A)\""
25477        );
25478
25479        let rebase = manual_merge_command(MergeStyle::Rebase, repo, "magi/0832/A", message);
25480        assert_eq!(rebase, "git -C /repo merge --ff-only magi/0832/A");
25481    }
25482
25483    #[test]
25484    fn a_nudge_gets_a_quarter_of_the_budget() {
25485        // The judge and implement budgets magi ships with.
25486        assert_eq!(retry_budget(secs(1200), true), secs(300));
25487        assert_eq!(retry_budget(secs(3600), true), secs(900));
25488    }
25489
25490    #[test]
25491    fn a_resent_prompt_keeps_the_whole_budget() {
25492        // The seat kept no context, so the retry is the original job again and
25493        // shortening it would only guarantee a second failure.
25494        assert_eq!(retry_budget(secs(1200), false), secs(1200));
25495        assert_eq!(retry_budget(secs(60), false), secs(60));
25496    }
25497
25498    #[test]
25499    fn the_floor_never_exceeds_the_original_budget() {
25500        // A short configured timeout must not be *raised* by the floor: the
25501        // operator asked for a bound, and a retry may not outlast the attempt
25502        // it is retrying.
25503        assert_eq!(retry_budget(secs(60), true), secs(60));
25504        assert_eq!(retry_budget(secs(480), true), secs(120));
25505        assert_eq!(retry_budget(secs(0), true), secs(0));
25506    }
25507
25508    fn evidence(exit_code: Option<i32>) -> agent::CommandEvidence {
25509        agent::CommandEvidence {
25510            id: "item1".to_owned(),
25511            description: "cargo test".to_owned(),
25512            exit_code,
25513            result_summary: String::new(),
25514            source: "codex".to_owned(),
25515        }
25516    }
25517
25518    #[test]
25519    fn a_reply_with_no_commands_at_all_is_not_unconfirmed() {
25520        // No evidence is not the same fact as unconfirmed evidence: a
25521        // backend with no adapter, or a reply that ran no commands at all,
25522        // must not be misread as carrying a dangling job.
25523        assert!(!has_unconfirmed_command(&[]));
25524    }
25525
25526    #[test]
25527    fn a_command_with_a_real_exit_code_is_confirmed_whatever_its_value() {
25528        // Deliberately not a check on the exit code's *value*: a fixer
25529        // legitimately runs something that fails mid-iteration before it
25530        // succeeds, and that must never by itself reopen a valid report.
25531        assert!(!has_unconfirmed_command(&[evidence(Some(0))]));
25532        assert!(!has_unconfirmed_command(&[evidence(Some(1))]));
25533        assert!(!has_unconfirmed_command(&[
25534            evidence(Some(0)),
25535            evidence(Some(101))
25536        ]));
25537    }
25538
25539    #[test]
25540    fn one_command_with_no_readable_exit_code_is_enough_to_flag_the_reply() {
25541        assert!(has_unconfirmed_command(&[
25542            evidence(Some(0)),
25543            evidence(None)
25544        ]));
25545    }
25546
25547    fn evidence_with(
25548        description: &str,
25549        exit_code: Option<i32>,
25550        result_summary: &str,
25551    ) -> agent::CommandEvidence {
25552        agent::CommandEvidence {
25553            id: "item1".to_owned(),
25554            description: description.to_owned(),
25555            exit_code,
25556            result_summary: result_summary.to_owned(),
25557            source: "codex".to_owned(),
25558        }
25559    }
25560
25561    fn valid_noop_summary(commit: &str, test_name: &str) -> String {
25562        format!(
25563            r#"NO CHANGE NEEDED: {{"status":"already_satisfied","requirements":[{{"requirement":"requested fix already landed","satisfied":true,"evidence":["c1","c2"]}}],"checks":[{{"id":"c1","kind":"commit","target":"{commit}","method":"git merge-base --is-ancestor {commit} HEAD","observed":"exit 0; {commit} is on base","passed":true}},{{"id":"c2","kind":"test","target":"{test_name}","method":"cargo test --lib {test_name}","observed":"test result: ok. 1 passed; 0 failed","passed":true}}],"unresolved":[]}}"#
25564        )
25565    }
25566
25567    #[test]
25568    fn a_clean_usable_reply_with_the_marker_is_a_verified_claim() {
25569        let text = valid_noop_summary("b32cfc4", "retry_test");
25570        let claim = verified_noop_claim(true, &[], &text)
25571            .expect("valid structured report with no CommandEvidence must be accepted");
25572        assert!(claim.contains("b32cfc4"), "{claim}");
25573        assert!(claim.contains("retry_test"), "{claim}");
25574    }
25575
25576    #[test]
25577    fn operational_regression_and_legacy_noop_claims_are_rejected() {
25578        let regression = "NO CHANGE NEEDED: Not established. No source changes, commit, or reproduction checks were completed. The reported Git configuration lock contention remains unresolved.";
25579        assert!(verified_noop_claim(true, &[], regression).is_none());
25580        let err = evaluate_noop_claim(true, &[], regression).unwrap_err();
25581        assert!(err.contains("single JSON object"), "{err}");
25582
25583        let legacy = "NO CHANGE NEEDED: already fixed by b32cfc4, on main.";
25584        assert!(verified_noop_claim(true, &[], legacy).is_none());
25585    }
25586
25587    #[test]
25588    fn an_unusable_reply_never_earns_the_benefit_of_the_doubt() {
25589        // A timeout or a bad exit code reads as the ordinary loss it is,
25590        // whatever the reply's own structured JSON claims.
25591        let text = valid_noop_summary("b32cfc4", "retry_test");
25592        assert!(verified_noop_claim(false, &[], &text).is_none());
25593    }
25594
25595    #[test]
25596    fn an_unconfirmed_command_disqualifies_the_claim_even_on_a_usable_reply() {
25597        let text = valid_noop_summary("b32cfc4", "retry_test");
25598        assert!(verified_noop_claim(true, &[evidence(None)], &text).is_none());
25599        // A matching confirmed command alongside the marker is fine.
25600        assert!(
25601            verified_noop_claim(
25602                true,
25603                &[evidence_with(
25604                    "cargo test --lib retry_test",
25605                    Some(0),
25606                    "1 passed"
25607                )],
25608                &text
25609            )
25610            .is_some()
25611        );
25612    }
25613
25614    #[test]
25615    fn contradictory_or_unrelated_command_evidence_is_rejected_while_mid_investigation_retry_passes()
25616     {
25617        let text = valid_noop_summary("b32cfc4", "retry_test");
25618
25619        // Unrelated passing command cannot substantiate a claimed test run.
25620        let err = evaluate_noop_claim(
25621            true,
25622            &[evidence_with("git status", Some(0), "nothing to commit")],
25623            &text,
25624        )
25625        .unwrap_err();
25626        assert!(err.contains("no matching command was recorded"), "{err}");
25627
25628        // Final matching command exited non-zero -> rejected even if an
25629        // unrelated command succeeded afterward.
25630        let err = evaluate_noop_claim(
25631            true,
25632            &[
25633                evidence_with("cargo test --lib retry_test", Some(0), "ok"),
25634                evidence_with("cargo test --lib retry_test", Some(101), "FAILED"),
25635                evidence_with("rg retry_test src", Some(0), "retry_test"),
25636            ],
25637            &text,
25638        )
25639        .unwrap_err();
25640        assert!(err.contains("exited with"), "{err}");
25641
25642        // A different invocation containing the entire method is not a rerun.
25643        let err = evaluate_noop_claim(
25644            true,
25645            &[evidence_with(
25646                "echo 'cargo test --lib retry_test'",
25647                Some(0),
25648                "retry_test",
25649            )],
25650            &text,
25651        )
25652        .unwrap_err();
25653        assert!(err.contains("no matching command was recorded"), "{err}");
25654
25655        // Mid-investigation failure followed by a passing re-run -> accepted!
25656        assert!(
25657            verified_noop_claim(
25658                true,
25659                &[
25660                    evidence_with("cargo test --lib retry_test", Some(101), "FAILED"),
25661                    evidence_with("cargo test --lib retry_test", Some(0), "1 passed"),
25662                ],
25663                &text
25664            )
25665            .is_some()
25666        );
25667    }
25668
25669    #[test]
25670    fn noop_test_claim_rejects_zero_tests_and_failed_results_despite_successful_exit() {
25671        let text = valid_noop_summary("b32cfc4", "retry_test");
25672        let method = "cargo test --lib retry_test";
25673        let empty = "running 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 42 filtered out";
25674        let ignored = "test result: ok. 0 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out";
25675        let failed =
25676            "test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out";
25677        let passed = "test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out";
25678        for output in [empty, ignored, failed] {
25679            let err = evaluate_noop_claim(true, &[evidence_with(method, Some(0), output)], &text)
25680                .unwrap_err();
25681            assert!(err.contains("failure or no passing tests"), "{err}");
25682        }
25683        // Multiple harnesses can legitimately include a filtered-out suite.
25684        let mixed = format!("{passed}\n{empty}");
25685        assert!(
25686            verified_noop_claim(true, &[evidence_with(method, Some(0), &mixed)], &text).is_some()
25687        );
25688        // A later real rerun of the same command can establish success.
25689        assert!(
25690            verified_noop_claim(
25691                true,
25692                &[
25693                    evidence_with(method, Some(0), empty),
25694                    evidence_with(method, Some(0), passed),
25695                ],
25696                &text,
25697            )
25698            .is_some()
25699        );
25700    }
25701
25702    #[test]
25703    fn path_claim_requires_matching_successful_command_when_commands_are_recorded() {
25704        let text = r#"NO CHANGE NEEDED: {"status":"already_satisfied","requirements":[{"requirement":"README includes the expected header","satisfied":true,"evidence":["p1"]}],"checks":[{"id":"p1","kind":"path","target":"README.md","method":"rg expected README.md","observed":"expected header found","passed":true}],"unresolved":[]}"#;
25705        let failed = evidence_with("rg expected README.md", Some(1), "");
25706        let unrelated = evidence_with("cat README.md", Some(0), "README");
25707        let err =
25708            evaluate_noop_claim(true, &[failed.clone(), unrelated.clone()], text).unwrap_err();
25709        assert!(err.contains("exited with"), "{err}");
25710        assert!(evaluate_noop_claim(true, &[unrelated], text).is_err());
25711        assert!(
25712            evaluate_noop_claim(
25713                true,
25714                &[
25715                    failed,
25716                    evidence_with("rg expected README.md", Some(0), "expected header"),
25717                ],
25718                text,
25719            )
25720            .unwrap()
25721            .is_some()
25722        );
25723    }
25724
25725    #[test]
25726    fn an_ordinary_reply_with_no_marker_is_never_a_claim() {
25727        assert!(verified_noop_claim(true, &[], "- did the thing\n- tested it").is_none());
25728        assert!(matches!(
25729            evaluate_noop_claim(true, &[], "- did the thing\n- tested it"),
25730            Ok(None)
25731        ));
25732    }
25733
25734    #[tokio::test]
25735    async fn repo_cross_verification_validates_commits_and_worktree_paths() {
25736        let tmp = tempfile::tempdir().unwrap();
25737        let repo = tmp.path().join("repo");
25738        std::fs::create_dir_all(&repo).unwrap();
25739        let run_git = |args: &[&str]| {
25740            let out = std::process::Command::new("git")
25741                .args(args)
25742                .current_dir(&repo)
25743                .output()
25744                .unwrap();
25745            assert!(out.status.success(), "git {args:?} failed");
25746            String::from_utf8_lossy(&out.stdout).trim().to_owned()
25747        };
25748        run_git(&["init", "-b", "main"]);
25749        run_git(&["config", "user.name", "test"]);
25750        run_git(&["config", "user.email", "test@example.com"]);
25751        std::fs::write(repo.join("README.md"), "hello\n").unwrap();
25752        run_git(&["add", "-A"]);
25753        run_git(&["commit", "-m", "base commit"]);
25754        let base = run_git(&["rev-parse", "HEAD"]);
25755
25756        // Create a commit on a side branch not on `base`.
25757        run_git(&["checkout", "-b", "side"]);
25758        std::fs::write(repo.join("side.txt"), "side\n").unwrap();
25759        run_git(&["add", "-A"]);
25760        run_git(&["commit", "-m", "side commit"]);
25761        let side = run_git(&["rev-parse", "HEAD"]);
25762        run_git(&["checkout", "main"]);
25763
25764        // Valid commit on base + existing path -> Accepted.
25765        let valid = format!(
25766            r#"NO CHANGE NEEDED: {{"status":"already_satisfied","requirements":[{{"requirement":"readme exists","satisfied":true,"evidence":["c1","c2"]}}],"checks":[{{"id":"c1","kind":"commit","target":"{base}","method":"git merge-base --is-ancestor {base} HEAD","observed":"exit 0; base commit is on main","passed":true}},{{"id":"c2","kind":"path","target":"README.md:1","method":"read README.md","observed":"contains expected greeting","passed":true}}],"unresolved":[]}}"#
25767        );
25768        assert!(matches!(
25769            verified_noop_claim_in_worktree(true, &[], &valid, &repo, &base).await,
25770            NoopClaimVerdict::Accepted
25771        ));
25772
25773        // Non-existent commit SHA -> Rejected.
25774        let missing_sha = valid.replace(&base, "deadbeef");
25775        assert!(matches!(
25776            verified_noop_claim_in_worktree(true, &[], &missing_sha, &repo, &base).await,
25777            NoopClaimVerdict::Rejected(ref r) if r.contains("does not exist in git history")
25778        ));
25779
25780        // Commit on unmerged side branch -> Rejected.
25781        let side_sha = valid.replace(&base, &side);
25782        assert!(matches!(
25783            verified_noop_claim_in_worktree(true, &[], &side_sha, &repo, &base).await,
25784            NoopClaimVerdict::Rejected(ref r) if r.contains("not an ancestor of base commit")
25785        ));
25786
25787        // Missing file path -> Rejected.
25788        let missing_path = valid.replace("README.md:1", "src/does_not_exist.rs");
25789        assert!(matches!(
25790            verified_noop_claim_in_worktree(true, &[], &missing_path, &repo, &base).await,
25791            NoopClaimVerdict::Rejected(ref r) if r.contains("does not exist in the worktree")
25792        ));
25793    }
25794
25795    /// Sets `runner.state.candidates` to one candidate per `(empty, verified)`
25796    /// pair, in order, labelled A, B, C, ...
25797    fn set_candidates(runner: &mut Runner, shape: &[(bool, Option<&str>)]) {
25798        runner.state.candidates = shape
25799            .iter()
25800            .enumerate()
25801            .map(|(i, &(empty, verified))| {
25802                let (summary, verified_noop) = match verified {
25803                    Some(raw) => (raw.to_owned(), Some(raw.to_owned())),
25804                    None => (String::new(), None),
25805                };
25806                Candidate {
25807                    index: i,
25808                    label: (b'A' + i as u8) as char,
25809                    agent: "sonnet".to_owned(),
25810                    branch: format!("magi/x/{}", (b'A' + i as u8) as char),
25811                    worktree: PathBuf::from(format!("/wt/{i}")),
25812                    summary,
25813                    stat: String::new(),
25814                    files: 0,
25815                    commits: 0,
25816                    empty,
25817                    failed: None,
25818                    verified_noop,
25819                    duration_ms: 0,
25820                    folded: false,
25821                }
25822            })
25823            .collect();
25824    }
25825
25826    #[test]
25827    fn after_implement_reads_all_candidates_verified_as_a_noop_not_a_failure() {
25828        ask_test_home();
25829        let mut runner = runner_at(RunStatus::Implementing);
25830        let a = valid_noop_summary("b32cfc4", "test_a");
25831        let b = valid_noop_summary("b32cfc4", "test_b");
25832        set_candidates(
25833            &mut runner,
25834            &[(true, Some(a.as_str())), (true, Some(b.as_str()))],
25835        );
25836
25837        runner
25838            .after_implement()
25839            .expect("a verified no-op is not an error");
25840
25841        assert_eq!(runner.state.status, RunStatus::VerifiedNoop);
25842    }
25843
25844    #[test]
25845    fn after_implement_does_not_accept_one_candidates_claim_next_to_an_ordinary_loss() {
25846        ask_test_home();
25847        let mut runner = runner_at(RunStatus::Implementing);
25848        let a = valid_noop_summary("b32cfc4", "test_a");
25849        // Candidate A declares a verified no-op; candidate B simply wrote
25850        // nothing and said nothing about why. One candidate's claim is not
25851        // the whole run's agreement.
25852        set_candidates(&mut runner, &[(true, Some(a.as_str())), (true, None)]);
25853
25854        let err = runner
25855            .after_implement()
25856            .expect_err("an unverified empty candidate must still fail the run");
25857
25858        assert!(
25859            err.to_string().contains("no candidate produced a change"),
25860            "{err}"
25861        );
25862        assert_eq!(runner.state.status, RunStatus::Failed);
25863    }
25864
25865    #[test]
25866    fn after_implement_invalidates_inconsistent_or_legacy_saved_noop_claims() {
25867        ask_test_home();
25868        let mut runner = runner_at(RunStatus::Implementing);
25869        // Simulate a saved incomplete run that stored a legacy/incomplete
25870        // `verified_noop` string before this build's strict contract.
25871        set_candidates(
25872            &mut runner,
25873            &[(
25874                true,
25875                Some(
25876                    "NO CHANGE NEEDED: Not established. The reported Git configuration lock contention remains unresolved.",
25877                ),
25878            )],
25879        );
25880
25881        let err = runner
25882            .after_implement()
25883            .expect_err("invalid saved noop claim must fail the run");
25884        assert!(
25885            err.to_string().contains("no candidate produced a change"),
25886            "{err}"
25887        );
25888        assert_eq!(runner.state.status, RunStatus::Failed);
25889        assert!(runner.state.candidates[0].verified_noop.is_none());
25890        assert!(runner.state.candidates[0].failed.is_some());
25891        assert!(runner.state.events.iter().any(|e| {
25892            e.message
25893                .contains("invalidated inconsistent saved NO CHANGE NEEDED")
25894        }));
25895    }
25896
25897    #[test]
25898    fn after_implement_rejects_candidate_with_failure_or_commits_on_verified_noop() {
25899        ask_test_home();
25900        let mut runner = runner_at(RunStatus::Implementing);
25901        let a = valid_noop_summary("b32cfc4", "test_a");
25902        set_candidates(&mut runner, &[(true, Some(a.as_str()))]);
25903        runner.state.candidates[0].failed = Some("agent timed out".to_owned());
25904
25905        let err = runner
25906            .after_implement()
25907            .expect_err("a failed candidate must never settle as verified no-op");
25908        assert!(err.to_string().contains("no candidate produced a change"));
25909        assert_eq!(runner.state.status, RunStatus::Failed);
25910        assert!(runner.state.candidates[0].verified_noop.is_none());
25911    }
25912
25913    #[test]
25914    fn after_implement_still_fails_an_ordinary_all_empty_run() {
25915        ask_test_home();
25916        let mut runner = runner_at(RunStatus::Implementing);
25917        set_candidates(&mut runner, &[(true, None), (true, None)]);
25918
25919        let err = runner
25920            .after_implement()
25921            .expect_err("no candidate declared anything; this is an ordinary failure");
25922
25923        assert!(
25924            err.to_string().contains("no candidate produced a change"),
25925            "{err}"
25926        );
25927        assert_eq!(runner.state.status, RunStatus::Failed);
25928    }
25929}
25930
25931/// A graft rollback whose restore could not be confirmed (see
25932/// [`Runner::graft`]).
25933#[derive(Debug)]
25934struct GraftRestoreFailed(String);
25935
25936impl std::fmt::Display for GraftRestoreFailed {
25937    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25938        write!(
25939            f,
25940            "could not restore the winner to its pre-graft commit: {}",
25941            self.0
25942        )
25943    }
25944}
25945
25946impl std::error::Error for GraftRestoreFailed {}
25947
25948/// The pre-spawn waits (shared build cache, parallelism slot) are infrastructure,
25949/// not the agent: they never draw on an agent's own timeout, and running out of
25950/// them never reads as an agent failure.
25951#[cfg(test)]
25952mod resource_wait_tests {
25953    use super::*;
25954    use std::collections::BTreeMap;
25955
25956    fn sh(id: &str, script: &str) -> AgentSpec {
25957        AgentSpec {
25958            id: id.to_owned(),
25959            kind: crate::config::AgentKind::Command,
25960            model: None,
25961            command: vec!["sh".to_owned(), "-c".to_owned(), script.to_owned()],
25962            extra_args: Vec::new(),
25963            env: BTreeMap::new(),
25964            prompt_delivery: None,
25965            max_turn_secs: None,
25966        }
25967    }
25968
25969    fn job(spec: AgentSpec, dir: &Path, timeout: Duration) -> SeatJob {
25970        SeatJob {
25971            seat: SeatState::new("impl-A", &spec.id, 1),
25972            spec,
25973            cwd: dir.to_path_buf(),
25974            prompt: "do it".to_owned(),
25975            timeout,
25976            allow_write: true,
25977            sessions: false,
25978            artifacts: dir.join("art"),
25979            stem: "impl-A".to_owned(),
25980            handover: None,
25981        }
25982    }
25983
25984    fn state(resource_wait_secs: u64) -> RunState {
25985        let mut config = Config::default();
25986        config.graph.timeout_resource_wait = resource_wait_secs;
25987        RunState::new(
25988            PathBuf::from("/repo"),
25989            "main".to_owned(),
25990            "abc1234".to_owned(),
25991            "task".to_owned(),
25992            config,
25993        )
25994    }
25995
25996    fn hold(cache: &Path) -> crate::cache::Guard {
25997        let owner = crate::cache::Owner::here("other-run", "e2e", "e2e", cache, "deadbeef");
25998        match crate::cache::try_acquire(&crate::run::home(), cache, &owner).expect("io") {
25999            crate::cache::AcquireOutcome::Acquired(g) => g,
26000            crate::cache::AcquireOutcome::Busy(b) => panic!("lease was not free: {b:?}"),
26001        }
26002    }
26003
26004    async fn run(
26005        jobs: Vec<SeatJob>,
26006        sem: Arc<Semaphore>,
26007        cache: Option<&Path>,
26008        st: &mut RunState,
26009    ) -> Vec<(usize, SeatState, AgentOutcome)> {
26010        let prompts = Prompts::default();
26011        let ctx = WaveCtx {
26012            run: "r",
26013            node: "implement",
26014            prompts: &prompts,
26015            cache,
26016            round: None,
26017            carry_seats: false,
26018            pauses: None,
26019        };
26020        wave(jobs, sem, &ctx, st, 0).await
26021    }
26022
26023    #[tokio::test]
26024    async fn isolated_editing_seat_wait_releases_only_after_its_own_target_is_free() {
26025        crate::run::pin_test_home();
26026        let home = crate::run::home();
26027        let tmp = tempfile::tempdir().unwrap();
26028        let repo = tmp.path().join("repo");
26029        let checkout = tmp.path().join("checkout");
26030        std::fs::create_dir(&repo).unwrap();
26031        git::git(&repo, &["init"]).await.unwrap();
26032        git::git(
26033            &repo,
26034            &[
26035                "-c",
26036                "user.name=Fixture",
26037                "-c",
26038                "user.email=fixture@example.invalid",
26039                "commit",
26040                "--allow-empty",
26041                "-m",
26042                "initial",
26043            ],
26044        )
26045        .await
26046        .unwrap();
26047        git::worktree_add_detached(&repo, &checkout, "HEAD")
26048            .await
26049            .unwrap();
26050        let target = crate::build_target::resolve(&home, &checkout).unwrap();
26051        let target_lease = hold(&target);
26052        let shared = tmp.path().join("unrelated");
26053        let _shared_lease = hold(&shared);
26054        let mut st = state(0);
26055        st.repo = repo.clone();
26056        st.config.verify.build_cache = crate::config::BuildCache::Isolated;
26057        st.config.verify.e2e = vec![format!(
26058            "CARGO_TARGET_DIR='{}' cargo test",
26059            git::path_arg(&shared)
26060        )];
26061        let config = tmp.path().join("config.toml");
26062        std::fs::write(&config, toml::to_string(&st.config).unwrap()).unwrap();
26063        let prompts = Prompts::default();
26064        let run_id = st.id.clone();
26065        let ctx = WaveCtx {
26066            run: &run_id,
26067            node: "implement",
26068            prompts: &prompts,
26069            cache: None,
26070            round: None,
26071            carry_seats: false,
26072            pauses: None,
26073        };
26074        let writer = job(sh("writer", "exit 99"), &checkout, Duration::from_secs(30));
26075        let results = wave(vec![writer], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0).await;
26076        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
26077        assert_eq!(results[0].1.turns, 0);
26078        let saved = RunState::load_under(&run_id, &home).unwrap();
26079        let block = saved.resource_block.unwrap();
26080        assert!(matches!(
26081            block.cause,
26082            crate::run::ResourceBlockCause::IsolatedCacheTimeout { target: ref actual, .. }
26083                if actual == &target
26084        ));
26085        let queue = crate::queue::Queue::at(tmp.path().join("queue"));
26086        let mut task = crate::queue::Task::new(
26087            "build".into(),
26088            "build".into(),
26089            repo,
26090            crate::queue::Source::Human,
26091        );
26092        task.runs.push(run_id);
26093        task.hold_machine(Some(format!(
26094            "{}{}",
26095            crate::cache::RESOURCE_HOLD,
26096            block.description()
26097        )));
26098        queue.put(&mut task).unwrap();
26099        let questions = crate::ask::Questions::at(tmp.path().join("questions"));
26100        let triage =
26101            || crate::triage::run_once(&queue, &questions, Some(&config), Timestamp::now());
26102        let pending = triage();
26103        assert!(pending.resumed.is_empty() && pending.asked.is_empty());
26104        assert_eq!(
26105            queue.get(&task.id).unwrap().status,
26106            crate::queue::TaskStatus::Held
26107        );
26108        drop(target_lease);
26109        assert_eq!(triage().resumed, vec![task.id.clone()]);
26110        assert_eq!(
26111            queue.get(&task.id).unwrap().status,
26112            crate::queue::TaskStatus::Queued
26113        );
26114        assert!(crate::cache::in_use(&home, &shared));
26115    }
26116
26117    #[tokio::test]
26118    async fn verification_cache_wait_preserves_the_command_budget() {
26119        crate::run::pin_test_home();
26120        let tmp = tempfile::tempdir().unwrap();
26121        let cache = tmp.path().join("target");
26122        let guard = hold(&cache);
26123        let release = tokio::spawn(async move {
26124            tokio::time::sleep(Duration::from_millis(100)).await;
26125            guard.release();
26126        });
26127        let mut st = state(10);
26128        let budget = Duration::from_millis(50);
26129        let wait = repository_wait(&st, None);
26130        let (outcomes, _) = with_cache_lease(
26131            &mut st,
26132            Some(&cache),
26133            "gate",
26134            "gate",
26135            tmp.path(),
26136            "abc1234",
26137            budget,
26138            "test gate",
26139            &wait,
26140            |_, available| async move {
26141                assert_eq!(
26142                    available, budget,
26143                    "contention must not shorten verification"
26144                );
26145                (Vec::new(), false, Vec::new())
26146            },
26147        )
26148        .await
26149        .unwrap();
26150        release.await.unwrap();
26151        assert!(outcomes.is_empty(), "{outcomes:?}");
26152        assert!(
26153            st.events
26154                .iter()
26155                .any(|event| event.message.contains("waiting for"))
26156        );
26157        assert!(st.resource_wait.is_none());
26158        // The verification body no longer owns the lease after returning.
26159        hold(&cache).release();
26160    }
26161
26162    #[tokio::test]
26163    async fn verification_cache_wait_expires_without_starting_commands() {
26164        crate::run::pin_test_home();
26165        let tmp = tempfile::tempdir().unwrap();
26166        let cache = tmp.path().join("target");
26167        let _held = hold(&cache);
26168        let mut st = state(0);
26169        let wait = repository_wait(&st, None);
26170        let (outcomes, _) = with_cache_lease(
26171            &mut st,
26172            Some(&cache),
26173            "gate",
26174            "gate",
26175            tmp.path(),
26176            "abc1234",
26177            Duration::from_secs(60),
26178            "test gate",
26179            &wait,
26180            |_, _| async { panic!("commands must not start without the cache lease") },
26181        )
26182        .await
26183        .unwrap();
26184        assert_eq!(outcomes.len(), 1);
26185        assert!(outcomes[0].resource_blocked);
26186        assert!(st.resource_wait.is_none());
26187        assert!(matches!(
26188            st.resource_block.unwrap().cause,
26189            crate::run::ResourceBlockCause::Timeout { limit_secs: 0, .. }
26190        ));
26191    }
26192
26193    #[tokio::test]
26194    async fn verification_resource_error_does_not_claim_an_elapsed_timeout() {
26195        crate::run::pin_test_home();
26196        let tmp = tempfile::tempdir().unwrap();
26197        std::fs::write(tmp.path().join("Cargo.toml"), "[invalid").unwrap();
26198        let cache = tmp.path().join("cache");
26199        let mut state = state(21600);
26200        let wait = repository_wait(&state, None);
26201        let (outcomes, _) = with_cache_lease(
26202            &mut state,
26203            Some(&cache),
26204            "gate",
26205            "gate",
26206            tmp.path(),
26207            "head",
26208            Duration::from_secs(60),
26209            "gate",
26210            &wait,
26211            |_, _| async { panic!("freshness failure must not start verification") },
26212        )
26213        .await
26214        .unwrap();
26215        assert_eq!(outcomes.len(), 1);
26216        assert!(outcomes[0].resource_blocked);
26217        let block = state.resource_block.unwrap();
26218        assert_eq!(block.cause, crate::run::ResourceBlockCause::Other);
26219        assert!(!block.description().contains("timed out"));
26220    }
26221
26222    #[tokio::test]
26223    async fn cancelled_cache_wait_preserves_the_park_cause_without_starting_an_agent() {
26224        crate::run::pin_test_home();
26225        let tmp = tempfile::tempdir().unwrap();
26226        let cache = tmp.path().join("cache");
26227        let _held = hold(&cache);
26228        let mut state = state(21600);
26229        let pause = Pause::new();
26230        let interrupt = Pause::new();
26231        let cause = ParkCause::Operator;
26232        pause.park_for(cause.clone());
26233        let prompts = Prompts::default();
26234        let ctx = WaveCtx {
26235            run: "test",
26236            node: "fix",
26237            prompts: &prompts,
26238            cache: Some(&cache),
26239            round: None,
26240            carry_seats: false,
26241            pauses: Some((&pause, &interrupt)),
26242        };
26243        let result = wave(
26244            vec![job(
26245                sh("writer", "exit 99"),
26246                tmp.path(),
26247                Duration::from_secs(1),
26248            )],
26249            Arc::new(Semaphore::new(1)),
26250            &ctx,
26251            &mut state,
26252            0,
26253        )
26254        .await;
26255        assert!(matches!(result[0].2, AgentOutcome::ResourceBlocked(_)));
26256        assert_eq!(result[0].1.turns, 0);
26257        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
26258        assert_eq!(
26259            state.resource_block.unwrap().cause,
26260            crate::run::ResourceBlockCause::Cancelled { park: Some(cause) }
26261        );
26262        assert!(state.active.is_empty());
26263    }
26264
26265    #[tokio::test]
26266    async fn a_cache_wait_longer_than_the_agent_budget_leaves_the_budget_whole() {
26267        crate::run::pin_test_home();
26268        let tmp = tempfile::tempdir().unwrap();
26269        let cache = tmp.path().join("target-a");
26270        let guard = hold(&cache);
26271        // Held for longer than the agent's whole 1s budget.
26272        tokio::spawn(async move {
26273            tokio::time::sleep(Duration::from_millis(1500)).await;
26274            guard.release();
26275        });
26276        let mut st = state(60);
26277        let results = run(
26278            vec![job(
26279                sh("alpha", "echo ok"),
26280                tmp.path(),
26281                Duration::from_secs(1),
26282            )],
26283            Arc::new(Semaphore::new(1)),
26284            Some(&cache),
26285            &mut st,
26286        )
26287        .await;
26288        assert!(
26289            matches!(results[0].2, AgentOutcome::Ok(_)),
26290            "the wait must not be charged to the agent"
26291        );
26292        assert!(st.resource_block.is_none());
26293        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
26294        assert!(st.resource_wait.is_none() && st.active.is_empty());
26295    }
26296
26297    #[tokio::test]
26298    #[cfg(unix)]
26299    async fn repository_wait_in_a_wave_is_a_bounded_cancellable_resource_block() {
26300        use std::os::fd::AsRawFd as _;
26301        crate::run::pin_test_home();
26302        let tmp = tempfile::tempdir().unwrap();
26303        crate::git::git(tmp.path(), &["init"]).await.unwrap();
26304        let common = tmp.path().join(".git");
26305        std::fs::write(common.join("updater.contract"), "test-protocol-v1\n").unwrap();
26306        let external = std::fs::File::create(common.join("updater.lock")).unwrap();
26307        assert_eq!(
26308            unsafe { libc::flock(external.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
26309            0
26310        );
26311        let mut st = state(1);
26312        st.config.coordination = crate::config::test_coordination();
26313        let mut reader = job(
26314            sh("reader", "echo must-not-run"),
26315            tmp.path(),
26316            Duration::from_secs(30),
26317        );
26318        reader.allow_write = false;
26319        let results = run(
26320            vec![reader.clone()],
26321            Arc::new(Semaphore::new(1)),
26322            None,
26323            &mut st,
26324        )
26325        .await;
26326        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
26327        assert_eq!(results[0].1.turns, 0);
26328        assert!(FailClass::of(&results[0].2).is_none());
26329        assert_eq!(
26330            st.resource_block.as_ref().unwrap().kind,
26331            "repository coordination"
26332        );
26333        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
26334        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
26335        drop(external);
26336        let editor = crate::repo_lock::SeatLease::for_checkout(
26337            tmp.path(),
26338            true,
26339            crate::config::test_coordination().as_ref(),
26340        )
26341        .await
26342        .unwrap();
26343        let pause = Pause::new();
26344        let interrupt = Pause::new();
26345        let prompts = Prompts::default();
26346        let ctx = WaveCtx {
26347            run: "r",
26348            node: "review",
26349            prompts: &prompts,
26350            cache: None,
26351            round: None,
26352            carry_seats: false,
26353            pauses: Some((&pause, &interrupt)),
26354        };
26355        let (results, ()) = tokio::join!(
26356            wave(vec![reader], Arc::new(Semaphore::new(1)), &ctx, &mut st, 0),
26357            async {
26358                tokio::time::sleep(Duration::from_millis(50)).await;
26359                pause.park();
26360            }
26361        );
26362        assert!(
26363            matches!(&results[0].2, AgentOutcome::ResourceBlocked(why) if why.contains("parking"))
26364        );
26365        assert_eq!(results[0].1.turns, 0);
26366        assert!(st.active.is_empty() && st.quota.is_empty() && st.handovers.is_empty());
26367        assert!(!tmp.path().join("art/impl-A.prompt.md").exists());
26368        drop(editor);
26369    }
26370
26371    #[tokio::test]
26372    async fn an_expired_cache_wait_blocks_without_asking_or_rotating_the_agent() {
26373        crate::run::pin_test_home();
26374        let tmp = tempfile::tempdir().unwrap();
26375        let cache = tmp.path().join("target-b");
26376        let _held = hold(&cache);
26377        let mut st = state(1);
26378        let results = run(
26379            vec![job(
26380                sh("alpha", "echo ok"),
26381                tmp.path(),
26382                Duration::from_secs(1),
26383            )],
26384            Arc::new(Semaphore::new(1)),
26385            Some(&cache),
26386            &mut st,
26387        )
26388        .await;
26389        let (_, seat, out) = &results[0];
26390        assert!(matches!(out, AgentOutcome::ResourceBlocked(_)));
26391        assert!(wave_blocked(&results));
26392        assert_eq!(seat.agent, "alpha", "the chosen agent is kept");
26393        assert_eq!(seat.turns, 0, "nothing was asked");
26394        assert!(
26395            !tmp.path().join("art").join("impl-A.prompt.md").exists(),
26396            "no agent was spawned"
26397        );
26398        assert!(FailClass::of(out).is_none(), "not a failure class");
26399        let block = st.resource_block.as_ref().expect("recorded for the resume");
26400        assert_eq!(block.kind, "shared build cache");
26401        assert!(matches!(
26402            block.cause,
26403            crate::run::ResourceBlockCause::Timeout { limit_secs: 1, .. }
26404        ));
26405        assert!(st.handovers.is_empty() && st.seat_history.is_empty() && st.quota.is_empty());
26406        assert!(st.active.is_empty());
26407    }
26408
26409    #[tokio::test]
26410    async fn a_semaphore_with_no_permits_ends_as_a_bounded_resource_block() {
26411        crate::run::pin_test_home();
26412        let tmp = tempfile::tempdir().unwrap();
26413        let mut st = state(1);
26414        let results = run(
26415            vec![job(
26416                sh("alpha", "echo ok"),
26417                tmp.path(),
26418                Duration::from_secs(1),
26419            )],
26420            Arc::new(Semaphore::new(0)),
26421            None,
26422            &mut st,
26423        )
26424        .await;
26425        assert!(matches!(results[0].2, AgentOutcome::ResourceBlocked(_)));
26426        assert_eq!(st.resource_block.as_ref().unwrap().kind, "parallel slot");
26427        assert!(!tmp.path().join("art").join("impl-A.prompt.md").exists());
26428    }
26429
26430    #[tokio::test]
26431    async fn an_agent_that_really_hangs_still_times_out_and_hands_over() {
26432        crate::run::pin_test_home();
26433        let tmp = tempfile::tempdir().unwrap();
26434        let mut st = state(60);
26435        let results = run(
26436            vec![job(
26437                sh("alpha", "sleep 30"),
26438                tmp.path(),
26439                Duration::from_secs(1),
26440            )],
26441            Arc::new(Semaphore::new(1)),
26442            None,
26443            &mut st,
26444        )
26445        .await;
26446        let out = &results[0].2;
26447        assert!(matches!(out, AgentOutcome::Failed(e) if e == TIMED_OUT));
26448        let class = FailClass::of(out).expect("a failure");
26449        assert_eq!(class, FailClass::Timeout);
26450        assert!(should_hand_over(None, &class), "existing handover policy");
26451        assert!(st.resource_block.is_none());
26452    }
26453}